repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
internal/util/util.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L368-L381
go
train
// ParseSections returns INI style sections from r.
func ParseSections(r io.Reader) (sections []string, err error)
// ParseSections returns INI style sections from r. func ParseSections(r io.Reader) (sections []string, err error)
{ s := bufio.NewScanner(r) for s.Scan() { t := s.Text() if strings.HasPrefix(t, "[") { sections = append(sections, strings.Trim(t, "[]")) } } err = s.Err() return }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cost/cost.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cost/cost.go#L50-L52
go
train
// Cost returns the total cost.
func Cost(requests, ms, memory int) float64
// Cost returns the total cost. func Cost(requests, ms, memory int) float64
{ return RequestCost(requests) + DurationCost(ms, memory) }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
infra/tfvars.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/infra/tfvars.go#L19-L53
go
train
// functionVars returns the function variables as terraform -var arguments.
func (p *Proxy) functionVars() (args []string)
// functionVars returns the function variables as terraform -var arguments. func (p *Proxy) functionVars() (args []string)
{ args = append(args, "-var") args = append(args, fmt.Sprintf("aws_region=%s", p.Region)) args = append(args, "-var") args = append(args, fmt.Sprintf("apex_environment=%s", p.Environment)) if p.Role != "" { args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_role=%s", p.Role)) } // GetConfig is slow, so store the results and then use the configurations as needed var relations []ConfigRelation for _, fn := range p.Functions { config, err := fn.GetConfig() if err != nil { log.Debugf("can't fetch function config: %s", err.Error()) continue } var relation ConfigRelation relation.Function = fn relation.Configuration = config.Configuration relations = append(relations, relation) } args = append(args, getFunctionArnVars(relations)...) args = append(args, getFunctionNameVars(relations)...) args = append(args, getFunctionArns(relations)...) args = append(args, getFunctionNames(relations)...) return args }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
infra/tfvars.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/infra/tfvars.go#L57-L64
go
train
// Generate a series of variables apex_function_FUNCTION that contains the arn of the functions // This function is being phased out in favour of apex_function_arns
func getFunctionArnVars(relations []ConfigRelation) (args []string)
// Generate a series of variables apex_function_FUNCTION that contains the arn of the functions // This function is being phased out in favour of apex_function_arns func getFunctionArnVars(relations []ConfigRelation) (args []string)
{ log.Debugf("Generating the tfvar apex_function_FUNCTION") for _, rel := range relations { args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_%s=%s", rel.Function.Name, *rel.Configuration.FunctionArn)) } return args }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
infra/tfvars.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/infra/tfvars.go#L78-L87
go
train
// Generates a map that has the function's name as a key and the arn of the function as a value
func getFunctionArns(relations []ConfigRelation) (args []string)
// Generates a map that has the function's name as a key and the arn of the function as a value func getFunctionArns(relations []ConfigRelation) (args []string)
{ log.Debugf("Generating the tfvar apex_function_arns") var arns []string for _, rel := range relations { arns = append(arns, fmt.Sprintf("%s = %q", rel.Function.Name, *rel.Configuration.FunctionArn)) } args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_arns={ %s }", strings.Join(arns, ", "))) return args }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
infra/tfvars.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/infra/tfvars.go#L90-L99
go
train
// Generates a map that has the function's name as a key and the full name of the function as a value
func getFunctionNames(relations []ConfigRelation) (args []string)
// Generates a map that has the function's name as a key and the full name of the function as a value func getFunctionNames(relations []ConfigRelation) (args []string)
{ log.Debugf("Generating the tfvar apex_function_names") var names []string for _, rel := range relations { names = append(names, fmt.Sprintf("%s = %q", rel.Function.Name, rel.Function.FunctionName)) } args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_names={ %s }", strings.Join(names, ", "))) return args }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
exec/exec.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/exec/exec.go#L23-L37
go
train
// Run command in specified directory.
func (p *Proxy) Run(command string, args ...string) error
// Run command in specified directory. func (p *Proxy) Run(command string, args ...string) error
{ log.WithFields(log.Fields{ "command": command, "args": args, }).Debug("exec") cmd := exec.Command(command, args...) cmd.Env = append(os.Environ(), p.functionEnvVars()...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Dir = p.Dir return cmd.Run() }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
plugins/clojure/clojure.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/plugins/clojure/clojure.go#L34-L56
go
train
// Open adds the shim and golang defaults.
func (p *Plugin) Open(fn *function.Function) error
// Open adds the shim and golang defaults. func (p *Plugin) Open(fn *function.Function) error
{ if !strings.HasPrefix(fn.Runtime, "clojure") { return nil } if fn.Hooks.Build == "" { fn.Hooks.Build = "lein uberjar && mv target/*-standalone.jar target/apex.jar" } if fn.Hooks.Clean == "" { fn.Hooks.Clean = "rm -fr target" } if _, err := os.Stat(".apexignore"); err != nil { // Since we're deploying a fat jar, we don't need anything else. fn.IgnoreFile = []byte(` * !**/apex.jar `) } return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
plugins/clojure/clojure.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/plugins/clojure/clojure.go#L59-L99
go
train
// Build adds the jar contents to zipfile.
func (p *Plugin) Build(fn *function.Function, zip *archive.Zip) error
// Build adds the jar contents to zipfile. func (p *Plugin) Build(fn *function.Function, zip *archive.Zip) error
{ if !strings.HasPrefix(fn.Runtime, "clojure") { return nil } jar := filepath.Join(fn.Path, "target", jarFile) if _, err := os.Stat(jar); err != nil { return errors.Errorf("missing jar file %q", jar) } fn.Log.Debug("appending compiled files") reader, err := azip.OpenReader(jar) if err != nil { return errors.Wrap(err, "opening zip") } defer reader.Close() for _, file := range reader.File { parts := strings.Split(file.Name, ".") ext := parts[len(parts)-1] if ext == "clj" || ext == "cljx" || ext == "cljc" { continue } r, err := file.Open() if err != nil { return errors.Wrap(err, "opening file") } b, err := ioutil.ReadAll(r) if err != nil { return errors.Wrap(err, "reading file") } r.Close() zip.AddBytes(file.Name, b) } return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/deploy/deploy.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/deploy/deploy.go#L57-L66
go
train
// Initialize.
func init()
// Initialize. func init()
{ root.Register(Command) f := Command.Flags() f.StringSliceVarP(&env, "set", "s", nil, "Set environment variable") f.StringVarP(&envFile, "env-file", "E", "", "Set environment variables from JSON file") f.StringVarP(&alias, "alias", "a", "current", "Function alias") f.StringVarP(&zip, "zip", "z", "", "Zip path") f.IntVarP(&concurrency, "concurrency", "c", 5, "Concurrent deploys") }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/deploy/deploy.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/deploy/deploy.go#L69-L94
go
train
// Run command.
func run(c *cobra.Command, args []string) error
// Run command. func run(c *cobra.Command, args []string) error
{ root.Project.Concurrency = concurrency root.Project.Alias = alias root.Project.Zip = zip if err := root.Project.LoadFunctions(args...); err != nil { return err } if envFile != "" { if err := root.Project.LoadEnvFromFile(envFile); err != nil { return fmt.Errorf("reading env file %q: %s", envFile, err) } } vars, err := utils.ParseEnv(env) if err != nil { return err } for k, v := range vars { root.Project.Setenv(k, v) } return root.Project.DeployAndClean() }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/docs/docs.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/docs/docs.go#L30-L53
go
train
// Run command.
func run(c *cobra.Command, args []string) (err error)
// Run command. func run(c *cobra.Command, args []string) (err error)
{ var w io.WriteCloser = os.Stdout if isatty.IsTerminal(os.Stdout.Fd()) { cmd := exec.Command("less", "-R") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr defer cmd.Wait() w, err = cmd.StdinPipe() if err != nil { return err } defer w.Close() if err := cmd.Start(); err != nil { return err } } _, err = io.Copy(w, doc.Reader()) return err }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
metrics/metrics.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/metrics/metrics.go#L33-L46
go
train
// Collect and aggregate metrics for multiple functions.
func (m *Metrics) Collect() (a map[string]AggregatedMetrics)
// Collect and aggregate metrics for multiple functions. func (m *Metrics) Collect() (a map[string]AggregatedMetrics)
{ a = make(map[string]AggregatedMetrics) for _, fnName := range m.FunctionNames { metric := Metric{ Config: m.Config, FunctionName: fnName, } a[fnName] = metric.Collect() } return }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/autocomplete/autocomplete.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/autocomplete/autocomplete.go#L43-L70
go
train
// Run command.
func run(c *cobra.Command, args []string)
// Run command. func run(c *cobra.Command, args []string)
{ // TODO: works with flags inbetween? if len(args) == 0 { rootCommands() flags(root.Command) return } // find command, on error assume it's in-complete // or missing and all root commands are shown cmd := find(args[0]) if cmd == nil { rootCommands() flags(root.Command) return } // command flags flags(cmd) // always show root flags flags(root.Command) // command accepts functions if ok := funcCommands[cmd.Name()]; ok { functions(args) } }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/autocomplete/autocomplete.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/autocomplete/autocomplete.go#L73-L80
go
train
// find command by `name`.
func find(name string) *cobra.Command
// find command by `name`. func find(name string) *cobra.Command
{ for _, cmd := range root.Command.Commands() { if cmd.Name() == name { return cmd } } return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/autocomplete/autocomplete.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/autocomplete/autocomplete.go#L83-L89
go
train
// output root commands.
func rootCommands()
// output root commands. func rootCommands()
{ for _, cmd := range root.Command.Commands() { if !cmd.Hidden { fmt.Printf("%s ", cmd.Name()) } } }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/autocomplete/autocomplete.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/autocomplete/autocomplete.go#L92-L98
go
train
// output flags.
func flags(cmd *cobra.Command)
// output flags. func flags(cmd *cobra.Command)
{ cmd.Flags().VisitAll(func(f *flag.Flag) { if !f.Hidden { fmt.Printf("--%s ", f.Name) } }) }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/autocomplete/autocomplete.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/autocomplete/autocomplete.go#L101-L112
go
train
// output (deduped) functions.
func functions(args []string)
// output (deduped) functions. func functions(args []string)
{ files, err := ioutil.ReadDir("functions") if err != nil { return } for _, file := range files { if !utils.ContainsString(args, file.Name()) { fmt.Printf("%s ", file.Name()) } } }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
plugins/inference/inference.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/plugins/inference/inference.go#L35-L51
go
train
// Open checks for files in the function directory to infer its runtime.
func (p *Plugin) Open(fn *function.Function) error
// Open checks for files in the function directory to infer its runtime. func (p *Plugin) Open(fn *function.Function) error
{ if fn.Runtime != "" { return nil } fn.Log.Debug("inferring runtime") for name, runtime := range p.Files { if _, err := os.Stat(filepath.Join(fn.Path, name)); err == nil { fn.Log.WithField("runtime", runtime).Debug("inferred runtime") fn.Runtime = runtime return nil } } return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
service/provider.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/service/provider.go#L24-L29
go
train
// NewProvider with session and dry run
func NewProvider(session *session.Session, dryRun bool) Provideriface
// NewProvider with session and dry run func NewProvider(session *session.Session, dryRun bool) Provideriface
{ return &Provider{ Session: session, DryRun: dryRun, } }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
service/provider.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/service/provider.go#L32-L40
go
train
// NewService returns Lambda service with AWS config
func (p *Provider) NewService(cfg *aws.Config) lambdaiface.LambdaAPI
// NewService returns Lambda service with AWS config func (p *Provider) NewService(cfg *aws.Config) lambdaiface.LambdaAPI
{ if p.DryRun { return dryrun.New(p.Session) } else if cfg != nil { return lambda.New(p.Session, cfg) } else { return lambda.New(p.Session) } }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/alias/alias.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/alias/alias.go#L63-L69
go
train
// Run command.
func run(c *cobra.Command, args []string) error
// Run command. func run(c *cobra.Command, args []string) error
{ if err := root.Project.LoadFunctions(args[1:]...); err != nil { return err } return root.Project.CreateOrUpdateAlias(alias, version) }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
plugins/shim/shim.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/plugins/shim/shim.go#L19-L33
go
train
// Build adds the nodejs shim files.
func (p *Plugin) Build(fn *function.Function, zip *archive.Zip) error
// Build adds the nodejs shim files. func (p *Plugin) Build(fn *function.Function, zip *archive.Zip) error
{ if fn.Shim { fn.Log.Debug("add shim") if err := zip.AddBytes("index.js", shim.MustAsset("index.js")); err != nil { return err } if err := zip.AddBytes("byline.js", shim.MustAsset("byline.js")); err != nil { return err } } return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/list/list.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/list/list.go#L38-L43
go
train
// Initialize.
func init()
// Initialize. func init()
{ root.Register(Command) f := Command.Flags() f.BoolVar(&tfvars, "tfvars", false, "Output as Terraform variables") }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/list/list.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/list/list.go#L46-L58
go
train
// Run command.
func run(c *cobra.Command, args []string) error
// Run command. func run(c *cobra.Command, args []string) error
{ if err := root.Project.LoadFunctions(args...); err != nil { return err } if tfvars { outputTFvars() } else { outputList() } return nil }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/list/list.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/list/list.go#L61-L71
go
train
// outputTFvars format.
func outputTFvars()
// outputTFvars format. func outputTFvars()
{ for _, fn := range root.Project.Functions { config, err := fn.GetConfig() if err != nil { log.Debugf("can't fetch function config: %s", err.Error()) continue } fmt.Printf("apex_function_%s=%q\n", fn.Name, *config.Configuration.FunctionArn) } }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/list/list.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/list/list.go#L74-L120
go
train
// outputList format.
func outputList()
// outputList format. func outputList()
{ fmt.Println() for _, fn := range root.Project.Functions { awsFn, err := fn.GetConfigCurrent() if awserr, ok := err.(awserr.Error); ok && awserr.Code() == "ResourceNotFoundException" { fmt.Printf(" \033[%dm%s\033[0m (not deployed) \n", colors.Blue, fn.Name) } else { fmt.Printf(" \033[%dm%s\033[0m\n", colors.Blue, fn.Name) } if fn.Description != "" { fmt.Printf(" description: %v\n", fn.Description) } fmt.Printf(" runtime: %v\n", fn.Runtime) fmt.Printf(" memory: %vmb\n", fn.Memory) fmt.Printf(" timeout: %vs\n", fn.Timeout) fmt.Printf(" role: %v\n", fn.Role) fmt.Printf(" handler: %v\n", fn.Handler) if awsFn != nil && awsFn.Configuration != nil && awsFn.Configuration.FunctionArn != nil { fmt.Printf(" arn: %v\n", *awsFn.Configuration.FunctionArn) } if err != nil { fmt.Println() continue // ignore } aliaslist, err := fn.GetAliases() if err != nil { continue } var aliases string for index, alias := range aliaslist.Aliases { if index > 0 { aliases += ", " } aliases += fmt.Sprintf("%s@v%s", *alias.Name, *alias.FunctionVersion) } if aliases == "" { aliases = "<none>" } fmt.Printf(" aliases: %s\n", aliases) fmt.Println() } }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/build/build.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/build/build.go#L40-L46
go
train
// Initialize.
func init()
// Initialize. func init()
{ root.Register(Command) f := Command.Flags() f.StringVarP(&envFile, "env-file", "E", "", "Set environment variables from JSON file") f.StringSliceVarP(&env, "set", "s", nil, "Set environment variable") }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/build/build.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/build/build.go#L59-L92
go
train
// Run command.
func run(c *cobra.Command, args []string) error
// Run command. func run(c *cobra.Command, args []string) error
{ if err := root.Project.LoadFunctions(name); err != nil { return err } fn := root.Project.Functions[0] if envFile != "" { if err := root.Project.LoadEnvFromFile(envFile); err != nil { return fmt.Errorf("reading env file %q: %s", envFile, err) } } vars, err := utils.ParseEnv(env) if err != nil { return err } for k, v := range vars { root.Project.Setenv(k, v) } zip, err := fn.Build() if err != nil { return err } if err := fn.Clean(); err != nil { return err } _, err = io.Copy(os.Stdout, zip) return err }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/exec/exec.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/exec/exec.go#L31-L35
go
train
// Initialize.
func init()
// Initialize. func init()
{ root.Register(Command) f := Command.Flags() f.StringVarP(&dir, "dir", "d", "", "Which directory to execute command from") }
apex/apex
c31f0a78ce189a8328563fa6a6eb97d04ace4284
cmd/apex/exec/exec.go
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/exec/exec.go#L38-L71
go
train
// Run command.
func run(c *cobra.Command, args []string) error
// Run command. func run(c *cobra.Command, args []string) error
{ var command string if dir == "" { pwd, err := os.Getwd() if err != nil { return err } dir = pwd } if len(args) > 0 { command = args[0] args = args[1:] } else { return errors.New("No command specified") } err := root.Project.LoadFunctions() if err != nil { return err } p := &exec.Proxy{ Functions: root.Project.Functions, Region: *root.Session.Config.Region, Environment: root.Project.InfraEnvironment, Role: root.Project.Role, Dir: dir, } return p.Run(command, args...) }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
fec.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/fec.go#L68-L175
go
train
// decode a fec packet
func (dec *fecDecoder) decode(in fecPacket) (recovered [][]byte)
// decode a fec packet func (dec *fecDecoder) decode(in fecPacket) (recovered [][]byte)
{ // insertion n := len(dec.rx) - 1 insertIdx := 0 for i := n; i >= 0; i-- { if in.seqid() == dec.rx[i].seqid() { // de-duplicate return nil } else if _itimediff(in.seqid(), dec.rx[i].seqid()) > 0 { // insertion insertIdx = i + 1 break } } // make a copy pkt := fecPacket(xmitBuf.Get().([]byte)[:len(in)]) copy(pkt, in) // insert into ordered rx queue if insertIdx == n+1 { dec.rx = append(dec.rx, pkt) } else { dec.rx = append(dec.rx, fecPacket{}) copy(dec.rx[insertIdx+1:], dec.rx[insertIdx:]) // shift right dec.rx[insertIdx] = pkt } // shard range for current packet shardBegin := pkt.seqid() - pkt.seqid()%uint32(dec.shardSize) shardEnd := shardBegin + uint32(dec.shardSize) - 1 // max search range in ordered queue for current shard searchBegin := insertIdx - int(pkt.seqid()%uint32(dec.shardSize)) if searchBegin < 0 { searchBegin = 0 } searchEnd := searchBegin + dec.shardSize - 1 if searchEnd >= len(dec.rx) { searchEnd = len(dec.rx) - 1 } // re-construct datashards if searchEnd-searchBegin+1 >= dec.dataShards { var numshard, numDataShard, first, maxlen int // zero caches shards := dec.decodeCache shardsflag := dec.flagCache for k := range dec.decodeCache { shards[k] = nil shardsflag[k] = false } // shard assembly for i := searchBegin; i <= searchEnd; i++ { seqid := dec.rx[i].seqid() if _itimediff(seqid, shardEnd) > 0 { break } else if _itimediff(seqid, shardBegin) >= 0 { shards[seqid%uint32(dec.shardSize)] = dec.rx[i].data() shardsflag[seqid%uint32(dec.shardSize)] = true numshard++ if dec.rx[i].flag() == typeData { numDataShard++ } if numshard == 1 { first = i } if len(dec.rx[i].data()) > maxlen { maxlen = len(dec.rx[i].data()) } } } if numDataShard == dec.dataShards { // case 1: no loss on data shards dec.rx = dec.freeRange(first, numshard, dec.rx) } else if numshard >= dec.dataShards { // case 2: loss on data shards, but it's recoverable from parity shards for k := range shards { if shards[k] != nil { dlen := len(shards[k]) shards[k] = shards[k][:maxlen] copy(shards[k][dlen:], dec.zeros) } else { shards[k] = xmitBuf.Get().([]byte)[:0] } } if err := dec.codec.ReconstructData(shards); err == nil { for k := range shards[:dec.dataShards] { if !shardsflag[k] { // recovered data should be recycled recovered = append(recovered, shards[k]) } } } dec.rx = dec.freeRange(first, numshard, dec.rx) } } // keep rxlimit if len(dec.rx) > dec.rxlimit { if dec.rx[0].flag() == typeData { // track the unrecoverable data atomic.AddUint64(&DefaultSnmp.FECShortShards, 1) } dec.rx = dec.freeRange(0, 1, dec.rx) } return }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
fec.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/fec.go#L178-L188
go
train
// free a range of fecPacket
func (dec *fecDecoder) freeRange(first, n int, q []fecPacket) []fecPacket
// free a range of fecPacket func (dec *fecDecoder) freeRange(first, n int, q []fecPacket) []fecPacket
{ for i := first; i < first+n; i++ { // recycle buffer xmitBuf.Put([]byte(q[i])) } if first == 0 && n < len(q)/2 { return q[n:] } copy(q[first:], q[first+n:]) return q[:len(q)-n] }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
fec.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/fec.go#L247-L295
go
train
// encodes the packet, outputs parity shards if we have collected quorum datashards // notice: the contents of 'ps' will be re-written in successive calling
func (enc *fecEncoder) encode(b []byte) (ps [][]byte)
// encodes the packet, outputs parity shards if we have collected quorum datashards // notice: the contents of 'ps' will be re-written in successive calling func (enc *fecEncoder) encode(b []byte) (ps [][]byte)
{ // The header format: // | FEC SEQID(4B) | FEC TYPE(2B) | SIZE (2B) | PAYLOAD(SIZE-2) | // |<-headerOffset |<-payloadOffset enc.markData(b[enc.headerOffset:]) binary.LittleEndian.PutUint16(b[enc.payloadOffset:], uint16(len(b[enc.payloadOffset:]))) // copy data from payloadOffset to fec shard cache sz := len(b) enc.shardCache[enc.shardCount] = enc.shardCache[enc.shardCount][:sz] copy(enc.shardCache[enc.shardCount][enc.payloadOffset:], b[enc.payloadOffset:]) enc.shardCount++ // track max datashard length if sz > enc.maxSize { enc.maxSize = sz } // Generation of Reed-Solomon Erasure Code if enc.shardCount == enc.dataShards { // fill '0' into the tail of each datashard for i := 0; i < enc.dataShards; i++ { shard := enc.shardCache[i] slen := len(shard) copy(shard[slen:enc.maxSize], enc.zeros) } // construct equal-sized slice with stripped header cache := enc.encodeCache for k := range cache { cache[k] = enc.shardCache[k][enc.payloadOffset:enc.maxSize] } // encoding if err := enc.codec.Encode(cache); err == nil { ps = enc.shardCache[enc.dataShards:] for k := range ps { enc.markParity(ps[k][enc.headerOffset:]) ps[k] = ps[k][:enc.maxSize] } } // counters resetting enc.shardCount = 0 enc.maxSize = 0 } return }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
readloop_linux.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/readloop_linux.go#L19-L26
go
train
// the read loop for a client session
func (s *UDPSession) readLoop()
// the read loop for a client session func (s *UDPSession) readLoop()
{ addr, _ := net.ResolveUDPAddr("udp", s.conn.LocalAddr().String()) if addr.IP.To4() != nil { s.readLoopIPv4() } else { s.readLoopIPv6() } }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
readloop_linux.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/readloop_linux.go#L100-L107
go
train
// monitor incoming data for all connections of server
func (l *Listener) monitor()
// monitor incoming data for all connections of server func (l *Listener) monitor()
{ addr, _ := net.ResolveUDPAddr("udp", l.conn.LocalAddr().String()) if addr.IP.To4() != nil { l.monitorIPv4() } else { l.monitorIPv6() } }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L49-L52
go
train
/* encode 16 bits unsigned int (lsb) */
func ikcp_encode16u(p []byte, w uint16) []byte
/* encode 16 bits unsigned int (lsb) */ func ikcp_encode16u(p []byte, w uint16) []byte
{ binary.LittleEndian.PutUint16(p, w) return p[2:] }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L55-L58
go
train
/* decode 16 bits unsigned int (lsb) */
func ikcp_decode16u(p []byte, w *uint16) []byte
/* decode 16 bits unsigned int (lsb) */ func ikcp_decode16u(p []byte, w *uint16) []byte
{ *w = binary.LittleEndian.Uint16(p) return p[2:] }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L61-L64
go
train
/* encode 32 bits unsigned int (lsb) */
func ikcp_encode32u(p []byte, l uint32) []byte
/* encode 32 bits unsigned int (lsb) */ func ikcp_encode32u(p []byte, l uint32) []byte
{ binary.LittleEndian.PutUint32(p, l) return p[4:] }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L67-L70
go
train
/* decode 32 bits unsigned int (lsb) */
func ikcp_decode32u(p []byte, l *uint32) []byte
/* decode 32 bits unsigned int (lsb) */ func ikcp_decode32u(p []byte, l *uint32) []byte
{ *l = binary.LittleEndian.Uint32(p) return p[4:] }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L112-L123
go
train
// encode a segment into buffer
func (seg *segment) encode(ptr []byte) []byte
// encode a segment into buffer func (seg *segment) encode(ptr []byte) []byte
{ ptr = ikcp_encode32u(ptr, seg.conv) ptr = ikcp_encode8u(ptr, seg.cmd) ptr = ikcp_encode8u(ptr, seg.frg) ptr = ikcp_encode16u(ptr, seg.wnd) ptr = ikcp_encode32u(ptr, seg.ts) ptr = ikcp_encode32u(ptr, seg.sn) ptr = ikcp_encode32u(ptr, seg.una) ptr = ikcp_encode32u(ptr, uint32(len(seg.data))) atomic.AddUint64(&DefaultSnmp.OutSegs, 1) return ptr }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L160-L177
go
train
// NewKCP create a new kcp control object, 'conv' must equal in two endpoint // from the same connection.
func NewKCP(conv uint32, output output_callback) *KCP
// NewKCP create a new kcp control object, 'conv' must equal in two endpoint // from the same connection. func NewKCP(conv uint32, output output_callback) *KCP
{ kcp := new(KCP) kcp.conv = conv kcp.snd_wnd = IKCP_WND_SND kcp.rcv_wnd = IKCP_WND_RCV kcp.rmt_wnd = IKCP_WND_RCV kcp.mtu = IKCP_MTU_DEF kcp.mss = kcp.mtu - IKCP_OVERHEAD kcp.buffer = make([]byte, kcp.mtu) kcp.rx_rto = IKCP_RTO_DEF kcp.rx_minrto = IKCP_RTO_MIN kcp.interval = IKCP_INTERVAL kcp.ts_flush = IKCP_INTERVAL kcp.ssthresh = IKCP_THRESH_INIT kcp.dead_link = IKCP_DEADLINK kcp.output = output return kcp }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L180-L183
go
train
// newSegment creates a KCP segment
func (kcp *KCP) newSegment(size int) (seg segment)
// newSegment creates a KCP segment func (kcp *KCP) newSegment(size int) (seg segment)
{ seg.data = xmitBuf.Get().([]byte)[:size] return }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L186-L191
go
train
// delSegment recycles a KCP segment
func (kcp *KCP) delSegment(seg *segment)
// delSegment recycles a KCP segment func (kcp *KCP) delSegment(seg *segment)
{ if seg.data != nil { xmitBuf.Put(seg.data) seg.data = nil } }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L196-L203
go
train
// ReserveBytes keeps n bytes untouched from the beginning of the buffer // the output_callback function should be aware of this // return false if n >= mss
func (kcp *KCP) ReserveBytes(n int) bool
// ReserveBytes keeps n bytes untouched from the beginning of the buffer // the output_callback function should be aware of this // return false if n >= mss func (kcp *KCP) ReserveBytes(n int) bool
{ if n >= int(kcp.mtu-IKCP_OVERHEAD) || n < 0 { return false } kcp.reserved = n kcp.mss = kcp.mtu - IKCP_OVERHEAD - uint32(n) return true }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L206-L228
go
train
// PeekSize checks the size of next message in the recv queue
func (kcp *KCP) PeekSize() (length int)
// PeekSize checks the size of next message in the recv queue func (kcp *KCP) PeekSize() (length int)
{ if len(kcp.rcv_queue) == 0 { return -1 } seg := &kcp.rcv_queue[0] if seg.frg == 0 { return len(seg.data) } if len(kcp.rcv_queue) < int(seg.frg+1) { return -1 } for k := range kcp.rcv_queue { seg := &kcp.rcv_queue[k] length += len(seg.data) if seg.frg == 0 { break } } return }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L231-L291
go
train
// Recv is user/upper level recv: returns size, returns below zero for EAGAIN
func (kcp *KCP) Recv(buffer []byte) (n int)
// Recv is user/upper level recv: returns size, returns below zero for EAGAIN func (kcp *KCP) Recv(buffer []byte) (n int)
{ if len(kcp.rcv_queue) == 0 { return -1 } peeksize := kcp.PeekSize() if peeksize < 0 { return -2 } if peeksize > len(buffer) { return -3 } var fast_recover bool if len(kcp.rcv_queue) >= int(kcp.rcv_wnd) { fast_recover = true } // merge fragment count := 0 for k := range kcp.rcv_queue { seg := &kcp.rcv_queue[k] copy(buffer, seg.data) buffer = buffer[len(seg.data):] n += len(seg.data) count++ kcp.delSegment(seg) if seg.frg == 0 { break } } if count > 0 { kcp.rcv_queue = kcp.remove_front(kcp.rcv_queue, count) } // move available data from rcv_buf -> rcv_queue count = 0 for k := range kcp.rcv_buf { seg := &kcp.rcv_buf[k] if seg.sn == kcp.rcv_nxt && len(kcp.rcv_queue) < int(kcp.rcv_wnd) { kcp.rcv_nxt++ count++ } else { break } } if count > 0 { kcp.rcv_queue = append(kcp.rcv_queue, kcp.rcv_buf[:count]...) kcp.rcv_buf = kcp.remove_front(kcp.rcv_buf, count) } // fast recover if len(kcp.rcv_queue) < int(kcp.rcv_wnd) && fast_recover { // ready to send back IKCP_CMD_WINS in ikcp_flush // tell remote my window size kcp.probe |= IKCP_ASK_TELL } return }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L294-L358
go
train
// Send is user/upper level send, returns below zero for error
func (kcp *KCP) Send(buffer []byte) int
// Send is user/upper level send, returns below zero for error func (kcp *KCP) Send(buffer []byte) int
{ var count int if len(buffer) == 0 { return -1 } // append to previous segment in streaming mode (if possible) if kcp.stream != 0 { n := len(kcp.snd_queue) if n > 0 { seg := &kcp.snd_queue[n-1] if len(seg.data) < int(kcp.mss) { capacity := int(kcp.mss) - len(seg.data) extend := capacity if len(buffer) < capacity { extend = len(buffer) } // grow slice, the underlying cap is guaranteed to // be larger than kcp.mss oldlen := len(seg.data) seg.data = seg.data[:oldlen+extend] copy(seg.data[oldlen:], buffer) buffer = buffer[extend:] } } if len(buffer) == 0 { return 0 } } if len(buffer) <= int(kcp.mss) { count = 1 } else { count = (len(buffer) + int(kcp.mss) - 1) / int(kcp.mss) } if count > 255 { return -2 } if count == 0 { count = 1 } for i := 0; i < count; i++ { var size int if len(buffer) > int(kcp.mss) { size = int(kcp.mss) } else { size = len(buffer) } seg := kcp.newSegment(size) copy(seg.data, buffer[:size]) if kcp.stream == 0 { // message mode seg.frg = uint8(count - i - 1) } else { // stream mode seg.frg = 0 } kcp.snd_queue = append(kcp.snd_queue, seg) buffer = buffer[size:] } return 0 }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L448-L450
go
train
// ack append
func (kcp *KCP) ack_push(sn, ts uint32)
// ack append func (kcp *KCP) ack_push(sn, ts uint32)
{ kcp.acklist = append(kcp.acklist, ackItem{sn, ts}) }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L453-L507
go
train
// returns true if data has repeated
func (kcp *KCP) parse_data(newseg segment) bool
// returns true if data has repeated func (kcp *KCP) parse_data(newseg segment) bool
{ sn := newseg.sn if _itimediff(sn, kcp.rcv_nxt+kcp.rcv_wnd) >= 0 || _itimediff(sn, kcp.rcv_nxt) < 0 { return true } n := len(kcp.rcv_buf) - 1 insert_idx := 0 repeat := false for i := n; i >= 0; i-- { seg := &kcp.rcv_buf[i] if seg.sn == sn { repeat = true break } if _itimediff(sn, seg.sn) > 0 { insert_idx = i + 1 break } } if !repeat { // replicate the content if it's new dataCopy := xmitBuf.Get().([]byte)[:len(newseg.data)] copy(dataCopy, newseg.data) newseg.data = dataCopy if insert_idx == n+1 { kcp.rcv_buf = append(kcp.rcv_buf, newseg) } else { kcp.rcv_buf = append(kcp.rcv_buf, segment{}) copy(kcp.rcv_buf[insert_idx+1:], kcp.rcv_buf[insert_idx:]) kcp.rcv_buf[insert_idx] = newseg } } // move available data from rcv_buf -> rcv_queue count := 0 for k := range kcp.rcv_buf { seg := &kcp.rcv_buf[k] if seg.sn == kcp.rcv_nxt && len(kcp.rcv_queue) < int(kcp.rcv_wnd) { kcp.rcv_nxt++ count++ } else { break } } if count > 0 { kcp.rcv_queue = append(kcp.rcv_queue, kcp.rcv_buf[:count]...) kcp.rcv_buf = kcp.remove_front(kcp.rcv_buf, count) } return repeat }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L511-L636
go
train
// Input when you received a low level packet (eg. UDP packet), call it // regular indicates a regular packet has received(not from FEC)
func (kcp *KCP) Input(data []byte, regular, ackNoDelay bool) int
// Input when you received a low level packet (eg. UDP packet), call it // regular indicates a regular packet has received(not from FEC) func (kcp *KCP) Input(data []byte, regular, ackNoDelay bool) int
{ snd_una := kcp.snd_una if len(data) < IKCP_OVERHEAD { return -1 } var latest uint32 // the latest ack packet var flag int var inSegs uint64 for { var ts, sn, length, una, conv uint32 var wnd uint16 var cmd, frg uint8 if len(data) < int(IKCP_OVERHEAD) { break } data = ikcp_decode32u(data, &conv) if conv != kcp.conv { return -1 } data = ikcp_decode8u(data, &cmd) data = ikcp_decode8u(data, &frg) data = ikcp_decode16u(data, &wnd) data = ikcp_decode32u(data, &ts) data = ikcp_decode32u(data, &sn) data = ikcp_decode32u(data, &una) data = ikcp_decode32u(data, &length) if len(data) < int(length) { return -2 } if cmd != IKCP_CMD_PUSH && cmd != IKCP_CMD_ACK && cmd != IKCP_CMD_WASK && cmd != IKCP_CMD_WINS { return -3 } // only trust window updates from regular packets. i.e: latest update if regular { kcp.rmt_wnd = uint32(wnd) } kcp.parse_una(una) kcp.shrink_buf() if cmd == IKCP_CMD_ACK { kcp.parse_ack(sn) kcp.parse_fastack(sn, ts) flag |= 1 latest = ts } else if cmd == IKCP_CMD_PUSH { repeat := true if _itimediff(sn, kcp.rcv_nxt+kcp.rcv_wnd) < 0 { kcp.ack_push(sn, ts) if _itimediff(sn, kcp.rcv_nxt) >= 0 { var seg segment seg.conv = conv seg.cmd = cmd seg.frg = frg seg.wnd = wnd seg.ts = ts seg.sn = sn seg.una = una seg.data = data[:length] // delayed data copying repeat = kcp.parse_data(seg) } } if regular && repeat { atomic.AddUint64(&DefaultSnmp.RepeatSegs, 1) } } else if cmd == IKCP_CMD_WASK { // ready to send back IKCP_CMD_WINS in Ikcp_flush // tell remote my window size kcp.probe |= IKCP_ASK_TELL } else if cmd == IKCP_CMD_WINS { // do nothing } else { return -3 } inSegs++ data = data[length:] } atomic.AddUint64(&DefaultSnmp.InSegs, inSegs) // update rtt with the latest ts // ignore the FEC packet if flag != 0 && regular { current := currentMs() if _itimediff(current, latest) >= 0 { kcp.update_ack(_itimediff(current, latest)) } } // cwnd update when packet arrived if kcp.nocwnd == 0 { if _itimediff(kcp.snd_una, snd_una) > 0 { if kcp.cwnd < kcp.rmt_wnd { mss := kcp.mss if kcp.cwnd < kcp.ssthresh { kcp.cwnd++ kcp.incr += mss } else { if kcp.incr < mss { kcp.incr = mss } kcp.incr += (mss*mss)/kcp.incr + (mss / 16) if (kcp.cwnd+1)*mss <= kcp.incr { kcp.cwnd++ } } if kcp.cwnd > kcp.rmt_wnd { kcp.cwnd = kcp.rmt_wnd kcp.incr = kcp.rmt_wnd * mss } } } } if ackNoDelay && len(kcp.acklist) > 0 { // ack immediately kcp.flush(true) } return 0 }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L646-L876
go
train
// flush pending data
func (kcp *KCP) flush(ackOnly bool) uint32
// flush pending data func (kcp *KCP) flush(ackOnly bool) uint32
{ var seg segment seg.conv = kcp.conv seg.cmd = IKCP_CMD_ACK seg.wnd = kcp.wnd_unused() seg.una = kcp.rcv_nxt buffer := kcp.buffer ptr := buffer[kcp.reserved:] // keep n bytes untouched // makeSpace makes room for writing makeSpace := func(space int) { size := len(buffer) - len(ptr) if size+space > int(kcp.mtu) { kcp.output(buffer, size) ptr = buffer[kcp.reserved:] } } // flush bytes in buffer if there is any flushBuffer := func() { size := len(buffer) - len(ptr) if size > kcp.reserved { kcp.output(buffer, size) } } // flush acknowledges for i, ack := range kcp.acklist { makeSpace(IKCP_OVERHEAD) // filter jitters caused by bufferbloat if ack.sn >= kcp.rcv_nxt || len(kcp.acklist)-1 == i { seg.sn, seg.ts = ack.sn, ack.ts ptr = seg.encode(ptr) } } kcp.acklist = kcp.acklist[0:0] if ackOnly { // flash remain ack segments flushBuffer() return kcp.interval } // probe window size (if remote window size equals zero) if kcp.rmt_wnd == 0 { current := currentMs() if kcp.probe_wait == 0 { kcp.probe_wait = IKCP_PROBE_INIT kcp.ts_probe = current + kcp.probe_wait } else { if _itimediff(current, kcp.ts_probe) >= 0 { if kcp.probe_wait < IKCP_PROBE_INIT { kcp.probe_wait = IKCP_PROBE_INIT } kcp.probe_wait += kcp.probe_wait / 2 if kcp.probe_wait > IKCP_PROBE_LIMIT { kcp.probe_wait = IKCP_PROBE_LIMIT } kcp.ts_probe = current + kcp.probe_wait kcp.probe |= IKCP_ASK_SEND } } } else { kcp.ts_probe = 0 kcp.probe_wait = 0 } // flush window probing commands if (kcp.probe & IKCP_ASK_SEND) != 0 { seg.cmd = IKCP_CMD_WASK makeSpace(IKCP_OVERHEAD) ptr = seg.encode(ptr) } // flush window probing commands if (kcp.probe & IKCP_ASK_TELL) != 0 { seg.cmd = IKCP_CMD_WINS makeSpace(IKCP_OVERHEAD) ptr = seg.encode(ptr) } kcp.probe = 0 // calculate window size cwnd := _imin_(kcp.snd_wnd, kcp.rmt_wnd) if kcp.nocwnd == 0 { cwnd = _imin_(kcp.cwnd, cwnd) } // sliding window, controlled by snd_nxt && sna_una+cwnd newSegsCount := 0 for k := range kcp.snd_queue { if _itimediff(kcp.snd_nxt, kcp.snd_una+cwnd) >= 0 { break } newseg := kcp.snd_queue[k] newseg.conv = kcp.conv newseg.cmd = IKCP_CMD_PUSH newseg.sn = kcp.snd_nxt kcp.snd_buf = append(kcp.snd_buf, newseg) kcp.snd_nxt++ newSegsCount++ } if newSegsCount > 0 { kcp.snd_queue = kcp.remove_front(kcp.snd_queue, newSegsCount) } // calculate resent resent := uint32(kcp.fastresend) if kcp.fastresend <= 0 { resent = 0xffffffff } // check for retransmissions current := currentMs() var change, lost, lostSegs, fastRetransSegs, earlyRetransSegs uint64 minrto := int32(kcp.interval) ref := kcp.snd_buf[:len(kcp.snd_buf)] // for bounds check elimination for k := range ref { segment := &ref[k] needsend := false if segment.acked == 1 { continue } if segment.xmit == 0 { // initial transmit needsend = true segment.rto = kcp.rx_rto segment.resendts = current + segment.rto } else if _itimediff(current, segment.resendts) >= 0 { // RTO needsend = true if kcp.nodelay == 0 { segment.rto += kcp.rx_rto } else { segment.rto += kcp.rx_rto / 2 } segment.resendts = current + segment.rto lost++ lostSegs++ } else if segment.fastack >= resent { // fast retransmit needsend = true segment.fastack = 0 segment.rto = kcp.rx_rto segment.resendts = current + segment.rto change++ fastRetransSegs++ } else if segment.fastack > 0 && newSegsCount == 0 { // early retransmit needsend = true segment.fastack = 0 segment.rto = kcp.rx_rto segment.resendts = current + segment.rto change++ earlyRetransSegs++ } if needsend { current = currentMs() // time update for a blocking call segment.xmit++ segment.ts = current segment.wnd = seg.wnd segment.una = seg.una need := IKCP_OVERHEAD + len(segment.data) makeSpace(need) ptr = segment.encode(ptr) copy(ptr, segment.data) ptr = ptr[len(segment.data):] if segment.xmit >= kcp.dead_link { kcp.state = 0xFFFFFFFF } } // get the nearest rto if rto := _itimediff(segment.resendts, current); rto > 0 && rto < minrto { minrto = rto } } // flash remain segments flushBuffer() // counter updates sum := lostSegs if lostSegs > 0 { atomic.AddUint64(&DefaultSnmp.LostSegs, lostSegs) } if fastRetransSegs > 0 { atomic.AddUint64(&DefaultSnmp.FastRetransSegs, fastRetransSegs) sum += fastRetransSegs } if earlyRetransSegs > 0 { atomic.AddUint64(&DefaultSnmp.EarlyRetransSegs, earlyRetransSegs) sum += earlyRetransSegs } if sum > 0 { atomic.AddUint64(&DefaultSnmp.RetransSegs, sum) } // cwnd update if kcp.nocwnd == 0 { // update ssthresh // rate halving, https://tools.ietf.org/html/rfc6937 if change > 0 { inflight := kcp.snd_nxt - kcp.snd_una kcp.ssthresh = inflight / 2 if kcp.ssthresh < IKCP_THRESH_MIN { kcp.ssthresh = IKCP_THRESH_MIN } kcp.cwnd = kcp.ssthresh + resent kcp.incr = kcp.cwnd * kcp.mss } // congestion control, https://tools.ietf.org/html/rfc5681 if lost > 0 { kcp.ssthresh = cwnd / 2 if kcp.ssthresh < IKCP_THRESH_MIN { kcp.ssthresh = IKCP_THRESH_MIN } kcp.cwnd = 1 kcp.incr = kcp.mss } if kcp.cwnd < 1 { kcp.cwnd = 1 kcp.incr = kcp.mss } } return uint32(minrto) }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L881-L904
go
train
// Update updates state (call it repeatedly, every 10ms-100ms), or you can ask // ikcp_check when to call it again (without ikcp_input/_send calling). // 'current' - current timestamp in millisec.
func (kcp *KCP) Update()
// Update updates state (call it repeatedly, every 10ms-100ms), or you can ask // ikcp_check when to call it again (without ikcp_input/_send calling). // 'current' - current timestamp in millisec. func (kcp *KCP) Update()
{ var slap int32 current := currentMs() if kcp.updated == 0 { kcp.updated = 1 kcp.ts_flush = current } slap = _itimediff(current, kcp.ts_flush) if slap >= 10000 || slap < -10000 { kcp.ts_flush = current slap = 0 } if slap >= 0 { kcp.ts_flush += kcp.interval if _itimediff(current, kcp.ts_flush) >= 0 { kcp.ts_flush = current + kcp.interval } kcp.flush(false) } }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L913-L954
go
train
// Check determines when should you invoke ikcp_update: // returns when you should invoke ikcp_update in millisec, if there // is no ikcp_input/_send calling. you can call ikcp_update in that // time, instead of call update repeatly. // Important to reduce unnacessary ikcp_update invoking. use it to // schedule ikcp_update (eg. implementing an epoll-like mechanism, // or optimize ikcp_update when handling massive kcp connections)
func (kcp *KCP) Check() uint32
// Check determines when should you invoke ikcp_update: // returns when you should invoke ikcp_update in millisec, if there // is no ikcp_input/_send calling. you can call ikcp_update in that // time, instead of call update repeatly. // Important to reduce unnacessary ikcp_update invoking. use it to // schedule ikcp_update (eg. implementing an epoll-like mechanism, // or optimize ikcp_update when handling massive kcp connections) func (kcp *KCP) Check() uint32
{ current := currentMs() ts_flush := kcp.ts_flush tm_flush := int32(0x7fffffff) tm_packet := int32(0x7fffffff) minimal := uint32(0) if kcp.updated == 0 { return current } if _itimediff(current, ts_flush) >= 10000 || _itimediff(current, ts_flush) < -10000 { ts_flush = current } if _itimediff(current, ts_flush) >= 0 { return current } tm_flush = _itimediff(ts_flush, current) for k := range kcp.snd_buf { seg := &kcp.snd_buf[k] diff := _itimediff(seg.resendts, current) if diff <= 0 { return current } if diff < tm_packet { tm_packet = diff } } minimal = uint32(tm_packet) if tm_packet >= tm_flush { minimal = uint32(tm_flush) } if minimal >= kcp.interval { minimal = kcp.interval } return current + minimal }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L957-L973
go
train
// SetMtu changes MTU size, default is 1400
func (kcp *KCP) SetMtu(mtu int) int
// SetMtu changes MTU size, default is 1400 func (kcp *KCP) SetMtu(mtu int) int
{ if mtu < 50 || mtu < IKCP_OVERHEAD { return -1 } if kcp.reserved >= int(kcp.mtu-IKCP_OVERHEAD) || kcp.reserved < 0 { return -1 } buffer := make([]byte, mtu) if buffer == nil { return -2 } kcp.mtu = uint32(mtu) kcp.mss = kcp.mtu - IKCP_OVERHEAD - uint32(kcp.reserved) kcp.buffer = buffer return 0 }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L981-L1005
go
train
// NoDelay options // fastest: ikcp_nodelay(kcp, 1, 20, 2, 1) // nodelay: 0:disable(default), 1:enable // interval: internal update timer interval in millisec, default is 100ms // resend: 0:disable fast resend(default), 1:enable fast resend // nc: 0:normal congestion control(default), 1:disable congestion control
func (kcp *KCP) NoDelay(nodelay, interval, resend, nc int) int
// NoDelay options // fastest: ikcp_nodelay(kcp, 1, 20, 2, 1) // nodelay: 0:disable(default), 1:enable // interval: internal update timer interval in millisec, default is 100ms // resend: 0:disable fast resend(default), 1:enable fast resend // nc: 0:normal congestion control(default), 1:disable congestion control func (kcp *KCP) NoDelay(nodelay, interval, resend, nc int) int
{ if nodelay >= 0 { kcp.nodelay = uint32(nodelay) if nodelay != 0 { kcp.rx_minrto = IKCP_RTO_NDL } else { kcp.rx_minrto = IKCP_RTO_MIN } } if interval >= 0 { if interval > 5000 { interval = 5000 } else if interval < 10 { interval = 10 } kcp.interval = uint32(interval) } if resend >= 0 { kcp.fastresend = int32(resend) } if nc >= 0 { kcp.nocwnd = int32(nc) } return 0 }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L1008-L1016
go
train
// WndSize sets maximum window size: sndwnd=32, rcvwnd=32 by default
func (kcp *KCP) WndSize(sndwnd, rcvwnd int) int
// WndSize sets maximum window size: sndwnd=32, rcvwnd=32 by default func (kcp *KCP) WndSize(sndwnd, rcvwnd int) int
{ if sndwnd > 0 { kcp.snd_wnd = uint32(sndwnd) } if rcvwnd > 0 { kcp.rcv_wnd = uint32(rcvwnd) } return 0 }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L1019-L1021
go
train
// WaitSnd gets how many packet is waiting to be sent
func (kcp *KCP) WaitSnd() int
// WaitSnd gets how many packet is waiting to be sent func (kcp *KCP) WaitSnd() int
{ return len(kcp.snd_buf) + len(kcp.snd_queue) }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
kcp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L1027-L1033
go
train
// remove front n elements from queue // if the number of elements to remove is more than half of the size. // just shift the rear elements to front, otherwise just reslice q to q[n:] // then the cost of runtime.growslice can always be less than n/2
func (kcp *KCP) remove_front(q []segment, n int) []segment
// remove front n elements from queue // if the number of elements to remove is more than half of the size. // just shift the rear elements to front, otherwise just reslice q to q[n:] // then the cost of runtime.growslice can always be less than n/2 func (kcp *KCP) remove_front(q []segment, n int) []segment
{ if n > len(q)/2 { newn := copy(q, q[n:]) return q[:newn] } return q[n:] }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L113-L168
go
train
// newUDPSession create a new udp session for client or server
func newUDPSession(conv uint32, dataShards, parityShards int, l *Listener, conn net.PacketConn, remote net.Addr, block BlockCrypt) *UDPSession
// newUDPSession create a new udp session for client or server func newUDPSession(conv uint32, dataShards, parityShards int, l *Listener, conn net.PacketConn, remote net.Addr, block BlockCrypt) *UDPSession
{ sess := new(UDPSession) sess.die = make(chan struct{}) sess.nonce = new(nonceAES128) sess.nonce.Init() sess.chReadEvent = make(chan struct{}, 1) sess.chWriteEvent = make(chan struct{}, 1) sess.chReadError = make(chan error, 1) sess.chWriteError = make(chan error, 1) sess.remote = remote sess.conn = conn sess.l = l sess.block = block sess.recvbuf = make([]byte, mtuLimit) // FEC codec initialization sess.fecDecoder = newFECDecoder(rxFECMulti*(dataShards+parityShards), dataShards, parityShards) if sess.block != nil { sess.fecEncoder = newFECEncoder(dataShards, parityShards, cryptHeaderSize) } else { sess.fecEncoder = newFECEncoder(dataShards, parityShards, 0) } // calculate additional header size introduced by FEC and encryption if sess.block != nil { sess.headerSize += cryptHeaderSize } if sess.fecEncoder != nil { sess.headerSize += fecHeaderSizePlus2 } sess.kcp = NewKCP(conv, func(buf []byte, size int) { if size >= IKCP_OVERHEAD+sess.headerSize { sess.output(buf[:size]) } }) sess.kcp.ReserveBytes(sess.headerSize) // register current session to the global updater, // which call sess.update() periodically. updater.addSession(sess) if sess.l == nil { // it's a client connection go sess.readLoop() atomic.AddUint64(&DefaultSnmp.ActiveOpens, 1) } else { atomic.AddUint64(&DefaultSnmp.PassiveOpens, 1) } currestab := atomic.AddUint64(&DefaultSnmp.CurrEstab, 1) maxconn := atomic.LoadUint64(&DefaultSnmp.MaxConn) if currestab > maxconn { atomic.CompareAndSwapUint64(&DefaultSnmp.MaxConn, maxconn, currestab) } return sess }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L171-L241
go
train
// Read implements net.Conn
func (s *UDPSession) Read(b []byte) (n int, err error)
// Read implements net.Conn func (s *UDPSession) Read(b []byte) (n int, err error)
{ for { s.mu.Lock() if len(s.bufptr) > 0 { // copy from buffer into b n = copy(b, s.bufptr) s.bufptr = s.bufptr[n:] s.mu.Unlock() atomic.AddUint64(&DefaultSnmp.BytesReceived, uint64(n)) return n, nil } if s.isClosed { s.mu.Unlock() return 0, errors.New(errBrokenPipe) } if size := s.kcp.PeekSize(); size > 0 { // peek data size from kcp if len(b) >= size { // receive data into 'b' directly s.kcp.Recv(b) s.mu.Unlock() atomic.AddUint64(&DefaultSnmp.BytesReceived, uint64(size)) return size, nil } // if necessary resize the stream buffer to guarantee a sufficent buffer space if cap(s.recvbuf) < size { s.recvbuf = make([]byte, size) } // resize the length of recvbuf to correspond to data size s.recvbuf = s.recvbuf[:size] s.kcp.Recv(s.recvbuf) n = copy(b, s.recvbuf) // copy to 'b' s.bufptr = s.recvbuf[n:] // pointer update s.mu.Unlock() atomic.AddUint64(&DefaultSnmp.BytesReceived, uint64(n)) return n, nil } // deadline for current reading operation var timeout *time.Timer var c <-chan time.Time if !s.rd.IsZero() { if time.Now().After(s.rd) { s.mu.Unlock() return 0, errTimeout{} } delay := s.rd.Sub(time.Now()) timeout = time.NewTimer(delay) c = timeout.C } s.mu.Unlock() // wait for read event or timeout select { case <-s.chReadEvent: case <-c: case <-s.die: case err = <-s.chReadError: if timeout != nil { timeout.Stop() } return n, err } if timeout != nil { timeout.Stop() } } }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L247-L305
go
train
// WriteBuffers write a vector of byte slices to the underlying connection
func (s *UDPSession) WriteBuffers(v [][]byte) (n int, err error)
// WriteBuffers write a vector of byte slices to the underlying connection func (s *UDPSession) WriteBuffers(v [][]byte) (n int, err error)
{ for { s.mu.Lock() if s.isClosed { s.mu.Unlock() return 0, errors.New(errBrokenPipe) } if s.kcp.WaitSnd() < int(s.kcp.snd_wnd) { for _, b := range v { n += len(b) for { if len(b) <= int(s.kcp.mss) { s.kcp.Send(b) break } else { s.kcp.Send(b[:s.kcp.mss]) b = b[s.kcp.mss:] } } } if s.kcp.WaitSnd() >= int(s.kcp.snd_wnd) || !s.writeDelay { s.kcp.flush(false) } s.mu.Unlock() atomic.AddUint64(&DefaultSnmp.BytesSent, uint64(n)) return n, nil } var timeout *time.Timer var c <-chan time.Time if !s.wd.IsZero() { if time.Now().After(s.wd) { s.mu.Unlock() return 0, errTimeout{} } delay := s.wd.Sub(time.Now()) timeout = time.NewTimer(delay) c = timeout.C } s.mu.Unlock() select { case <-s.chWriteEvent: case <-c: case <-s.die: case err = <-s.chWriteError: if timeout != nil { timeout.Stop() } return n, err } if timeout != nil { timeout.Stop() } } }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L308-L327
go
train
// Close closes the connection.
func (s *UDPSession) Close() error
// Close closes the connection. func (s *UDPSession) Close() error
{ // remove current session from updater & listener(if necessary) updater.removeSession(s) if s.l != nil { // notify listener s.l.closeSession(s.remote) } s.mu.Lock() defer s.mu.Unlock() if s.isClosed { return errors.New(errBrokenPipe) } close(s.die) s.isClosed = true atomic.AddUint64(&DefaultSnmp.CurrEstab, ^uint64(0)) if s.l == nil { // client socket close return s.conn.Close() } return nil }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L336-L344
go
train
// SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
func (s *UDPSession) SetDeadline(t time.Time) error
// SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline. func (s *UDPSession) SetDeadline(t time.Time) error
{ s.mu.Lock() defer s.mu.Unlock() s.rd = t s.wd = t s.notifyReadEvent() s.notifyWriteEvent() return nil }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L347-L353
go
train
// SetReadDeadline implements the Conn SetReadDeadline method.
func (s *UDPSession) SetReadDeadline(t time.Time) error
// SetReadDeadline implements the Conn SetReadDeadline method. func (s *UDPSession) SetReadDeadline(t time.Time) error
{ s.mu.Lock() defer s.mu.Unlock() s.rd = t s.notifyReadEvent() return nil }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L356-L362
go
train
// SetWriteDeadline implements the Conn SetWriteDeadline method.
func (s *UDPSession) SetWriteDeadline(t time.Time) error
// SetWriteDeadline implements the Conn SetWriteDeadline method. func (s *UDPSession) SetWriteDeadline(t time.Time) error
{ s.mu.Lock() defer s.mu.Unlock() s.wd = t s.notifyWriteEvent() return nil }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L365-L369
go
train
// SetWriteDelay delays write for bulk transfer until the next update interval
func (s *UDPSession) SetWriteDelay(delay bool)
// SetWriteDelay delays write for bulk transfer until the next update interval func (s *UDPSession) SetWriteDelay(delay bool)
{ s.mu.Lock() defer s.mu.Unlock() s.writeDelay = delay }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L372-L376
go
train
// SetWindowSize set maximum window size
func (s *UDPSession) SetWindowSize(sndwnd, rcvwnd int)
// SetWindowSize set maximum window size func (s *UDPSession) SetWindowSize(sndwnd, rcvwnd int)
{ s.mu.Lock() defer s.mu.Unlock() s.kcp.WndSize(sndwnd, rcvwnd) }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L379-L388
go
train
// SetMtu sets the maximum transmission unit(not including UDP header)
func (s *UDPSession) SetMtu(mtu int) bool
// SetMtu sets the maximum transmission unit(not including UDP header) func (s *UDPSession) SetMtu(mtu int) bool
{ if mtu > mtuLimit { return false } s.mu.Lock() defer s.mu.Unlock() s.kcp.SetMtu(mtu) return true }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L391-L399
go
train
// SetStreamMode toggles the stream mode on/off
func (s *UDPSession) SetStreamMode(enable bool)
// SetStreamMode toggles the stream mode on/off func (s *UDPSession) SetStreamMode(enable bool)
{ s.mu.Lock() defer s.mu.Unlock() if enable { s.kcp.stream = 1 } else { s.kcp.stream = 0 } }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L402-L406
go
train
// SetACKNoDelay changes ack flush option, set true to flush ack immediately,
func (s *UDPSession) SetACKNoDelay(nodelay bool)
// SetACKNoDelay changes ack flush option, set true to flush ack immediately, func (s *UDPSession) SetACKNoDelay(nodelay bool)
{ s.mu.Lock() defer s.mu.Unlock() s.ackNoDelay = nodelay }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L409-L413
go
train
// SetDUP duplicates udp packets for kcp output, for testing purpose only
func (s *UDPSession) SetDUP(dup int)
// SetDUP duplicates udp packets for kcp output, for testing purpose only func (s *UDPSession) SetDUP(dup int)
{ s.mu.Lock() defer s.mu.Unlock() s.dup = dup }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L417-L421
go
train
// SetNoDelay calls nodelay() of kcp // https://github.com/skywind3000/kcp/blob/master/README.en.md#protocol-configuration
func (s *UDPSession) SetNoDelay(nodelay, interval, resend, nc int)
// SetNoDelay calls nodelay() of kcp // https://github.com/skywind3000/kcp/blob/master/README.en.md#protocol-configuration func (s *UDPSession) SetNoDelay(nodelay, interval, resend, nc int)
{ s.mu.Lock() defer s.mu.Unlock() s.kcp.NoDelay(nodelay, interval, resend, nc) }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L441-L450
go
train
// SetReadBuffer sets the socket read buffer, no effect if it's accepted from Listener
func (s *UDPSession) SetReadBuffer(bytes int) error
// SetReadBuffer sets the socket read buffer, no effect if it's accepted from Listener func (s *UDPSession) SetReadBuffer(bytes int) error
{ s.mu.Lock() defer s.mu.Unlock() if s.l == nil { if nc, ok := s.conn.(setReadBuffer); ok { return nc.SetReadBuffer(bytes) } } return errors.New(errInvalidOperation) }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L470-L515
go
train
// post-processing for sending a packet from kcp core // steps: // 1. FEC packet generation // 2. CRC32 integrity // 3. Encryption // 4. WriteTo kernel
func (s *UDPSession) output(buf []byte)
// post-processing for sending a packet from kcp core // steps: // 1. FEC packet generation // 2. CRC32 integrity // 3. Encryption // 4. WriteTo kernel func (s *UDPSession) output(buf []byte)
{ var ecc [][]byte // 1. FEC encoding if s.fecEncoder != nil { ecc = s.fecEncoder.encode(buf) } // 2&3. crc32 & encryption if s.block != nil { s.nonce.Fill(buf[:nonceSize]) checksum := crc32.ChecksumIEEE(buf[cryptHeaderSize:]) binary.LittleEndian.PutUint32(buf[nonceSize:], checksum) s.block.Encrypt(buf, buf) for k := range ecc { s.nonce.Fill(ecc[k][:nonceSize]) checksum := crc32.ChecksumIEEE(ecc[k][cryptHeaderSize:]) binary.LittleEndian.PutUint32(ecc[k][nonceSize:], checksum) s.block.Encrypt(ecc[k], ecc[k]) } } // 4. WriteTo kernel nbytes := 0 npkts := 0 for i := 0; i < s.dup+1; i++ { if n, err := s.conn.WriteTo(buf, s.remote); err == nil { nbytes += n npkts++ } else { s.notifyWriteError(err) } } for k := range ecc { if n, err := s.conn.WriteTo(ecc[k], s.remote); err == nil { nbytes += n npkts++ } else { s.notifyWriteError(err) } } atomic.AddUint64(&DefaultSnmp.OutPkts, uint64(npkts)) atomic.AddUint64(&DefaultSnmp.OutBytes, uint64(nbytes)) }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L518-L527
go
train
// kcp update, returns interval for next calling
func (s *UDPSession) update() (interval time.Duration)
// kcp update, returns interval for next calling func (s *UDPSession) update() (interval time.Duration)
{ s.mu.Lock() waitsnd := s.kcp.WaitSnd() interval = time.Duration(s.kcp.flush(false)) * time.Millisecond if s.kcp.WaitSnd() < waitsnd { s.notifyWriteEvent() } s.mu.Unlock() return }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L554-L573
go
train
// packet input stage
func (s *UDPSession) packetInput(data []byte)
// packet input stage func (s *UDPSession) packetInput(data []byte)
{ dataValid := false if s.block != nil { s.block.Decrypt(data, data) data = data[nonceSize:] checksum := crc32.ChecksumIEEE(data[crcSize:]) if checksum == binary.LittleEndian.Uint32(data) { data = data[crcSize:] dataValid = true } else { atomic.AddUint64(&DefaultSnmp.InCsumErrors, 1) } } else if s.block == nil { dataValid = true } if dataValid { s.kcpInput(data) } }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L681-L730
go
train
// packet input stage
func (l *Listener) packetInput(data []byte, addr net.Addr)
// packet input stage func (l *Listener) packetInput(data []byte, addr net.Addr)
{ dataValid := false if l.block != nil { l.block.Decrypt(data, data) data = data[nonceSize:] checksum := crc32.ChecksumIEEE(data[crcSize:]) if checksum == binary.LittleEndian.Uint32(data) { data = data[crcSize:] dataValid = true } else { atomic.AddUint64(&DefaultSnmp.InCsumErrors, 1) } } else if l.block == nil { dataValid = true } if dataValid { l.sessionLock.Lock() s, ok := l.sessions[addr.String()] l.sessionLock.Unlock() if !ok { // new address:port if len(l.chAccepts) < cap(l.chAccepts) { // do not let the new sessions overwhelm accept queue var conv uint32 convValid := false if l.fecDecoder != nil { isfec := binary.LittleEndian.Uint16(data[4:]) if isfec == typeData { conv = binary.LittleEndian.Uint32(data[fecHeaderSizePlus2:]) convValid = true } } else { conv = binary.LittleEndian.Uint32(data) convValid = true } if convValid { // creates a new session only if the 'conv' field in kcp is accessible s := newUDPSession(conv, l.dataShards, l.parityShards, l, l.conn, addr, l.block) s.kcpInput(data) l.sessionLock.Lock() l.sessions[addr.String()] = s l.sessionLock.Unlock() l.chAccepts <- s } } } else { s.kcpInput(data) } } }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L733-L738
go
train
// SetReadBuffer sets the socket read buffer for the Listener
func (l *Listener) SetReadBuffer(bytes int) error
// SetReadBuffer sets the socket read buffer for the Listener func (l *Listener) SetReadBuffer(bytes int) error
{ if nc, ok := l.conn.(setReadBuffer); ok { return nc.SetReadBuffer(bytes) } return errors.New(errInvalidOperation) }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L741-L746
go
train
// SetWriteBuffer sets the socket write buffer for the Listener
func (l *Listener) SetWriteBuffer(bytes int) error
// SetWriteBuffer sets the socket write buffer for the Listener func (l *Listener) SetWriteBuffer(bytes int) error
{ if nc, ok := l.conn.(setWriteBuffer); ok { return nc.SetWriteBuffer(bytes) } return errors.New(errInvalidOperation) }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L749-L759
go
train
// SetDSCP sets the 6bit DSCP field of IP header
func (l *Listener) SetDSCP(dscp int) error
// SetDSCP sets the 6bit DSCP field of IP header func (l *Listener) SetDSCP(dscp int) error
{ if nc, ok := l.conn.(net.Conn); ok { addr, _ := net.ResolveUDPAddr("udp", nc.LocalAddr().String()) if addr.IP.To4() != nil { return ipv4.NewConn(nc).SetTOS(dscp << 2) } else { return ipv6.NewConn(nc).SetTrafficClass(dscp) } } return errors.New(errInvalidOperation) }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L767-L781
go
train
// AcceptKCP accepts a KCP connection
func (l *Listener) AcceptKCP() (*UDPSession, error)
// AcceptKCP accepts a KCP connection func (l *Listener) AcceptKCP() (*UDPSession, error)
{ var timeout <-chan time.Time if tdeadline, ok := l.rd.Load().(time.Time); ok && !tdeadline.IsZero() { timeout = time.After(tdeadline.Sub(time.Now())) } select { case <-timeout: return nil, &errTimeout{} case c := <-l.chAccepts: return c, nil case <-l.die: return nil, errors.New(errBrokenPipe) } }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L784-L788
go
train
// SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
func (l *Listener) SetDeadline(t time.Time) error
// SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline. func (l *Listener) SetDeadline(t time.Time) error
{ l.SetReadDeadline(t) l.SetWriteDeadline(t) return nil }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L791-L794
go
train
// SetReadDeadline implements the Conn SetReadDeadline method.
func (l *Listener) SetReadDeadline(t time.Time) error
// SetReadDeadline implements the Conn SetReadDeadline method. func (l *Listener) SetReadDeadline(t time.Time) error
{ l.rd.Store(t) return nil }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L797-L800
go
train
// SetWriteDeadline implements the Conn SetWriteDeadline method.
func (l *Listener) SetWriteDeadline(t time.Time) error
// SetWriteDeadline implements the Conn SetWriteDeadline method. func (l *Listener) SetWriteDeadline(t time.Time) error
{ l.wd.Store(t) return nil }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L803-L806
go
train
// Close stops listening on the UDP address. Already Accepted connections are not closed.
func (l *Listener) Close() error
// Close stops listening on the UDP address. Already Accepted connections are not closed. func (l *Listener) Close() error
{ close(l.die) return l.conn.Close() }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L809-L817
go
train
// closeSession notify the listener that a session has closed
func (l *Listener) closeSession(remote net.Addr) (ret bool)
// closeSession notify the listener that a session has closed func (l *Listener) closeSession(remote net.Addr) (ret bool)
{ l.sessionLock.Lock() defer l.sessionLock.Unlock() if _, ok := l.sessions[remote.String()]; ok { delete(l.sessions, remote.String()) return true } return false }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L827-L838
go
train
// ListenWithOptions listens for incoming KCP packets addressed to the local address laddr on the network "udp" with packet encryption, // dataShards, parityShards defines Reed-Solomon Erasure Coding parameters
func ListenWithOptions(laddr string, block BlockCrypt, dataShards, parityShards int) (*Listener, error)
// ListenWithOptions listens for incoming KCP packets addressed to the local address laddr on the network "udp" with packet encryption, // dataShards, parityShards defines Reed-Solomon Erasure Coding parameters func ListenWithOptions(laddr string, block BlockCrypt, dataShards, parityShards int) (*Listener, error)
{ udpaddr, err := net.ResolveUDPAddr("udp", laddr) if err != nil { return nil, errors.Wrap(err, "net.ResolveUDPAddr") } conn, err := net.ListenUDP("udp", udpaddr) if err != nil { return nil, errors.Wrap(err, "net.ListenUDP") } return ServeConn(block, dataShards, parityShards, conn) }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L841-L863
go
train
// ServeConn serves KCP protocol for a single packet connection.
func ServeConn(block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*Listener, error)
// ServeConn serves KCP protocol for a single packet connection. func ServeConn(block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*Listener, error)
{ l := new(Listener) l.conn = conn l.sessions = make(map[string]*UDPSession) l.chAccepts = make(chan *UDPSession, acceptBacklog) l.chSessionClosed = make(chan net.Addr) l.die = make(chan struct{}) l.dataShards = dataShards l.parityShards = parityShards l.block = block l.fecDecoder = newFECDecoder(rxFECMulti*(dataShards+parityShards), dataShards, parityShards) // calculate header size if l.block != nil { l.headerSize += cryptHeaderSize } if l.fecDecoder != nil { l.headerSize += fecHeaderSizePlus2 } go l.monitor() return l, nil }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L869-L886
go
train
// DialWithOptions connects to the remote address "raddr" on the network "udp" with packet encryption
func DialWithOptions(raddr string, block BlockCrypt, dataShards, parityShards int) (*UDPSession, error)
// DialWithOptions connects to the remote address "raddr" on the network "udp" with packet encryption func DialWithOptions(raddr string, block BlockCrypt, dataShards, parityShards int) (*UDPSession, error)
{ // network type detection udpaddr, err := net.ResolveUDPAddr("udp", raddr) if err != nil { return nil, errors.Wrap(err, "net.ResolveUDPAddr") } network := "udp4" if udpaddr.IP.To4() == nil { network = "udp" } conn, err := net.ListenUDP(network, nil) if err != nil { return nil, errors.Wrap(err, "net.DialUDP") } return NewConn(raddr, block, dataShards, parityShards, conn) }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
sess.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L889-L898
go
train
// NewConn establishes a session and talks KCP protocol over a packet connection.
func NewConn(raddr string, block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*UDPSession, error)
// NewConn establishes a session and talks KCP protocol over a packet connection. func NewConn(raddr string, block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*UDPSession, error)
{ udpaddr, err := net.ResolveUDPAddr("udp", raddr) if err != nil { return nil, errors.Wrap(err, "net.ResolveUDPAddr") } var convid uint32 binary.Read(rand.Reader, binary.LittleEndian, &convid) return newUDPSession(convid, dataShards, parityShards, nil, conn, udpaddr, block), nil }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
snmp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/snmp.go#L71-L99
go
train
// ToSlice returns current snmp info as slice
func (s *Snmp) ToSlice() []string
// ToSlice returns current snmp info as slice func (s *Snmp) ToSlice() []string
{ snmp := s.Copy() return []string{ fmt.Sprint(snmp.BytesSent), fmt.Sprint(snmp.BytesReceived), fmt.Sprint(snmp.MaxConn), fmt.Sprint(snmp.ActiveOpens), fmt.Sprint(snmp.PassiveOpens), fmt.Sprint(snmp.CurrEstab), fmt.Sprint(snmp.InErrs), fmt.Sprint(snmp.InCsumErrors), fmt.Sprint(snmp.KCPInErrors), fmt.Sprint(snmp.InPkts), fmt.Sprint(snmp.OutPkts), fmt.Sprint(snmp.InSegs), fmt.Sprint(snmp.OutSegs), fmt.Sprint(snmp.InBytes), fmt.Sprint(snmp.OutBytes), fmt.Sprint(snmp.RetransSegs), fmt.Sprint(snmp.FastRetransSegs), fmt.Sprint(snmp.EarlyRetransSegs), fmt.Sprint(snmp.LostSegs), fmt.Sprint(snmp.RepeatSegs), fmt.Sprint(snmp.FECParityShards), fmt.Sprint(snmp.FECErrs), fmt.Sprint(snmp.FECRecovered), fmt.Sprint(snmp.FECShortShards), } }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
snmp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/snmp.go#L102-L129
go
train
// Copy make a copy of current snmp snapshot
func (s *Snmp) Copy() *Snmp
// Copy make a copy of current snmp snapshot func (s *Snmp) Copy() *Snmp
{ d := newSnmp() d.BytesSent = atomic.LoadUint64(&s.BytesSent) d.BytesReceived = atomic.LoadUint64(&s.BytesReceived) d.MaxConn = atomic.LoadUint64(&s.MaxConn) d.ActiveOpens = atomic.LoadUint64(&s.ActiveOpens) d.PassiveOpens = atomic.LoadUint64(&s.PassiveOpens) d.CurrEstab = atomic.LoadUint64(&s.CurrEstab) d.InErrs = atomic.LoadUint64(&s.InErrs) d.InCsumErrors = atomic.LoadUint64(&s.InCsumErrors) d.KCPInErrors = atomic.LoadUint64(&s.KCPInErrors) d.InPkts = atomic.LoadUint64(&s.InPkts) d.OutPkts = atomic.LoadUint64(&s.OutPkts) d.InSegs = atomic.LoadUint64(&s.InSegs) d.OutSegs = atomic.LoadUint64(&s.OutSegs) d.InBytes = atomic.LoadUint64(&s.InBytes) d.OutBytes = atomic.LoadUint64(&s.OutBytes) d.RetransSegs = atomic.LoadUint64(&s.RetransSegs) d.FastRetransSegs = atomic.LoadUint64(&s.FastRetransSegs) d.EarlyRetransSegs = atomic.LoadUint64(&s.EarlyRetransSegs) d.LostSegs = atomic.LoadUint64(&s.LostSegs) d.RepeatSegs = atomic.LoadUint64(&s.RepeatSegs) d.FECParityShards = atomic.LoadUint64(&s.FECParityShards) d.FECErrs = atomic.LoadUint64(&s.FECErrs) d.FECRecovered = atomic.LoadUint64(&s.FECRecovered) d.FECShortShards = atomic.LoadUint64(&s.FECShortShards) return d }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
snmp.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/snmp.go#L132-L157
go
train
// Reset values to zero
func (s *Snmp) Reset()
// Reset values to zero func (s *Snmp) Reset()
{ atomic.StoreUint64(&s.BytesSent, 0) atomic.StoreUint64(&s.BytesReceived, 0) atomic.StoreUint64(&s.MaxConn, 0) atomic.StoreUint64(&s.ActiveOpens, 0) atomic.StoreUint64(&s.PassiveOpens, 0) atomic.StoreUint64(&s.CurrEstab, 0) atomic.StoreUint64(&s.InErrs, 0) atomic.StoreUint64(&s.InCsumErrors, 0) atomic.StoreUint64(&s.KCPInErrors, 0) atomic.StoreUint64(&s.InPkts, 0) atomic.StoreUint64(&s.OutPkts, 0) atomic.StoreUint64(&s.InSegs, 0) atomic.StoreUint64(&s.OutSegs, 0) atomic.StoreUint64(&s.InBytes, 0) atomic.StoreUint64(&s.OutBytes, 0) atomic.StoreUint64(&s.RetransSegs, 0) atomic.StoreUint64(&s.FastRetransSegs, 0) atomic.StoreUint64(&s.EarlyRetransSegs, 0) atomic.StoreUint64(&s.LostSegs, 0) atomic.StoreUint64(&s.RepeatSegs, 0) atomic.StoreUint64(&s.FECParityShards, 0) atomic.StoreUint64(&s.FECErrs, 0) atomic.StoreUint64(&s.FECRecovered, 0) atomic.StoreUint64(&s.FECShortShards, 0) }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
crypt.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/crypt.go#L44-L48
go
train
// NewSalsa20BlockCrypt https://en.wikipedia.org/wiki/Salsa20
func NewSalsa20BlockCrypt(key []byte) (BlockCrypt, error)
// NewSalsa20BlockCrypt https://en.wikipedia.org/wiki/Salsa20 func NewSalsa20BlockCrypt(key []byte) (BlockCrypt, error)
{ c := new(salsa20BlockCrypt) copy(c.key[:], key) return c, nil }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
crypt.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/crypt.go#L66-L74
go
train
// NewSM4BlockCrypt https://github.com/tjfoc/gmsm/tree/master/sm4
func NewSM4BlockCrypt(key []byte) (BlockCrypt, error)
// NewSM4BlockCrypt https://github.com/tjfoc/gmsm/tree/master/sm4 func NewSM4BlockCrypt(key []byte) (BlockCrypt, error)
{ c := new(sm4BlockCrypt) block, err := sm4.NewCipher(key) if err != nil { return nil, err } c.block = block return c, nil }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
crypt.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/crypt.go#L86-L94
go
train
// NewTwofishBlockCrypt https://en.wikipedia.org/wiki/Twofish
func NewTwofishBlockCrypt(key []byte) (BlockCrypt, error)
// NewTwofishBlockCrypt https://en.wikipedia.org/wiki/Twofish func NewTwofishBlockCrypt(key []byte) (BlockCrypt, error)
{ c := new(twofishBlockCrypt) block, err := twofish.NewCipher(key) if err != nil { return nil, err } c.block = block return c, nil }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
crypt.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/crypt.go#L106-L114
go
train
// NewTripleDESBlockCrypt https://en.wikipedia.org/wiki/Triple_DES
func NewTripleDESBlockCrypt(key []byte) (BlockCrypt, error)
// NewTripleDESBlockCrypt https://en.wikipedia.org/wiki/Triple_DES func NewTripleDESBlockCrypt(key []byte) (BlockCrypt, error)
{ c := new(tripleDESBlockCrypt) block, err := des.NewTripleDESCipher(key) if err != nil { return nil, err } c.block = block return c, nil }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
crypt.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/crypt.go#L126-L134
go
train
// NewCast5BlockCrypt https://en.wikipedia.org/wiki/CAST-128
func NewCast5BlockCrypt(key []byte) (BlockCrypt, error)
// NewCast5BlockCrypt https://en.wikipedia.org/wiki/CAST-128 func NewCast5BlockCrypt(key []byte) (BlockCrypt, error)
{ c := new(cast5BlockCrypt) block, err := cast5.NewCipher(key) if err != nil { return nil, err } c.block = block return c, nil }
xtaci/kcp-go
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
crypt.go
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/crypt.go#L146-L154
go
train
// NewBlowfishBlockCrypt https://en.wikipedia.org/wiki/Blowfish_(cipher)
func NewBlowfishBlockCrypt(key []byte) (BlockCrypt, error)
// NewBlowfishBlockCrypt https://en.wikipedia.org/wiki/Blowfish_(cipher) func NewBlowfishBlockCrypt(key []byte) (BlockCrypt, error)
{ c := new(blowfishBlockCrypt) block, err := blowfish.NewCipher(key) if err != nil { return nil, err } c.block = block return c, nil }