repo
stringlengths 5
67
| path
stringlengths 4
218
| func_name
stringlengths 0
151
| original_string
stringlengths 52
373k
| language
stringclasses 6
values | code
stringlengths 52
373k
| code_tokens
listlengths 10
512
| docstring
stringlengths 3
47.2k
| docstring_tokens
listlengths 3
234
| sha
stringlengths 40
40
| url
stringlengths 85
339
| partition
stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
golang/mock
|
gomock/internal/mock_gomock/mock_matcher.go
|
Matches
|
func (m *MockMatcher) Matches(arg0 interface{}) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Matches", arg0)
ret0, _ := ret[0].(bool)
return ret0
}
|
go
|
func (m *MockMatcher) Matches(arg0 interface{}) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Matches", arg0)
ret0, _ := ret[0].(bool)
return ret0
}
|
[
"func",
"(",
"m",
"*",
"MockMatcher",
")",
"Matches",
"(",
"arg0",
"interface",
"{",
"}",
")",
"bool",
"{",
"m",
".",
"ctrl",
".",
"T",
".",
"Helper",
"(",
")",
"\n",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"Matches\"",
",",
"arg0",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"bool",
")",
"\n",
"return",
"ret0",
"\n",
"}"
] |
// Matches mocks base method
|
[
"Matches",
"mocks",
"base",
"method"
] |
937870445b8bddd7f05ea90e81c58ebe83681534
|
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/internal/mock_gomock/mock_matcher.go#L36-L41
|
train
|
golang/mock
|
gomock/internal/mock_gomock/mock_matcher.go
|
Matches
|
func (mr *MockMatcherMockRecorder) Matches(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Matches", reflect.TypeOf((*MockMatcher)(nil).Matches), arg0)
}
|
go
|
func (mr *MockMatcherMockRecorder) Matches(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Matches", reflect.TypeOf((*MockMatcher)(nil).Matches), arg0)
}
|
[
"func",
"(",
"mr",
"*",
"MockMatcherMockRecorder",
")",
"Matches",
"(",
"arg0",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"mr",
".",
"mock",
".",
"ctrl",
".",
"T",
".",
"Helper",
"(",
")",
"\n",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"Matches\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockMatcher",
")",
"(",
"nil",
")",
".",
"Matches",
")",
",",
"arg0",
")",
"\n",
"}"
] |
// Matches indicates an expected call of Matches
|
[
"Matches",
"indicates",
"an",
"expected",
"call",
"of",
"Matches"
] |
937870445b8bddd7f05ea90e81c58ebe83681534
|
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/internal/mock_gomock/mock_matcher.go#L44-L47
|
train
|
golang/mock
|
gomock/internal/mock_gomock/mock_matcher.go
|
String
|
func (m *MockMatcher) String() string {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "String")
ret0, _ := ret[0].(string)
return ret0
}
|
go
|
func (m *MockMatcher) String() string {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "String")
ret0, _ := ret[0].(string)
return ret0
}
|
[
"func",
"(",
"m",
"*",
"MockMatcher",
")",
"String",
"(",
")",
"string",
"{",
"m",
".",
"ctrl",
".",
"T",
".",
"Helper",
"(",
")",
"\n",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"String\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"string",
")",
"\n",
"return",
"ret0",
"\n",
"}"
] |
// String mocks base method
|
[
"String",
"mocks",
"base",
"method"
] |
937870445b8bddd7f05ea90e81c58ebe83681534
|
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/internal/mock_gomock/mock_matcher.go#L50-L55
|
train
|
golang/mock
|
mockgen/parse.go
|
parseFile
|
func (p *fileParser) parseFile(importPath string, file *ast.File) (*model.Package, error) {
allImports, dotImports := importsOfFile(file)
// Don't stomp imports provided by -imports. Those should take precedence.
for pkg, path := range allImports {
if _, ok := p.imports[pkg]; !ok {
p.imports[pkg] = path
}
}
// Add imports from auxiliary files, which might be needed for embedded interfaces.
// Don't stomp any other imports.
for _, f := range p.auxFiles {
auxImports, _ := importsOfFile(f)
for pkg, path := range auxImports {
if _, ok := p.imports[pkg]; !ok {
p.imports[pkg] = path
}
}
}
var is []*model.Interface
for ni := range iterInterfaces(file) {
i, err := p.parseInterface(ni.name.String(), importPath, ni.it)
if err != nil {
return nil, err
}
is = append(is, i)
}
return &model.Package{
Name: file.Name.String(),
Interfaces: is,
DotImports: dotImports,
}, nil
}
|
go
|
func (p *fileParser) parseFile(importPath string, file *ast.File) (*model.Package, error) {
allImports, dotImports := importsOfFile(file)
// Don't stomp imports provided by -imports. Those should take precedence.
for pkg, path := range allImports {
if _, ok := p.imports[pkg]; !ok {
p.imports[pkg] = path
}
}
// Add imports from auxiliary files, which might be needed for embedded interfaces.
// Don't stomp any other imports.
for _, f := range p.auxFiles {
auxImports, _ := importsOfFile(f)
for pkg, path := range auxImports {
if _, ok := p.imports[pkg]; !ok {
p.imports[pkg] = path
}
}
}
var is []*model.Interface
for ni := range iterInterfaces(file) {
i, err := p.parseInterface(ni.name.String(), importPath, ni.it)
if err != nil {
return nil, err
}
is = append(is, i)
}
return &model.Package{
Name: file.Name.String(),
Interfaces: is,
DotImports: dotImports,
}, nil
}
|
[
"func",
"(",
"p",
"*",
"fileParser",
")",
"parseFile",
"(",
"importPath",
"string",
",",
"file",
"*",
"ast",
".",
"File",
")",
"(",
"*",
"model",
".",
"Package",
",",
"error",
")",
"{",
"allImports",
",",
"dotImports",
":=",
"importsOfFile",
"(",
"file",
")",
"\n",
"for",
"pkg",
",",
"path",
":=",
"range",
"allImports",
"{",
"if",
"_",
",",
"ok",
":=",
"p",
".",
"imports",
"[",
"pkg",
"]",
";",
"!",
"ok",
"{",
"p",
".",
"imports",
"[",
"pkg",
"]",
"=",
"path",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"p",
".",
"auxFiles",
"{",
"auxImports",
",",
"_",
":=",
"importsOfFile",
"(",
"f",
")",
"\n",
"for",
"pkg",
",",
"path",
":=",
"range",
"auxImports",
"{",
"if",
"_",
",",
"ok",
":=",
"p",
".",
"imports",
"[",
"pkg",
"]",
";",
"!",
"ok",
"{",
"p",
".",
"imports",
"[",
"pkg",
"]",
"=",
"path",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"is",
"[",
"]",
"*",
"model",
".",
"Interface",
"\n",
"for",
"ni",
":=",
"range",
"iterInterfaces",
"(",
"file",
")",
"{",
"i",
",",
"err",
":=",
"p",
".",
"parseInterface",
"(",
"ni",
".",
"name",
".",
"String",
"(",
")",
",",
"importPath",
",",
"ni",
".",
"it",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"is",
"=",
"append",
"(",
"is",
",",
"i",
")",
"\n",
"}",
"\n",
"return",
"&",
"model",
".",
"Package",
"{",
"Name",
":",
"file",
".",
"Name",
".",
"String",
"(",
")",
",",
"Interfaces",
":",
"is",
",",
"DotImports",
":",
"dotImports",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// parseFile loads all file imports and auxiliary files import into the
// fileParser, parses all file interfaces and returns package model.
|
[
"parseFile",
"loads",
"all",
"file",
"imports",
"and",
"auxiliary",
"files",
"import",
"into",
"the",
"fileParser",
"parses",
"all",
"file",
"interfaces",
"and",
"returns",
"package",
"model",
"."
] |
937870445b8bddd7f05ea90e81c58ebe83681534
|
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/parse.go#L161-L193
|
train
|
golang/mock
|
mockgen/parse.go
|
parsePackage
|
func (p *fileParser) parsePackage(path string) error {
var pkgs map[string]*ast.Package
if imp, err := build.Import(path, p.srcDir, build.FindOnly); err != nil {
return err
} else if pkgs, err = parser.ParseDir(p.fileSet, imp.Dir, nil, 0); err != nil {
return err
}
for _, pkg := range pkgs {
file := ast.MergePackageFiles(pkg, ast.FilterFuncDuplicates|ast.FilterUnassociatedComments|ast.FilterImportDuplicates)
if _, ok := p.importedInterfaces[path]; !ok {
p.importedInterfaces[path] = make(map[string]*ast.InterfaceType)
}
for ni := range iterInterfaces(file) {
p.importedInterfaces[path][ni.name.Name] = ni.it
}
imports, _ := importsOfFile(file)
for pkgName, pkgPath := range imports {
if _, ok := p.imports[pkgName]; !ok {
p.imports[pkgName] = pkgPath
}
}
}
return nil
}
|
go
|
func (p *fileParser) parsePackage(path string) error {
var pkgs map[string]*ast.Package
if imp, err := build.Import(path, p.srcDir, build.FindOnly); err != nil {
return err
} else if pkgs, err = parser.ParseDir(p.fileSet, imp.Dir, nil, 0); err != nil {
return err
}
for _, pkg := range pkgs {
file := ast.MergePackageFiles(pkg, ast.FilterFuncDuplicates|ast.FilterUnassociatedComments|ast.FilterImportDuplicates)
if _, ok := p.importedInterfaces[path]; !ok {
p.importedInterfaces[path] = make(map[string]*ast.InterfaceType)
}
for ni := range iterInterfaces(file) {
p.importedInterfaces[path][ni.name.Name] = ni.it
}
imports, _ := importsOfFile(file)
for pkgName, pkgPath := range imports {
if _, ok := p.imports[pkgName]; !ok {
p.imports[pkgName] = pkgPath
}
}
}
return nil
}
|
[
"func",
"(",
"p",
"*",
"fileParser",
")",
"parsePackage",
"(",
"path",
"string",
")",
"error",
"{",
"var",
"pkgs",
"map",
"[",
"string",
"]",
"*",
"ast",
".",
"Package",
"\n",
"if",
"imp",
",",
"err",
":=",
"build",
".",
"Import",
"(",
"path",
",",
"p",
".",
"srcDir",
",",
"build",
".",
"FindOnly",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"if",
"pkgs",
",",
"err",
"=",
"parser",
".",
"ParseDir",
"(",
"p",
".",
"fileSet",
",",
"imp",
".",
"Dir",
",",
"nil",
",",
"0",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"pkg",
":=",
"range",
"pkgs",
"{",
"file",
":=",
"ast",
".",
"MergePackageFiles",
"(",
"pkg",
",",
"ast",
".",
"FilterFuncDuplicates",
"|",
"ast",
".",
"FilterUnassociatedComments",
"|",
"ast",
".",
"FilterImportDuplicates",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"p",
".",
"importedInterfaces",
"[",
"path",
"]",
";",
"!",
"ok",
"{",
"p",
".",
"importedInterfaces",
"[",
"path",
"]",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"ast",
".",
"InterfaceType",
")",
"\n",
"}",
"\n",
"for",
"ni",
":=",
"range",
"iterInterfaces",
"(",
"file",
")",
"{",
"p",
".",
"importedInterfaces",
"[",
"path",
"]",
"[",
"ni",
".",
"name",
".",
"Name",
"]",
"=",
"ni",
".",
"it",
"\n",
"}",
"\n",
"imports",
",",
"_",
":=",
"importsOfFile",
"(",
"file",
")",
"\n",
"for",
"pkgName",
",",
"pkgPath",
":=",
"range",
"imports",
"{",
"if",
"_",
",",
"ok",
":=",
"p",
".",
"imports",
"[",
"pkgName",
"]",
";",
"!",
"ok",
"{",
"p",
".",
"imports",
"[",
"pkgName",
"]",
"=",
"pkgPath",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// parsePackage loads package specified by path, parses it and populates
// corresponding imports and importedInterfaces into the fileParser.
|
[
"parsePackage",
"loads",
"package",
"specified",
"by",
"path",
"parses",
"it",
"and",
"populates",
"corresponding",
"imports",
"and",
"importedInterfaces",
"into",
"the",
"fileParser",
"."
] |
937870445b8bddd7f05ea90e81c58ebe83681534
|
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/parse.go#L197-L220
|
train
|
golang/mock
|
mockgen/parse.go
|
importsOfFile
|
func importsOfFile(file *ast.File) (normalImports map[string]string, dotImports []string) {
normalImports = make(map[string]string)
dotImports = make([]string, 0)
for _, is := range file.Imports {
var pkgName string
importPath := is.Path.Value[1 : len(is.Path.Value)-1] // remove quotes
if is.Name != nil {
// Named imports are always certain.
if is.Name.Name == "_" {
continue
}
pkgName = is.Name.Name
} else {
pkg, err := build.Import(importPath, "", 0)
if err != nil {
// Fallback to import path suffix. Note that this is uncertain.
_, last := path.Split(importPath)
// If the last path component has dots, the first dot-delimited
// field is used as the name.
pkgName = strings.SplitN(last, ".", 2)[0]
} else {
pkgName = pkg.Name
}
}
if pkgName == "." {
dotImports = append(dotImports, importPath)
} else {
if _, ok := normalImports[pkgName]; ok {
log.Fatalf("imported package collision: %q imported twice", pkgName)
}
normalImports[pkgName] = importPath
}
}
return
}
|
go
|
func importsOfFile(file *ast.File) (normalImports map[string]string, dotImports []string) {
normalImports = make(map[string]string)
dotImports = make([]string, 0)
for _, is := range file.Imports {
var pkgName string
importPath := is.Path.Value[1 : len(is.Path.Value)-1] // remove quotes
if is.Name != nil {
// Named imports are always certain.
if is.Name.Name == "_" {
continue
}
pkgName = is.Name.Name
} else {
pkg, err := build.Import(importPath, "", 0)
if err != nil {
// Fallback to import path suffix. Note that this is uncertain.
_, last := path.Split(importPath)
// If the last path component has dots, the first dot-delimited
// field is used as the name.
pkgName = strings.SplitN(last, ".", 2)[0]
} else {
pkgName = pkg.Name
}
}
if pkgName == "." {
dotImports = append(dotImports, importPath)
} else {
if _, ok := normalImports[pkgName]; ok {
log.Fatalf("imported package collision: %q imported twice", pkgName)
}
normalImports[pkgName] = importPath
}
}
return
}
|
[
"func",
"importsOfFile",
"(",
"file",
"*",
"ast",
".",
"File",
")",
"(",
"normalImports",
"map",
"[",
"string",
"]",
"string",
",",
"dotImports",
"[",
"]",
"string",
")",
"{",
"normalImports",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"dotImports",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"for",
"_",
",",
"is",
":=",
"range",
"file",
".",
"Imports",
"{",
"var",
"pkgName",
"string",
"\n",
"importPath",
":=",
"is",
".",
"Path",
".",
"Value",
"[",
"1",
":",
"len",
"(",
"is",
".",
"Path",
".",
"Value",
")",
"-",
"1",
"]",
"\n",
"if",
"is",
".",
"Name",
"!=",
"nil",
"{",
"if",
"is",
".",
"Name",
".",
"Name",
"==",
"\"_\"",
"{",
"continue",
"\n",
"}",
"\n",
"pkgName",
"=",
"is",
".",
"Name",
".",
"Name",
"\n",
"}",
"else",
"{",
"pkg",
",",
"err",
":=",
"build",
".",
"Import",
"(",
"importPath",
",",
"\"\"",
",",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"_",
",",
"last",
":=",
"path",
".",
"Split",
"(",
"importPath",
")",
"\n",
"pkgName",
"=",
"strings",
".",
"SplitN",
"(",
"last",
",",
"\".\"",
",",
"2",
")",
"[",
"0",
"]",
"\n",
"}",
"else",
"{",
"pkgName",
"=",
"pkg",
".",
"Name",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"pkgName",
"==",
"\".\"",
"{",
"dotImports",
"=",
"append",
"(",
"dotImports",
",",
"importPath",
")",
"\n",
"}",
"else",
"{",
"if",
"_",
",",
"ok",
":=",
"normalImports",
"[",
"pkgName",
"]",
";",
"ok",
"{",
"log",
".",
"Fatalf",
"(",
"\"imported package collision: %q imported twice\"",
",",
"pkgName",
")",
"\n",
"}",
"\n",
"normalImports",
"[",
"pkgName",
"]",
"=",
"importPath",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// importsOfFile returns a map of package name to import path
// of the imports in file.
|
[
"importsOfFile",
"returns",
"a",
"map",
"of",
"package",
"name",
"to",
"import",
"path",
"of",
"the",
"imports",
"in",
"file",
"."
] |
937870445b8bddd7f05ea90e81c58ebe83681534
|
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/parse.go#L444-L481
|
train
|
golang/mock
|
mockgen/parse.go
|
iterInterfaces
|
func iterInterfaces(file *ast.File) <-chan namedInterface {
ch := make(chan namedInterface)
go func() {
for _, decl := range file.Decls {
gd, ok := decl.(*ast.GenDecl)
if !ok || gd.Tok != token.TYPE {
continue
}
for _, spec := range gd.Specs {
ts, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
it, ok := ts.Type.(*ast.InterfaceType)
if !ok {
continue
}
ch <- namedInterface{ts.Name, it}
}
}
close(ch)
}()
return ch
}
|
go
|
func iterInterfaces(file *ast.File) <-chan namedInterface {
ch := make(chan namedInterface)
go func() {
for _, decl := range file.Decls {
gd, ok := decl.(*ast.GenDecl)
if !ok || gd.Tok != token.TYPE {
continue
}
for _, spec := range gd.Specs {
ts, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
it, ok := ts.Type.(*ast.InterfaceType)
if !ok {
continue
}
ch <- namedInterface{ts.Name, it}
}
}
close(ch)
}()
return ch
}
|
[
"func",
"iterInterfaces",
"(",
"file",
"*",
"ast",
".",
"File",
")",
"<-",
"chan",
"namedInterface",
"{",
"ch",
":=",
"make",
"(",
"chan",
"namedInterface",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"for",
"_",
",",
"decl",
":=",
"range",
"file",
".",
"Decls",
"{",
"gd",
",",
"ok",
":=",
"decl",
".",
"(",
"*",
"ast",
".",
"GenDecl",
")",
"\n",
"if",
"!",
"ok",
"||",
"gd",
".",
"Tok",
"!=",
"token",
".",
"TYPE",
"{",
"continue",
"\n",
"}",
"\n",
"for",
"_",
",",
"spec",
":=",
"range",
"gd",
".",
"Specs",
"{",
"ts",
",",
"ok",
":=",
"spec",
".",
"(",
"*",
"ast",
".",
"TypeSpec",
")",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"it",
",",
"ok",
":=",
"ts",
".",
"Type",
".",
"(",
"*",
"ast",
".",
"InterfaceType",
")",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"ch",
"<-",
"namedInterface",
"{",
"ts",
".",
"Name",
",",
"it",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"close",
"(",
"ch",
")",
"\n",
"}",
"(",
")",
"\n",
"return",
"ch",
"\n",
"}"
] |
// Create an iterator over all interfaces in file.
|
[
"Create",
"an",
"iterator",
"over",
"all",
"interfaces",
"in",
"file",
"."
] |
937870445b8bddd7f05ea90e81c58ebe83681534
|
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/parse.go#L489-L513
|
train
|
golang/mock
|
mockgen/parse.go
|
isVariadic
|
func isVariadic(f *ast.FuncType) bool {
nargs := len(f.Params.List)
if nargs == 0 {
return false
}
_, ok := f.Params.List[nargs-1].Type.(*ast.Ellipsis)
return ok
}
|
go
|
func isVariadic(f *ast.FuncType) bool {
nargs := len(f.Params.List)
if nargs == 0 {
return false
}
_, ok := f.Params.List[nargs-1].Type.(*ast.Ellipsis)
return ok
}
|
[
"func",
"isVariadic",
"(",
"f",
"*",
"ast",
".",
"FuncType",
")",
"bool",
"{",
"nargs",
":=",
"len",
"(",
"f",
".",
"Params",
".",
"List",
")",
"\n",
"if",
"nargs",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"_",
",",
"ok",
":=",
"f",
".",
"Params",
".",
"List",
"[",
"nargs",
"-",
"1",
"]",
".",
"Type",
".",
"(",
"*",
"ast",
".",
"Ellipsis",
")",
"\n",
"return",
"ok",
"\n",
"}"
] |
// isVariadic returns whether the function is variadic.
|
[
"isVariadic",
"returns",
"whether",
"the",
"function",
"is",
"variadic",
"."
] |
937870445b8bddd7f05ea90e81c58ebe83681534
|
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/parse.go#L516-L523
|
train
|
golang/mock
|
gomock/controller.go
|
NewController
|
func NewController(t TestReporter) *Controller {
h, ok := t.(TestHelper)
if !ok {
h = nopTestHelper{t}
}
return &Controller{
T: h,
expectedCalls: newCallSet(),
}
}
|
go
|
func NewController(t TestReporter) *Controller {
h, ok := t.(TestHelper)
if !ok {
h = nopTestHelper{t}
}
return &Controller{
T: h,
expectedCalls: newCallSet(),
}
}
|
[
"func",
"NewController",
"(",
"t",
"TestReporter",
")",
"*",
"Controller",
"{",
"h",
",",
"ok",
":=",
"t",
".",
"(",
"TestHelper",
")",
"\n",
"if",
"!",
"ok",
"{",
"h",
"=",
"nopTestHelper",
"{",
"t",
"}",
"\n",
"}",
"\n",
"return",
"&",
"Controller",
"{",
"T",
":",
"h",
",",
"expectedCalls",
":",
"newCallSet",
"(",
")",
",",
"}",
"\n",
"}"
] |
// NewController returns a new Controller. It is the preferred way to create a
// Controller.
|
[
"NewController",
"returns",
"a",
"new",
"Controller",
".",
"It",
"is",
"the",
"preferred",
"way",
"to",
"create",
"a",
"Controller",
"."
] |
937870445b8bddd7f05ea90e81c58ebe83681534
|
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/controller.go#L118-L128
|
train
|
golang/mock
|
gomock/controller.go
|
WithContext
|
func WithContext(ctx context.Context, t TestReporter) (*Controller, context.Context) {
h, ok := t.(TestHelper)
if !ok {
h = nopTestHelper{t}
}
ctx, cancel := context.WithCancel(ctx)
return NewController(&cancelReporter{h, cancel}), ctx
}
|
go
|
func WithContext(ctx context.Context, t TestReporter) (*Controller, context.Context) {
h, ok := t.(TestHelper)
if !ok {
h = nopTestHelper{t}
}
ctx, cancel := context.WithCancel(ctx)
return NewController(&cancelReporter{h, cancel}), ctx
}
|
[
"func",
"WithContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"t",
"TestReporter",
")",
"(",
"*",
"Controller",
",",
"context",
".",
"Context",
")",
"{",
"h",
",",
"ok",
":=",
"t",
".",
"(",
"TestHelper",
")",
"\n",
"if",
"!",
"ok",
"{",
"h",
"=",
"nopTestHelper",
"{",
"t",
"}",
"\n",
"}",
"\n",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithCancel",
"(",
"ctx",
")",
"\n",
"return",
"NewController",
"(",
"&",
"cancelReporter",
"{",
"h",
",",
"cancel",
"}",
")",
",",
"ctx",
"\n",
"}"
] |
// WithContext returns a new Controller and a Context, which is cancelled on any
// fatal failure.
|
[
"WithContext",
"returns",
"a",
"new",
"Controller",
"and",
"a",
"Context",
"which",
"is",
"cancelled",
"on",
"any",
"fatal",
"failure",
"."
] |
937870445b8bddd7f05ea90e81c58ebe83681534
|
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/controller.go#L145-L153
|
train
|
golang/mock
|
gomock/controller.go
|
RecordCall
|
func (ctrl *Controller) RecordCall(receiver interface{}, method string, args ...interface{}) *Call {
ctrl.T.Helper()
recv := reflect.ValueOf(receiver)
for i := 0; i < recv.Type().NumMethod(); i++ {
if recv.Type().Method(i).Name == method {
return ctrl.RecordCallWithMethodType(receiver, method, recv.Method(i).Type(), args...)
}
}
ctrl.T.Fatalf("gomock: failed finding method %s on %T", method, receiver)
panic("unreachable")
}
|
go
|
func (ctrl *Controller) RecordCall(receiver interface{}, method string, args ...interface{}) *Call {
ctrl.T.Helper()
recv := reflect.ValueOf(receiver)
for i := 0; i < recv.Type().NumMethod(); i++ {
if recv.Type().Method(i).Name == method {
return ctrl.RecordCallWithMethodType(receiver, method, recv.Method(i).Type(), args...)
}
}
ctrl.T.Fatalf("gomock: failed finding method %s on %T", method, receiver)
panic("unreachable")
}
|
[
"func",
"(",
"ctrl",
"*",
"Controller",
")",
"RecordCall",
"(",
"receiver",
"interface",
"{",
"}",
",",
"method",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"*",
"Call",
"{",
"ctrl",
".",
"T",
".",
"Helper",
"(",
")",
"\n",
"recv",
":=",
"reflect",
".",
"ValueOf",
"(",
"receiver",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"recv",
".",
"Type",
"(",
")",
".",
"NumMethod",
"(",
")",
";",
"i",
"++",
"{",
"if",
"recv",
".",
"Type",
"(",
")",
".",
"Method",
"(",
"i",
")",
".",
"Name",
"==",
"method",
"{",
"return",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"receiver",
",",
"method",
",",
"recv",
".",
"Method",
"(",
"i",
")",
".",
"Type",
"(",
")",
",",
"args",
"...",
")",
"\n",
"}",
"\n",
"}",
"\n",
"ctrl",
".",
"T",
".",
"Fatalf",
"(",
"\"gomock: failed finding method %s on %T\"",
",",
"method",
",",
"receiver",
")",
"\n",
"panic",
"(",
"\"unreachable\"",
")",
"\n",
"}"
] |
// RecordCall is called by a mock. It should not be called by user code.
|
[
"RecordCall",
"is",
"called",
"by",
"a",
"mock",
".",
"It",
"should",
"not",
"be",
"called",
"by",
"user",
"code",
"."
] |
937870445b8bddd7f05ea90e81c58ebe83681534
|
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/controller.go#L162-L173
|
train
|
golang/mock
|
gomock/controller.go
|
RecordCallWithMethodType
|
func (ctrl *Controller) RecordCallWithMethodType(receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call {
ctrl.T.Helper()
call := newCall(ctrl.T, receiver, method, methodType, args...)
ctrl.mu.Lock()
defer ctrl.mu.Unlock()
ctrl.expectedCalls.Add(call)
return call
}
|
go
|
func (ctrl *Controller) RecordCallWithMethodType(receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call {
ctrl.T.Helper()
call := newCall(ctrl.T, receiver, method, methodType, args...)
ctrl.mu.Lock()
defer ctrl.mu.Unlock()
ctrl.expectedCalls.Add(call)
return call
}
|
[
"func",
"(",
"ctrl",
"*",
"Controller",
")",
"RecordCallWithMethodType",
"(",
"receiver",
"interface",
"{",
"}",
",",
"method",
"string",
",",
"methodType",
"reflect",
".",
"Type",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"*",
"Call",
"{",
"ctrl",
".",
"T",
".",
"Helper",
"(",
")",
"\n",
"call",
":=",
"newCall",
"(",
"ctrl",
".",
"T",
",",
"receiver",
",",
"method",
",",
"methodType",
",",
"args",
"...",
")",
"\n",
"ctrl",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ctrl",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"ctrl",
".",
"expectedCalls",
".",
"Add",
"(",
"call",
")",
"\n",
"return",
"call",
"\n",
"}"
] |
// RecordCallWithMethodType is called by a mock. It should not be called by user code.
|
[
"RecordCallWithMethodType",
"is",
"called",
"by",
"a",
"mock",
".",
"It",
"should",
"not",
"be",
"called",
"by",
"user",
"code",
"."
] |
937870445b8bddd7f05ea90e81c58ebe83681534
|
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/controller.go#L176-L186
|
train
|
golang/mock
|
gomock/controller.go
|
Call
|
func (ctrl *Controller) Call(receiver interface{}, method string, args ...interface{}) []interface{} {
ctrl.T.Helper()
// Nest this code so we can use defer to make sure the lock is released.
actions := func() []func([]interface{}) []interface{} {
ctrl.T.Helper()
ctrl.mu.Lock()
defer ctrl.mu.Unlock()
expected, err := ctrl.expectedCalls.FindMatch(receiver, method, args)
if err != nil {
origin := callerInfo(2)
ctrl.T.Fatalf("Unexpected call to %T.%v(%v) at %s because: %s", receiver, method, args, origin, err)
}
// Two things happen here:
// * the matching call no longer needs to check prerequite calls,
// * and the prerequite calls are no longer expected, so remove them.
preReqCalls := expected.dropPrereqs()
for _, preReqCall := range preReqCalls {
ctrl.expectedCalls.Remove(preReqCall)
}
actions := expected.call(args)
if expected.exhausted() {
ctrl.expectedCalls.Remove(expected)
}
return actions
}()
var rets []interface{}
for _, action := range actions {
if r := action(args); r != nil {
rets = r
}
}
return rets
}
|
go
|
func (ctrl *Controller) Call(receiver interface{}, method string, args ...interface{}) []interface{} {
ctrl.T.Helper()
// Nest this code so we can use defer to make sure the lock is released.
actions := func() []func([]interface{}) []interface{} {
ctrl.T.Helper()
ctrl.mu.Lock()
defer ctrl.mu.Unlock()
expected, err := ctrl.expectedCalls.FindMatch(receiver, method, args)
if err != nil {
origin := callerInfo(2)
ctrl.T.Fatalf("Unexpected call to %T.%v(%v) at %s because: %s", receiver, method, args, origin, err)
}
// Two things happen here:
// * the matching call no longer needs to check prerequite calls,
// * and the prerequite calls are no longer expected, so remove them.
preReqCalls := expected.dropPrereqs()
for _, preReqCall := range preReqCalls {
ctrl.expectedCalls.Remove(preReqCall)
}
actions := expected.call(args)
if expected.exhausted() {
ctrl.expectedCalls.Remove(expected)
}
return actions
}()
var rets []interface{}
for _, action := range actions {
if r := action(args); r != nil {
rets = r
}
}
return rets
}
|
[
"func",
"(",
"ctrl",
"*",
"Controller",
")",
"Call",
"(",
"receiver",
"interface",
"{",
"}",
",",
"method",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"ctrl",
".",
"T",
".",
"Helper",
"(",
")",
"\n",
"actions",
":=",
"func",
"(",
")",
"[",
"]",
"func",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"ctrl",
".",
"T",
".",
"Helper",
"(",
")",
"\n",
"ctrl",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ctrl",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"expected",
",",
"err",
":=",
"ctrl",
".",
"expectedCalls",
".",
"FindMatch",
"(",
"receiver",
",",
"method",
",",
"args",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"origin",
":=",
"callerInfo",
"(",
"2",
")",
"\n",
"ctrl",
".",
"T",
".",
"Fatalf",
"(",
"\"Unexpected call to %T.%v(%v) at %s because: %s\"",
",",
"receiver",
",",
"method",
",",
"args",
",",
"origin",
",",
"err",
")",
"\n",
"}",
"\n",
"preReqCalls",
":=",
"expected",
".",
"dropPrereqs",
"(",
")",
"\n",
"for",
"_",
",",
"preReqCall",
":=",
"range",
"preReqCalls",
"{",
"ctrl",
".",
"expectedCalls",
".",
"Remove",
"(",
"preReqCall",
")",
"\n",
"}",
"\n",
"actions",
":=",
"expected",
".",
"call",
"(",
"args",
")",
"\n",
"if",
"expected",
".",
"exhausted",
"(",
")",
"{",
"ctrl",
".",
"expectedCalls",
".",
"Remove",
"(",
"expected",
")",
"\n",
"}",
"\n",
"return",
"actions",
"\n",
"}",
"(",
")",
"\n",
"var",
"rets",
"[",
"]",
"interface",
"{",
"}",
"\n",
"for",
"_",
",",
"action",
":=",
"range",
"actions",
"{",
"if",
"r",
":=",
"action",
"(",
"args",
")",
";",
"r",
"!=",
"nil",
"{",
"rets",
"=",
"r",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"rets",
"\n",
"}"
] |
// Call is called by a mock. It should not be called by user code.
|
[
"Call",
"is",
"called",
"by",
"a",
"mock",
".",
"It",
"should",
"not",
"be",
"called",
"by",
"user",
"code",
"."
] |
937870445b8bddd7f05ea90e81c58ebe83681534
|
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/controller.go#L189-L227
|
train
|
golang/mock
|
gomock/controller.go
|
Finish
|
func (ctrl *Controller) Finish() {
ctrl.T.Helper()
ctrl.mu.Lock()
defer ctrl.mu.Unlock()
if ctrl.finished {
ctrl.T.Fatalf("Controller.Finish was called more than once. It has to be called exactly once.")
}
ctrl.finished = true
// If we're currently panicking, probably because this is a deferred call,
// pass through the panic.
if err := recover(); err != nil {
panic(err)
}
// Check that all remaining expected calls are satisfied.
failures := ctrl.expectedCalls.Failures()
for _, call := range failures {
ctrl.T.Errorf("missing call(s) to %v", call)
}
if len(failures) != 0 {
ctrl.T.Fatalf("aborting test due to missing call(s)")
}
}
|
go
|
func (ctrl *Controller) Finish() {
ctrl.T.Helper()
ctrl.mu.Lock()
defer ctrl.mu.Unlock()
if ctrl.finished {
ctrl.T.Fatalf("Controller.Finish was called more than once. It has to be called exactly once.")
}
ctrl.finished = true
// If we're currently panicking, probably because this is a deferred call,
// pass through the panic.
if err := recover(); err != nil {
panic(err)
}
// Check that all remaining expected calls are satisfied.
failures := ctrl.expectedCalls.Failures()
for _, call := range failures {
ctrl.T.Errorf("missing call(s) to %v", call)
}
if len(failures) != 0 {
ctrl.T.Fatalf("aborting test due to missing call(s)")
}
}
|
[
"func",
"(",
"ctrl",
"*",
"Controller",
")",
"Finish",
"(",
")",
"{",
"ctrl",
".",
"T",
".",
"Helper",
"(",
")",
"\n",
"ctrl",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ctrl",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"ctrl",
".",
"finished",
"{",
"ctrl",
".",
"T",
".",
"Fatalf",
"(",
"\"Controller.Finish was called more than once. It has to be called exactly once.\"",
")",
"\n",
"}",
"\n",
"ctrl",
".",
"finished",
"=",
"true",
"\n",
"if",
"err",
":=",
"recover",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"failures",
":=",
"ctrl",
".",
"expectedCalls",
".",
"Failures",
"(",
")",
"\n",
"for",
"_",
",",
"call",
":=",
"range",
"failures",
"{",
"ctrl",
".",
"T",
".",
"Errorf",
"(",
"\"missing call(s) to %v\"",
",",
"call",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"failures",
")",
"!=",
"0",
"{",
"ctrl",
".",
"T",
".",
"Fatalf",
"(",
"\"aborting test due to missing call(s)\"",
")",
"\n",
"}",
"\n",
"}"
] |
// Finish checks to see if all the methods that were expected to be called
// were called. It should be invoked for each Controller. It is not idempotent
// and therefore can only be invoked once.
|
[
"Finish",
"checks",
"to",
"see",
"if",
"all",
"the",
"methods",
"that",
"were",
"expected",
"to",
"be",
"called",
"were",
"called",
".",
"It",
"should",
"be",
"invoked",
"for",
"each",
"Controller",
".",
"It",
"is",
"not",
"idempotent",
"and",
"therefore",
"can",
"only",
"be",
"invoked",
"once",
"."
] |
937870445b8bddd7f05ea90e81c58ebe83681534
|
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/controller.go#L232-L257
|
train
|
golang/mock
|
mockgen/model/model.go
|
Imports
|
func (pkg *Package) Imports() map[string]bool {
im := make(map[string]bool)
for _, intf := range pkg.Interfaces {
intf.addImports(im)
}
return im
}
|
go
|
func (pkg *Package) Imports() map[string]bool {
im := make(map[string]bool)
for _, intf := range pkg.Interfaces {
intf.addImports(im)
}
return im
}
|
[
"func",
"(",
"pkg",
"*",
"Package",
")",
"Imports",
"(",
")",
"map",
"[",
"string",
"]",
"bool",
"{",
"im",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n",
"for",
"_",
",",
"intf",
":=",
"range",
"pkg",
".",
"Interfaces",
"{",
"intf",
".",
"addImports",
"(",
"im",
")",
"\n",
"}",
"\n",
"return",
"im",
"\n",
"}"
] |
// Imports returns the imports needed by the Package as a set of import paths.
|
[
"Imports",
"returns",
"the",
"imports",
"needed",
"by",
"the",
"Package",
"as",
"a",
"set",
"of",
"import",
"paths",
"."
] |
937870445b8bddd7f05ea90e81c58ebe83681534
|
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/model/model.go#L44-L50
|
train
|
golang/mock
|
mockgen/model/model.go
|
funcArgsFromType
|
func funcArgsFromType(t reflect.Type) (in []*Parameter, variadic *Parameter, out []*Parameter, err error) {
nin := t.NumIn()
if t.IsVariadic() {
nin--
}
var p *Parameter
for i := 0; i < nin; i++ {
p, err = parameterFromType(t.In(i))
if err != nil {
return
}
in = append(in, p)
}
if t.IsVariadic() {
p, err = parameterFromType(t.In(nin).Elem())
if err != nil {
return
}
variadic = p
}
for i := 0; i < t.NumOut(); i++ {
p, err = parameterFromType(t.Out(i))
if err != nil {
return
}
out = append(out, p)
}
return
}
|
go
|
func funcArgsFromType(t reflect.Type) (in []*Parameter, variadic *Parameter, out []*Parameter, err error) {
nin := t.NumIn()
if t.IsVariadic() {
nin--
}
var p *Parameter
for i := 0; i < nin; i++ {
p, err = parameterFromType(t.In(i))
if err != nil {
return
}
in = append(in, p)
}
if t.IsVariadic() {
p, err = parameterFromType(t.In(nin).Elem())
if err != nil {
return
}
variadic = p
}
for i := 0; i < t.NumOut(); i++ {
p, err = parameterFromType(t.Out(i))
if err != nil {
return
}
out = append(out, p)
}
return
}
|
[
"func",
"funcArgsFromType",
"(",
"t",
"reflect",
".",
"Type",
")",
"(",
"in",
"[",
"]",
"*",
"Parameter",
",",
"variadic",
"*",
"Parameter",
",",
"out",
"[",
"]",
"*",
"Parameter",
",",
"err",
"error",
")",
"{",
"nin",
":=",
"t",
".",
"NumIn",
"(",
")",
"\n",
"if",
"t",
".",
"IsVariadic",
"(",
")",
"{",
"nin",
"--",
"\n",
"}",
"\n",
"var",
"p",
"*",
"Parameter",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"nin",
";",
"i",
"++",
"{",
"p",
",",
"err",
"=",
"parameterFromType",
"(",
"t",
".",
"In",
"(",
"i",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"in",
"=",
"append",
"(",
"in",
",",
"p",
")",
"\n",
"}",
"\n",
"if",
"t",
".",
"IsVariadic",
"(",
")",
"{",
"p",
",",
"err",
"=",
"parameterFromType",
"(",
"t",
".",
"In",
"(",
"nin",
")",
".",
"Elem",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"variadic",
"=",
"p",
"\n",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"t",
".",
"NumOut",
"(",
")",
";",
"i",
"++",
"{",
"p",
",",
"err",
"=",
"parameterFromType",
"(",
"t",
".",
"Out",
"(",
"i",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"out",
"=",
"append",
"(",
"out",
",",
"p",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// t's Kind must be a reflect.Func.
|
[
"t",
"s",
"Kind",
"must",
"be",
"a",
"reflect",
".",
"Func",
"."
] |
937870445b8bddd7f05ea90e81c58ebe83681534
|
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/model/model.go#L312-L340
|
train
|
anacrolix/torrent
|
metainfo/magnet.go
|
ParseMagnetURI
|
func ParseMagnetURI(uri string) (m Magnet, err error) {
u, err := url.Parse(uri)
if err != nil {
err = fmt.Errorf("error parsing uri: %s", err)
return
}
if u.Scheme != "magnet" {
err = fmt.Errorf("unexpected scheme: %q", u.Scheme)
return
}
xt := u.Query().Get("xt")
if !strings.HasPrefix(xt, xtPrefix) {
err = fmt.Errorf("bad xt parameter")
return
}
infoHash := xt[len(xtPrefix):]
// BTIH hash can be in HEX or BASE32 encoding
// will assign appropriate func judging from symbol length
var decode func(dst, src []byte) (int, error)
switch len(infoHash) {
case 40:
decode = hex.Decode
case 32:
decode = base32.StdEncoding.Decode
}
if decode == nil {
err = fmt.Errorf("unhandled xt parameter encoding: encoded length %d", len(infoHash))
return
}
n, err := decode(m.InfoHash[:], []byte(infoHash))
if err != nil {
err = fmt.Errorf("error decoding xt: %s", err)
return
}
if n != 20 {
panic(n)
}
m.DisplayName = u.Query().Get("dn")
m.Trackers = u.Query()["tr"]
return
}
|
go
|
func ParseMagnetURI(uri string) (m Magnet, err error) {
u, err := url.Parse(uri)
if err != nil {
err = fmt.Errorf("error parsing uri: %s", err)
return
}
if u.Scheme != "magnet" {
err = fmt.Errorf("unexpected scheme: %q", u.Scheme)
return
}
xt := u.Query().Get("xt")
if !strings.HasPrefix(xt, xtPrefix) {
err = fmt.Errorf("bad xt parameter")
return
}
infoHash := xt[len(xtPrefix):]
// BTIH hash can be in HEX or BASE32 encoding
// will assign appropriate func judging from symbol length
var decode func(dst, src []byte) (int, error)
switch len(infoHash) {
case 40:
decode = hex.Decode
case 32:
decode = base32.StdEncoding.Decode
}
if decode == nil {
err = fmt.Errorf("unhandled xt parameter encoding: encoded length %d", len(infoHash))
return
}
n, err := decode(m.InfoHash[:], []byte(infoHash))
if err != nil {
err = fmt.Errorf("error decoding xt: %s", err)
return
}
if n != 20 {
panic(n)
}
m.DisplayName = u.Query().Get("dn")
m.Trackers = u.Query()["tr"]
return
}
|
[
"func",
"ParseMagnetURI",
"(",
"uri",
"string",
")",
"(",
"m",
"Magnet",
",",
"err",
"error",
")",
"{",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"uri",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"error parsing uri: %s\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"u",
".",
"Scheme",
"!=",
"\"magnet\"",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"unexpected scheme: %q\"",
",",
"u",
".",
"Scheme",
")",
"\n",
"return",
"\n",
"}",
"\n",
"xt",
":=",
"u",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"\"xt\"",
")",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"xt",
",",
"xtPrefix",
")",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"bad xt parameter\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"infoHash",
":=",
"xt",
"[",
"len",
"(",
"xtPrefix",
")",
":",
"]",
"\n",
"var",
"decode",
"func",
"(",
"dst",
",",
"src",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"\n",
"switch",
"len",
"(",
"infoHash",
")",
"{",
"case",
"40",
":",
"decode",
"=",
"hex",
".",
"Decode",
"\n",
"case",
"32",
":",
"decode",
"=",
"base32",
".",
"StdEncoding",
".",
"Decode",
"\n",
"}",
"\n",
"if",
"decode",
"==",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"unhandled xt parameter encoding: encoded length %d\"",
",",
"len",
"(",
"infoHash",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"decode",
"(",
"m",
".",
"InfoHash",
"[",
":",
"]",
",",
"[",
"]",
"byte",
"(",
"infoHash",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"error decoding xt: %s\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"n",
"!=",
"20",
"{",
"panic",
"(",
"n",
")",
"\n",
"}",
"\n",
"m",
".",
"DisplayName",
"=",
"u",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"\"dn\"",
")",
"\n",
"m",
".",
"Trackers",
"=",
"u",
".",
"Query",
"(",
")",
"[",
"\"tr\"",
"]",
"\n",
"return",
"\n",
"}"
] |
// ParseMagnetURI parses Magnet-formatted URIs into a Magnet instance
|
[
"ParseMagnetURI",
"parses",
"Magnet",
"-",
"formatted",
"URIs",
"into",
"a",
"Magnet",
"instance"
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/magnet.go#L35-L77
|
train
|
anacrolix/torrent
|
metainfo/metainfo.go
|
Load
|
func Load(r io.Reader) (*MetaInfo, error) {
var mi MetaInfo
d := bencode.NewDecoder(r)
err := d.Decode(&mi)
if err != nil {
return nil, err
}
return &mi, nil
}
|
go
|
func Load(r io.Reader) (*MetaInfo, error) {
var mi MetaInfo
d := bencode.NewDecoder(r)
err := d.Decode(&mi)
if err != nil {
return nil, err
}
return &mi, nil
}
|
[
"func",
"Load",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"*",
"MetaInfo",
",",
"error",
")",
"{",
"var",
"mi",
"MetaInfo",
"\n",
"d",
":=",
"bencode",
".",
"NewDecoder",
"(",
"r",
")",
"\n",
"err",
":=",
"d",
".",
"Decode",
"(",
"&",
"mi",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"mi",
",",
"nil",
"\n",
"}"
] |
// Load a MetaInfo from an io.Reader. Returns a non-nil error in case of
// failure.
|
[
"Load",
"a",
"MetaInfo",
"from",
"an",
"io",
".",
"Reader",
".",
"Returns",
"a",
"non",
"-",
"nil",
"error",
"in",
"case",
"of",
"failure",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/metainfo.go#L25-L33
|
train
|
anacrolix/torrent
|
metainfo/metainfo.go
|
LoadFromFile
|
func LoadFromFile(filename string) (*MetaInfo, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
return Load(f)
}
|
go
|
func LoadFromFile(filename string) (*MetaInfo, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
return Load(f)
}
|
[
"func",
"LoadFromFile",
"(",
"filename",
"string",
")",
"(",
"*",
"MetaInfo",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"return",
"Load",
"(",
"f",
")",
"\n",
"}"
] |
// Convenience function for loading a MetaInfo from a file.
|
[
"Convenience",
"function",
"for",
"loading",
"a",
"MetaInfo",
"from",
"a",
"file",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/metainfo.go#L36-L43
|
train
|
anacrolix/torrent
|
metainfo/metainfo.go
|
Write
|
func (mi MetaInfo) Write(w io.Writer) error {
return bencode.NewEncoder(w).Encode(mi)
}
|
go
|
func (mi MetaInfo) Write(w io.Writer) error {
return bencode.NewEncoder(w).Encode(mi)
}
|
[
"func",
"(",
"mi",
"MetaInfo",
")",
"Write",
"(",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"return",
"bencode",
".",
"NewEncoder",
"(",
"w",
")",
".",
"Encode",
"(",
"mi",
")",
"\n",
"}"
] |
// Encode to bencoded form.
|
[
"Encode",
"to",
"bencoded",
"form",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/metainfo.go#L55-L57
|
train
|
anacrolix/torrent
|
metainfo/metainfo.go
|
SetDefaults
|
func (mi *MetaInfo) SetDefaults() {
mi.Comment = "yoloham"
mi.CreatedBy = "github.com/anacrolix/torrent"
mi.CreationDate = time.Now().Unix()
// mi.Info.PieceLength = 256 * 1024
}
|
go
|
func (mi *MetaInfo) SetDefaults() {
mi.Comment = "yoloham"
mi.CreatedBy = "github.com/anacrolix/torrent"
mi.CreationDate = time.Now().Unix()
// mi.Info.PieceLength = 256 * 1024
}
|
[
"func",
"(",
"mi",
"*",
"MetaInfo",
")",
"SetDefaults",
"(",
")",
"{",
"mi",
".",
"Comment",
"=",
"\"yoloham\"",
"\n",
"mi",
".",
"CreatedBy",
"=",
"\"github.com/anacrolix/torrent\"",
"\n",
"mi",
".",
"CreationDate",
"=",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
"\n",
"}"
] |
// Set good default values in preparation for creating a new MetaInfo file.
|
[
"Set",
"good",
"default",
"values",
"in",
"preparation",
"for",
"creating",
"a",
"new",
"MetaInfo",
"file",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/metainfo.go#L60-L65
|
train
|
anacrolix/torrent
|
metainfo/metainfo.go
|
Magnet
|
func (mi *MetaInfo) Magnet(displayName string, infoHash Hash) (m Magnet) {
for t := range mi.UpvertedAnnounceList().DistinctValues() {
m.Trackers = append(m.Trackers, t)
}
m.DisplayName = displayName
m.InfoHash = infoHash
return
}
|
go
|
func (mi *MetaInfo) Magnet(displayName string, infoHash Hash) (m Magnet) {
for t := range mi.UpvertedAnnounceList().DistinctValues() {
m.Trackers = append(m.Trackers, t)
}
m.DisplayName = displayName
m.InfoHash = infoHash
return
}
|
[
"func",
"(",
"mi",
"*",
"MetaInfo",
")",
"Magnet",
"(",
"displayName",
"string",
",",
"infoHash",
"Hash",
")",
"(",
"m",
"Magnet",
")",
"{",
"for",
"t",
":=",
"range",
"mi",
".",
"UpvertedAnnounceList",
"(",
")",
".",
"DistinctValues",
"(",
")",
"{",
"m",
".",
"Trackers",
"=",
"append",
"(",
"m",
".",
"Trackers",
",",
"t",
")",
"\n",
"}",
"\n",
"m",
".",
"DisplayName",
"=",
"displayName",
"\n",
"m",
".",
"InfoHash",
"=",
"infoHash",
"\n",
"return",
"\n",
"}"
] |
// Creates a Magnet from a MetaInfo.
|
[
"Creates",
"a",
"Magnet",
"from",
"a",
"MetaInfo",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/metainfo.go#L68-L75
|
train
|
anacrolix/torrent
|
metainfo/metainfo.go
|
UpvertedAnnounceList
|
func (mi *MetaInfo) UpvertedAnnounceList() AnnounceList {
if mi.AnnounceList.OverridesAnnounce(mi.Announce) {
return mi.AnnounceList
}
if mi.Announce != "" {
return [][]string{[]string{mi.Announce}}
}
return nil
}
|
go
|
func (mi *MetaInfo) UpvertedAnnounceList() AnnounceList {
if mi.AnnounceList.OverridesAnnounce(mi.Announce) {
return mi.AnnounceList
}
if mi.Announce != "" {
return [][]string{[]string{mi.Announce}}
}
return nil
}
|
[
"func",
"(",
"mi",
"*",
"MetaInfo",
")",
"UpvertedAnnounceList",
"(",
")",
"AnnounceList",
"{",
"if",
"mi",
".",
"AnnounceList",
".",
"OverridesAnnounce",
"(",
"mi",
".",
"Announce",
")",
"{",
"return",
"mi",
".",
"AnnounceList",
"\n",
"}",
"\n",
"if",
"mi",
".",
"Announce",
"!=",
"\"\"",
"{",
"return",
"[",
"]",
"[",
"]",
"string",
"{",
"[",
"]",
"string",
"{",
"mi",
".",
"Announce",
"}",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Returns the announce list converted from the old single announce field if
// necessary.
|
[
"Returns",
"the",
"announce",
"list",
"converted",
"from",
"the",
"old",
"single",
"announce",
"field",
"if",
"necessary",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/metainfo.go#L79-L87
|
train
|
anacrolix/torrent
|
cmd/torrent-pick/main.go
|
totalBytesEstimate
|
func totalBytesEstimate(tc *torrent.Client) (ret int64) {
var noInfo, hadInfo int64
for _, t := range tc.Torrents() {
info := t.Info()
if info == nil {
noInfo++
continue
}
ret += info.TotalLength()
hadInfo++
}
if hadInfo != 0 {
// Treat each torrent without info as the average of those with,
// rounded up.
ret += (noInfo*ret + hadInfo - 1) / hadInfo
}
return
}
|
go
|
func totalBytesEstimate(tc *torrent.Client) (ret int64) {
var noInfo, hadInfo int64
for _, t := range tc.Torrents() {
info := t.Info()
if info == nil {
noInfo++
continue
}
ret += info.TotalLength()
hadInfo++
}
if hadInfo != 0 {
// Treat each torrent without info as the average of those with,
// rounded up.
ret += (noInfo*ret + hadInfo - 1) / hadInfo
}
return
}
|
[
"func",
"totalBytesEstimate",
"(",
"tc",
"*",
"torrent",
".",
"Client",
")",
"(",
"ret",
"int64",
")",
"{",
"var",
"noInfo",
",",
"hadInfo",
"int64",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"tc",
".",
"Torrents",
"(",
")",
"{",
"info",
":=",
"t",
".",
"Info",
"(",
")",
"\n",
"if",
"info",
"==",
"nil",
"{",
"noInfo",
"++",
"\n",
"continue",
"\n",
"}",
"\n",
"ret",
"+=",
"info",
".",
"TotalLength",
"(",
")",
"\n",
"hadInfo",
"++",
"\n",
"}",
"\n",
"if",
"hadInfo",
"!=",
"0",
"{",
"ret",
"+=",
"(",
"noInfo",
"*",
"ret",
"+",
"hadInfo",
"-",
"1",
")",
"/",
"hadInfo",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Returns an estimate of the total bytes for all torrents.
|
[
"Returns",
"an",
"estimate",
"of",
"the",
"total",
"bytes",
"for",
"all",
"torrents",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/cmd/torrent-pick/main.go#L51-L68
|
train
|
anacrolix/torrent
|
connection.go
|
ipv6
|
func (cn *connection) ipv6() bool {
ip := cn.remoteAddr.IP
if ip.To4() != nil {
return false
}
return len(ip) == net.IPv6len
}
|
go
|
func (cn *connection) ipv6() bool {
ip := cn.remoteAddr.IP
if ip.To4() != nil {
return false
}
return len(ip) == net.IPv6len
}
|
[
"func",
"(",
"cn",
"*",
"connection",
")",
"ipv6",
"(",
")",
"bool",
"{",
"ip",
":=",
"cn",
".",
"remoteAddr",
".",
"IP",
"\n",
"if",
"ip",
".",
"To4",
"(",
")",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"len",
"(",
"ip",
")",
"==",
"net",
".",
"IPv6len",
"\n",
"}"
] |
// Returns true if the connection is over IPv6.
|
[
"Returns",
"true",
"if",
"the",
"connection",
"is",
"over",
"IPv6",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L137-L143
|
train
|
anacrolix/torrent
|
connection.go
|
hasPreferredNetworkOver
|
func (l *connection) hasPreferredNetworkOver(r *connection) (left, ok bool) {
var ml multiLess
ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
ml.NextBool(!l.utp(), !r.utp())
ml.NextBool(l.ipv6(), r.ipv6())
return ml.FinalOk()
}
|
go
|
func (l *connection) hasPreferredNetworkOver(r *connection) (left, ok bool) {
var ml multiLess
ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
ml.NextBool(!l.utp(), !r.utp())
ml.NextBool(l.ipv6(), r.ipv6())
return ml.FinalOk()
}
|
[
"func",
"(",
"l",
"*",
"connection",
")",
"hasPreferredNetworkOver",
"(",
"r",
"*",
"connection",
")",
"(",
"left",
",",
"ok",
"bool",
")",
"{",
"var",
"ml",
"multiLess",
"\n",
"ml",
".",
"NextBool",
"(",
"l",
".",
"isPreferredDirection",
"(",
")",
",",
"r",
".",
"isPreferredDirection",
"(",
")",
")",
"\n",
"ml",
".",
"NextBool",
"(",
"!",
"l",
".",
"utp",
"(",
")",
",",
"!",
"r",
".",
"utp",
"(",
")",
")",
"\n",
"ml",
".",
"NextBool",
"(",
"l",
".",
"ipv6",
"(",
")",
",",
"r",
".",
"ipv6",
"(",
")",
")",
"\n",
"return",
"ml",
".",
"FinalOk",
"(",
")",
"\n",
"}"
] |
// Returns whether the left connection should be preferred over the right one,
// considering only their networking properties. If ok is false, we can't
// decide.
|
[
"Returns",
"whether",
"the",
"left",
"connection",
"should",
"be",
"preferred",
"over",
"the",
"right",
"one",
"considering",
"only",
"their",
"networking",
"properties",
".",
"If",
"ok",
"is",
"false",
"we",
"can",
"t",
"decide",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L154-L160
|
train
|
anacrolix/torrent
|
connection.go
|
bestPeerNumPieces
|
func (cn *connection) bestPeerNumPieces() pieceIndex {
if cn.t.haveInfo() {
return cn.t.numPieces()
}
return cn.peerMinPieces
}
|
go
|
func (cn *connection) bestPeerNumPieces() pieceIndex {
if cn.t.haveInfo() {
return cn.t.numPieces()
}
return cn.peerMinPieces
}
|
[
"func",
"(",
"cn",
"*",
"connection",
")",
"bestPeerNumPieces",
"(",
")",
"pieceIndex",
"{",
"if",
"cn",
".",
"t",
".",
"haveInfo",
"(",
")",
"{",
"return",
"cn",
".",
"t",
".",
"numPieces",
"(",
")",
"\n",
"}",
"\n",
"return",
"cn",
".",
"peerMinPieces",
"\n",
"}"
] |
// The best guess at number of pieces in the torrent for this peer.
|
[
"The",
"best",
"guess",
"at",
"number",
"of",
"pieces",
"in",
"the",
"torrent",
"for",
"this",
"peer",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L194-L199
|
train
|
anacrolix/torrent
|
connection.go
|
setNumPieces
|
func (cn *connection) setNumPieces(num pieceIndex) error {
cn.peerPieces.RemoveRange(bitmap.BitIndex(num), bitmap.ToEnd)
cn.peerPiecesChanged()
return nil
}
|
go
|
func (cn *connection) setNumPieces(num pieceIndex) error {
cn.peerPieces.RemoveRange(bitmap.BitIndex(num), bitmap.ToEnd)
cn.peerPiecesChanged()
return nil
}
|
[
"func",
"(",
"cn",
"*",
"connection",
")",
"setNumPieces",
"(",
"num",
"pieceIndex",
")",
"error",
"{",
"cn",
".",
"peerPieces",
".",
"RemoveRange",
"(",
"bitmap",
".",
"BitIndex",
"(",
"num",
")",
",",
"bitmap",
".",
"ToEnd",
")",
"\n",
"cn",
".",
"peerPiecesChanged",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Correct the PeerPieces slice length. Return false if the existing slice is
// invalid, such as by receiving badly sized BITFIELD, or invalid HAVE
// messages.
|
[
"Correct",
"the",
"PeerPieces",
"slice",
"length",
".",
"Return",
"false",
"if",
"the",
"existing",
"slice",
"is",
"invalid",
"such",
"as",
"by",
"receiving",
"badly",
"sized",
"BITFIELD",
"or",
"invalid",
"HAVE",
"messages",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L212-L216
|
train
|
anacrolix/torrent
|
connection.go
|
Post
|
func (cn *connection) Post(msg pp.Message) {
torrent.Add(fmt.Sprintf("messages posted of type %s", msg.Type.String()), 1)
// We don't need to track bytes here because a connection.w Writer wrapper
// takes care of that (although there's some delay between us recording
// the message, and the connection writer flushing it out.).
cn.writeBuffer.Write(msg.MustMarshalBinary())
// Last I checked only Piece messages affect stats, and we don't post
// those.
cn.wroteMsg(&msg)
cn.tickleWriter()
}
|
go
|
func (cn *connection) Post(msg pp.Message) {
torrent.Add(fmt.Sprintf("messages posted of type %s", msg.Type.String()), 1)
// We don't need to track bytes here because a connection.w Writer wrapper
// takes care of that (although there's some delay between us recording
// the message, and the connection writer flushing it out.).
cn.writeBuffer.Write(msg.MustMarshalBinary())
// Last I checked only Piece messages affect stats, and we don't post
// those.
cn.wroteMsg(&msg)
cn.tickleWriter()
}
|
[
"func",
"(",
"cn",
"*",
"connection",
")",
"Post",
"(",
"msg",
"pp",
".",
"Message",
")",
"{",
"torrent",
".",
"Add",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"messages posted of type %s\"",
",",
"msg",
".",
"Type",
".",
"String",
"(",
")",
")",
",",
"1",
")",
"\n",
"cn",
".",
"writeBuffer",
".",
"Write",
"(",
"msg",
".",
"MustMarshalBinary",
"(",
")",
")",
"\n",
"cn",
".",
"wroteMsg",
"(",
"&",
"msg",
")",
"\n",
"cn",
".",
"tickleWriter",
"(",
")",
"\n",
"}"
] |
// Writes a message into the write buffer.
|
[
"Writes",
"a",
"message",
"into",
"the",
"write",
"buffer",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L330-L340
|
train
|
anacrolix/torrent
|
connection.go
|
nominalMaxRequests
|
func (cn *connection) nominalMaxRequests() (ret int) {
if cn.t.requestStrategy == 3 {
expectingTime := int64(cn.totalExpectingTime())
if expectingTime == 0 {
expectingTime = math.MaxInt64
} else {
expectingTime *= 2
}
return int(clamp(
1,
int64(cn.PeerMaxRequests),
max(
// It makes sense to always pipeline at least one connection,
// since latency must be non-zero.
2,
// Request only as many as we expect to receive in the
// dupliateRequestTimeout window. We are trying to avoid having to
// duplicate requests.
cn.chunksReceivedWhileExpecting*int64(cn.t.duplicateRequestTimeout)/expectingTime,
),
))
}
return int(clamp(
1,
int64(cn.PeerMaxRequests),
max(64,
cn.stats.ChunksReadUseful.Int64()-(cn.stats.ChunksRead.Int64()-cn.stats.ChunksReadUseful.Int64()))))
}
|
go
|
func (cn *connection) nominalMaxRequests() (ret int) {
if cn.t.requestStrategy == 3 {
expectingTime := int64(cn.totalExpectingTime())
if expectingTime == 0 {
expectingTime = math.MaxInt64
} else {
expectingTime *= 2
}
return int(clamp(
1,
int64(cn.PeerMaxRequests),
max(
// It makes sense to always pipeline at least one connection,
// since latency must be non-zero.
2,
// Request only as many as we expect to receive in the
// dupliateRequestTimeout window. We are trying to avoid having to
// duplicate requests.
cn.chunksReceivedWhileExpecting*int64(cn.t.duplicateRequestTimeout)/expectingTime,
),
))
}
return int(clamp(
1,
int64(cn.PeerMaxRequests),
max(64,
cn.stats.ChunksReadUseful.Int64()-(cn.stats.ChunksRead.Int64()-cn.stats.ChunksReadUseful.Int64()))))
}
|
[
"func",
"(",
"cn",
"*",
"connection",
")",
"nominalMaxRequests",
"(",
")",
"(",
"ret",
"int",
")",
"{",
"if",
"cn",
".",
"t",
".",
"requestStrategy",
"==",
"3",
"{",
"expectingTime",
":=",
"int64",
"(",
"cn",
".",
"totalExpectingTime",
"(",
")",
")",
"\n",
"if",
"expectingTime",
"==",
"0",
"{",
"expectingTime",
"=",
"math",
".",
"MaxInt64",
"\n",
"}",
"else",
"{",
"expectingTime",
"*=",
"2",
"\n",
"}",
"\n",
"return",
"int",
"(",
"clamp",
"(",
"1",
",",
"int64",
"(",
"cn",
".",
"PeerMaxRequests",
")",
",",
"max",
"(",
"2",
",",
"cn",
".",
"chunksReceivedWhileExpecting",
"*",
"int64",
"(",
"cn",
".",
"t",
".",
"duplicateRequestTimeout",
")",
"/",
"expectingTime",
",",
")",
",",
")",
")",
"\n",
"}",
"\n",
"return",
"int",
"(",
"clamp",
"(",
"1",
",",
"int64",
"(",
"cn",
".",
"PeerMaxRequests",
")",
",",
"max",
"(",
"64",
",",
"cn",
".",
"stats",
".",
"ChunksReadUseful",
".",
"Int64",
"(",
")",
"-",
"(",
"cn",
".",
"stats",
".",
"ChunksRead",
".",
"Int64",
"(",
")",
"-",
"cn",
".",
"stats",
".",
"ChunksReadUseful",
".",
"Int64",
"(",
")",
")",
")",
")",
")",
"\n",
"}"
] |
// The actual value to use as the maximum outbound requests.
|
[
"The",
"actual",
"value",
"to",
"use",
"as",
"the",
"maximum",
"outbound",
"requests",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L375-L402
|
train
|
anacrolix/torrent
|
connection.go
|
request
|
func (cn *connection) request(r request, mw messageWriter) bool {
if _, ok := cn.requests[r]; ok {
panic("chunk already requested")
}
if !cn.PeerHasPiece(pieceIndex(r.Index)) {
panic("requesting piece peer doesn't have")
}
if _, ok := cn.t.conns[cn]; !ok {
panic("requesting but not in active conns")
}
if cn.closed.IsSet() {
panic("requesting when connection is closed")
}
if cn.PeerChoked {
if cn.peerAllowedFast.Get(int(r.Index)) {
torrent.Add("allowed fast requests sent", 1)
} else {
panic("requesting while choked and not allowed fast")
}
}
if cn.t.hashingPiece(pieceIndex(r.Index)) {
panic("piece is being hashed")
}
if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
panic("piece is queued for hash")
}
if cn.requests == nil {
cn.requests = make(map[request]struct{})
}
cn.requests[r] = struct{}{}
if cn.validReceiveChunks == nil {
cn.validReceiveChunks = make(map[request]struct{})
}
cn.validReceiveChunks[r] = struct{}{}
cn.t.pendingRequests[r]++
cn.t.lastRequested[r] = time.AfterFunc(cn.t.duplicateRequestTimeout, func() {
torrent.Add("duplicate request timeouts", 1)
cn.mu().Lock()
defer cn.mu().Unlock()
delete(cn.t.lastRequested, r)
for cn := range cn.t.conns {
if cn.PeerHasPiece(pieceIndex(r.Index)) {
cn.updateRequests()
}
}
})
cn.updateExpectingChunks()
return mw(pp.Message{
Type: pp.Request,
Index: r.Index,
Begin: r.Begin,
Length: r.Length,
})
}
|
go
|
func (cn *connection) request(r request, mw messageWriter) bool {
if _, ok := cn.requests[r]; ok {
panic("chunk already requested")
}
if !cn.PeerHasPiece(pieceIndex(r.Index)) {
panic("requesting piece peer doesn't have")
}
if _, ok := cn.t.conns[cn]; !ok {
panic("requesting but not in active conns")
}
if cn.closed.IsSet() {
panic("requesting when connection is closed")
}
if cn.PeerChoked {
if cn.peerAllowedFast.Get(int(r.Index)) {
torrent.Add("allowed fast requests sent", 1)
} else {
panic("requesting while choked and not allowed fast")
}
}
if cn.t.hashingPiece(pieceIndex(r.Index)) {
panic("piece is being hashed")
}
if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
panic("piece is queued for hash")
}
if cn.requests == nil {
cn.requests = make(map[request]struct{})
}
cn.requests[r] = struct{}{}
if cn.validReceiveChunks == nil {
cn.validReceiveChunks = make(map[request]struct{})
}
cn.validReceiveChunks[r] = struct{}{}
cn.t.pendingRequests[r]++
cn.t.lastRequested[r] = time.AfterFunc(cn.t.duplicateRequestTimeout, func() {
torrent.Add("duplicate request timeouts", 1)
cn.mu().Lock()
defer cn.mu().Unlock()
delete(cn.t.lastRequested, r)
for cn := range cn.t.conns {
if cn.PeerHasPiece(pieceIndex(r.Index)) {
cn.updateRequests()
}
}
})
cn.updateExpectingChunks()
return mw(pp.Message{
Type: pp.Request,
Index: r.Index,
Begin: r.Begin,
Length: r.Length,
})
}
|
[
"func",
"(",
"cn",
"*",
"connection",
")",
"request",
"(",
"r",
"request",
",",
"mw",
"messageWriter",
")",
"bool",
"{",
"if",
"_",
",",
"ok",
":=",
"cn",
".",
"requests",
"[",
"r",
"]",
";",
"ok",
"{",
"panic",
"(",
"\"chunk already requested\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"cn",
".",
"PeerHasPiece",
"(",
"pieceIndex",
"(",
"r",
".",
"Index",
")",
")",
"{",
"panic",
"(",
"\"requesting piece peer doesn't have\"",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"cn",
".",
"t",
".",
"conns",
"[",
"cn",
"]",
";",
"!",
"ok",
"{",
"panic",
"(",
"\"requesting but not in active conns\"",
")",
"\n",
"}",
"\n",
"if",
"cn",
".",
"closed",
".",
"IsSet",
"(",
")",
"{",
"panic",
"(",
"\"requesting when connection is closed\"",
")",
"\n",
"}",
"\n",
"if",
"cn",
".",
"PeerChoked",
"{",
"if",
"cn",
".",
"peerAllowedFast",
".",
"Get",
"(",
"int",
"(",
"r",
".",
"Index",
")",
")",
"{",
"torrent",
".",
"Add",
"(",
"\"allowed fast requests sent\"",
",",
"1",
")",
"\n",
"}",
"else",
"{",
"panic",
"(",
"\"requesting while choked and not allowed fast\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"cn",
".",
"t",
".",
"hashingPiece",
"(",
"pieceIndex",
"(",
"r",
".",
"Index",
")",
")",
"{",
"panic",
"(",
"\"piece is being hashed\"",
")",
"\n",
"}",
"\n",
"if",
"cn",
".",
"t",
".",
"pieceQueuedForHash",
"(",
"pieceIndex",
"(",
"r",
".",
"Index",
")",
")",
"{",
"panic",
"(",
"\"piece is queued for hash\"",
")",
"\n",
"}",
"\n",
"if",
"cn",
".",
"requests",
"==",
"nil",
"{",
"cn",
".",
"requests",
"=",
"make",
"(",
"map",
"[",
"request",
"]",
"struct",
"{",
"}",
")",
"\n",
"}",
"\n",
"cn",
".",
"requests",
"[",
"r",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"if",
"cn",
".",
"validReceiveChunks",
"==",
"nil",
"{",
"cn",
".",
"validReceiveChunks",
"=",
"make",
"(",
"map",
"[",
"request",
"]",
"struct",
"{",
"}",
")",
"\n",
"}",
"\n",
"cn",
".",
"validReceiveChunks",
"[",
"r",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"cn",
".",
"t",
".",
"pendingRequests",
"[",
"r",
"]",
"++",
"\n",
"cn",
".",
"t",
".",
"lastRequested",
"[",
"r",
"]",
"=",
"time",
".",
"AfterFunc",
"(",
"cn",
".",
"t",
".",
"duplicateRequestTimeout",
",",
"func",
"(",
")",
"{",
"torrent",
".",
"Add",
"(",
"\"duplicate request timeouts\"",
",",
"1",
")",
"\n",
"cn",
".",
"mu",
"(",
")",
".",
"Lock",
"(",
")",
"\n",
"defer",
"cn",
".",
"mu",
"(",
")",
".",
"Unlock",
"(",
")",
"\n",
"delete",
"(",
"cn",
".",
"t",
".",
"lastRequested",
",",
"r",
")",
"\n",
"for",
"cn",
":=",
"range",
"cn",
".",
"t",
".",
"conns",
"{",
"if",
"cn",
".",
"PeerHasPiece",
"(",
"pieceIndex",
"(",
"r",
".",
"Index",
")",
")",
"{",
"cn",
".",
"updateRequests",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
")",
"\n",
"cn",
".",
"updateExpectingChunks",
"(",
")",
"\n",
"return",
"mw",
"(",
"pp",
".",
"Message",
"{",
"Type",
":",
"pp",
".",
"Request",
",",
"Index",
":",
"r",
".",
"Index",
",",
"Begin",
":",
"r",
".",
"Begin",
",",
"Length",
":",
"r",
".",
"Length",
",",
"}",
")",
"\n",
"}"
] |
// Proxies the messageWriter's response.
|
[
"Proxies",
"the",
"messageWriter",
"s",
"response",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L482-L535
|
train
|
anacrolix/torrent
|
connection.go
|
writer
|
func (cn *connection) writer(keepAliveTimeout time.Duration) {
var (
lastWrite time.Time = time.Now()
keepAliveTimer *time.Timer
)
keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
cn.mu().Lock()
defer cn.mu().Unlock()
if time.Since(lastWrite) >= keepAliveTimeout {
cn.tickleWriter()
}
keepAliveTimer.Reset(keepAliveTimeout)
})
cn.mu().Lock()
defer cn.mu().Unlock()
defer cn.Close()
defer keepAliveTimer.Stop()
frontBuf := new(bytes.Buffer)
for {
if cn.closed.IsSet() {
return
}
if cn.writeBuffer.Len() == 0 {
cn.fillWriteBuffer(func(msg pp.Message) bool {
cn.wroteMsg(&msg)
cn.writeBuffer.Write(msg.MustMarshalBinary())
torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1)
return cn.writeBuffer.Len() < 1<<16 // 64KiB
})
}
if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout {
cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
postedKeepalives.Add(1)
}
if cn.writeBuffer.Len() == 0 {
// TODO: Minimize wakeups....
cn.writerCond.Wait()
continue
}
// Flip the buffers.
frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
cn.mu().Unlock()
n, err := cn.w.Write(frontBuf.Bytes())
cn.mu().Lock()
if n != 0 {
lastWrite = time.Now()
keepAliveTimer.Reset(keepAliveTimeout)
}
if err != nil {
return
}
if n != frontBuf.Len() {
panic("short write")
}
frontBuf.Reset()
}
}
|
go
|
func (cn *connection) writer(keepAliveTimeout time.Duration) {
var (
lastWrite time.Time = time.Now()
keepAliveTimer *time.Timer
)
keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
cn.mu().Lock()
defer cn.mu().Unlock()
if time.Since(lastWrite) >= keepAliveTimeout {
cn.tickleWriter()
}
keepAliveTimer.Reset(keepAliveTimeout)
})
cn.mu().Lock()
defer cn.mu().Unlock()
defer cn.Close()
defer keepAliveTimer.Stop()
frontBuf := new(bytes.Buffer)
for {
if cn.closed.IsSet() {
return
}
if cn.writeBuffer.Len() == 0 {
cn.fillWriteBuffer(func(msg pp.Message) bool {
cn.wroteMsg(&msg)
cn.writeBuffer.Write(msg.MustMarshalBinary())
torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1)
return cn.writeBuffer.Len() < 1<<16 // 64KiB
})
}
if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout {
cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
postedKeepalives.Add(1)
}
if cn.writeBuffer.Len() == 0 {
// TODO: Minimize wakeups....
cn.writerCond.Wait()
continue
}
// Flip the buffers.
frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
cn.mu().Unlock()
n, err := cn.w.Write(frontBuf.Bytes())
cn.mu().Lock()
if n != 0 {
lastWrite = time.Now()
keepAliveTimer.Reset(keepAliveTimeout)
}
if err != nil {
return
}
if n != frontBuf.Len() {
panic("short write")
}
frontBuf.Reset()
}
}
|
[
"func",
"(",
"cn",
"*",
"connection",
")",
"writer",
"(",
"keepAliveTimeout",
"time",
".",
"Duration",
")",
"{",
"var",
"(",
"lastWrite",
"time",
".",
"Time",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"keepAliveTimer",
"*",
"time",
".",
"Timer",
"\n",
")",
"\n",
"keepAliveTimer",
"=",
"time",
".",
"AfterFunc",
"(",
"keepAliveTimeout",
",",
"func",
"(",
")",
"{",
"cn",
".",
"mu",
"(",
")",
".",
"Lock",
"(",
")",
"\n",
"defer",
"cn",
".",
"mu",
"(",
")",
".",
"Unlock",
"(",
")",
"\n",
"if",
"time",
".",
"Since",
"(",
"lastWrite",
")",
">=",
"keepAliveTimeout",
"{",
"cn",
".",
"tickleWriter",
"(",
")",
"\n",
"}",
"\n",
"keepAliveTimer",
".",
"Reset",
"(",
"keepAliveTimeout",
")",
"\n",
"}",
")",
"\n",
"cn",
".",
"mu",
"(",
")",
".",
"Lock",
"(",
")",
"\n",
"defer",
"cn",
".",
"mu",
"(",
")",
".",
"Unlock",
"(",
")",
"\n",
"defer",
"cn",
".",
"Close",
"(",
")",
"\n",
"defer",
"keepAliveTimer",
".",
"Stop",
"(",
")",
"\n",
"frontBuf",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"for",
"{",
"if",
"cn",
".",
"closed",
".",
"IsSet",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"cn",
".",
"writeBuffer",
".",
"Len",
"(",
")",
"==",
"0",
"{",
"cn",
".",
"fillWriteBuffer",
"(",
"func",
"(",
"msg",
"pp",
".",
"Message",
")",
"bool",
"{",
"cn",
".",
"wroteMsg",
"(",
"&",
"msg",
")",
"\n",
"cn",
".",
"writeBuffer",
".",
"Write",
"(",
"msg",
".",
"MustMarshalBinary",
"(",
")",
")",
"\n",
"torrent",
".",
"Add",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"messages filled of type %s\"",
",",
"msg",
".",
"Type",
".",
"String",
"(",
")",
")",
",",
"1",
")",
"\n",
"return",
"cn",
".",
"writeBuffer",
".",
"Len",
"(",
")",
"<",
"1",
"<<",
"16",
"\n",
"}",
")",
"\n",
"}",
"\n",
"if",
"cn",
".",
"writeBuffer",
".",
"Len",
"(",
")",
"==",
"0",
"&&",
"time",
".",
"Since",
"(",
"lastWrite",
")",
">=",
"keepAliveTimeout",
"{",
"cn",
".",
"writeBuffer",
".",
"Write",
"(",
"pp",
".",
"Message",
"{",
"Keepalive",
":",
"true",
"}",
".",
"MustMarshalBinary",
"(",
")",
")",
"\n",
"postedKeepalives",
".",
"Add",
"(",
"1",
")",
"\n",
"}",
"\n",
"if",
"cn",
".",
"writeBuffer",
".",
"Len",
"(",
")",
"==",
"0",
"{",
"cn",
".",
"writerCond",
".",
"Wait",
"(",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"frontBuf",
",",
"cn",
".",
"writeBuffer",
"=",
"cn",
".",
"writeBuffer",
",",
"frontBuf",
"\n",
"cn",
".",
"mu",
"(",
")",
".",
"Unlock",
"(",
")",
"\n",
"n",
",",
"err",
":=",
"cn",
".",
"w",
".",
"Write",
"(",
"frontBuf",
".",
"Bytes",
"(",
")",
")",
"\n",
"cn",
".",
"mu",
"(",
")",
".",
"Lock",
"(",
")",
"\n",
"if",
"n",
"!=",
"0",
"{",
"lastWrite",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"keepAliveTimer",
".",
"Reset",
"(",
"keepAliveTimeout",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"n",
"!=",
"frontBuf",
".",
"Len",
"(",
")",
"{",
"panic",
"(",
"\"short write\"",
")",
"\n",
"}",
"\n",
"frontBuf",
".",
"Reset",
"(",
")",
"\n",
"}",
"\n",
"}"
] |
// Routine that writes to the peer. Some of what to write is buffered by
// activity elsewhere in the Client, and some is determined locally when the
// connection is writable.
|
[
"Routine",
"that",
"writes",
"to",
"the",
"peer",
".",
"Some",
"of",
"what",
"to",
"write",
"is",
"buffered",
"by",
"activity",
"elsewhere",
"in",
"the",
"Client",
"and",
"some",
"is",
"determined",
"locally",
"when",
"the",
"connection",
"is",
"writable",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L593-L649
|
train
|
anacrolix/torrent
|
connection.go
|
iterBitmapsDistinct
|
func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
return func(cb iter.Callback) {
for _, bm := range bms {
if !iter.All(func(i interface{}) bool {
skip.Add(i.(int))
return cb(i)
}, bitmap.Sub(bm, *skip).Iter) {
return
}
}
}
}
|
go
|
func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
return func(cb iter.Callback) {
for _, bm := range bms {
if !iter.All(func(i interface{}) bool {
skip.Add(i.(int))
return cb(i)
}, bitmap.Sub(bm, *skip).Iter) {
return
}
}
}
}
|
[
"func",
"iterBitmapsDistinct",
"(",
"skip",
"*",
"bitmap",
".",
"Bitmap",
",",
"bms",
"...",
"bitmap",
".",
"Bitmap",
")",
"iter",
".",
"Func",
"{",
"return",
"func",
"(",
"cb",
"iter",
".",
"Callback",
")",
"{",
"for",
"_",
",",
"bm",
":=",
"range",
"bms",
"{",
"if",
"!",
"iter",
".",
"All",
"(",
"func",
"(",
"i",
"interface",
"{",
"}",
")",
"bool",
"{",
"skip",
".",
"Add",
"(",
"i",
".",
"(",
"int",
")",
")",
"\n",
"return",
"cb",
"(",
"i",
")",
"\n",
"}",
",",
"bitmap",
".",
"Sub",
"(",
"bm",
",",
"*",
"skip",
")",
".",
"Iter",
")",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// Emits the indices in the Bitmaps bms in order, never repeating any index.
// skip is mutated during execution, and its initial values will never be
// emitted.
|
[
"Emits",
"the",
"indices",
"in",
"the",
"Bitmaps",
"bms",
"in",
"order",
"never",
"repeating",
"any",
"index",
".",
"skip",
"is",
"mutated",
"during",
"execution",
"and",
"its",
"initial",
"values",
"will",
"never",
"be",
"emitted",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L684-L695
|
train
|
anacrolix/torrent
|
connection.go
|
shouldRequestWithoutBias
|
func (cn *connection) shouldRequestWithoutBias() bool {
if cn.t.requestStrategy != 2 {
return false
}
if len(cn.t.readers) == 0 {
return false
}
if len(cn.t.conns) == 1 {
return true
}
if cn == cn.t.fastestConn {
return true
}
return false
}
|
go
|
func (cn *connection) shouldRequestWithoutBias() bool {
if cn.t.requestStrategy != 2 {
return false
}
if len(cn.t.readers) == 0 {
return false
}
if len(cn.t.conns) == 1 {
return true
}
if cn == cn.t.fastestConn {
return true
}
return false
}
|
[
"func",
"(",
"cn",
"*",
"connection",
")",
"shouldRequestWithoutBias",
"(",
")",
"bool",
"{",
"if",
"cn",
".",
"t",
".",
"requestStrategy",
"!=",
"2",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"len",
"(",
"cn",
".",
"t",
".",
"readers",
")",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"len",
"(",
"cn",
".",
"t",
".",
"conns",
")",
"==",
"1",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"cn",
"==",
"cn",
".",
"t",
".",
"fastestConn",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// The connection should download highest priority pieces first, without any
// inclination toward avoiding wastage. Generally we might do this if there's
// a single connection, or this is the fastest connection, and we have active
// readers that signal an ordering preference. It's conceivable that the best
// connection should do this, since it's least likely to waste our time if
// assigned to the highest priority pieces, and assigning more than one this
// role would cause significant wasted bandwidth.
|
[
"The",
"connection",
"should",
"download",
"highest",
"priority",
"pieces",
"first",
"without",
"any",
"inclination",
"toward",
"avoiding",
"wastage",
".",
"Generally",
"we",
"might",
"do",
"this",
"if",
"there",
"s",
"a",
"single",
"connection",
"or",
"this",
"is",
"the",
"fastest",
"connection",
"and",
"we",
"have",
"active",
"readers",
"that",
"signal",
"an",
"ordering",
"preference",
".",
"It",
"s",
"conceivable",
"that",
"the",
"best",
"connection",
"should",
"do",
"this",
"since",
"it",
"s",
"least",
"likely",
"to",
"waste",
"our",
"time",
"if",
"assigned",
"to",
"the",
"highest",
"priority",
"pieces",
"and",
"assigning",
"more",
"than",
"one",
"this",
"role",
"would",
"cause",
"significant",
"wasted",
"bandwidth",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L738-L752
|
train
|
anacrolix/torrent
|
connection.go
|
stopRequestingPiece
|
func (cn *connection) stopRequestingPiece(piece pieceIndex) bool {
return cn.pieceRequestOrder.Remove(bitmap.BitIndex(piece))
}
|
go
|
func (cn *connection) stopRequestingPiece(piece pieceIndex) bool {
return cn.pieceRequestOrder.Remove(bitmap.BitIndex(piece))
}
|
[
"func",
"(",
"cn",
"*",
"connection",
")",
"stopRequestingPiece",
"(",
"piece",
"pieceIndex",
")",
"bool",
"{",
"return",
"cn",
".",
"pieceRequestOrder",
".",
"Remove",
"(",
"bitmap",
".",
"BitIndex",
"(",
"piece",
")",
")",
"\n",
"}"
] |
// check callers updaterequests
|
[
"check",
"callers",
"updaterequests"
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L811-L813
|
train
|
anacrolix/torrent
|
connection.go
|
updatePiecePriority
|
func (cn *connection) updatePiecePriority(piece pieceIndex) bool {
tpp := cn.t.piecePriority(piece)
if !cn.PeerHasPiece(piece) {
tpp = PiecePriorityNone
}
if tpp == PiecePriorityNone {
return cn.stopRequestingPiece(piece)
}
prio := cn.getPieceInclination()[piece]
switch cn.t.requestStrategy {
case 1:
switch tpp {
case PiecePriorityNormal:
case PiecePriorityReadahead:
prio -= int(cn.t.numPieces())
case PiecePriorityNext, PiecePriorityNow:
prio -= 2 * int(cn.t.numPieces())
default:
panic(tpp)
}
prio += int(piece / 3)
default:
}
return cn.pieceRequestOrder.Set(bitmap.BitIndex(piece), prio) || cn.shouldRequestWithoutBias()
}
|
go
|
func (cn *connection) updatePiecePriority(piece pieceIndex) bool {
tpp := cn.t.piecePriority(piece)
if !cn.PeerHasPiece(piece) {
tpp = PiecePriorityNone
}
if tpp == PiecePriorityNone {
return cn.stopRequestingPiece(piece)
}
prio := cn.getPieceInclination()[piece]
switch cn.t.requestStrategy {
case 1:
switch tpp {
case PiecePriorityNormal:
case PiecePriorityReadahead:
prio -= int(cn.t.numPieces())
case PiecePriorityNext, PiecePriorityNow:
prio -= 2 * int(cn.t.numPieces())
default:
panic(tpp)
}
prio += int(piece / 3)
default:
}
return cn.pieceRequestOrder.Set(bitmap.BitIndex(piece), prio) || cn.shouldRequestWithoutBias()
}
|
[
"func",
"(",
"cn",
"*",
"connection",
")",
"updatePiecePriority",
"(",
"piece",
"pieceIndex",
")",
"bool",
"{",
"tpp",
":=",
"cn",
".",
"t",
".",
"piecePriority",
"(",
"piece",
")",
"\n",
"if",
"!",
"cn",
".",
"PeerHasPiece",
"(",
"piece",
")",
"{",
"tpp",
"=",
"PiecePriorityNone",
"\n",
"}",
"\n",
"if",
"tpp",
"==",
"PiecePriorityNone",
"{",
"return",
"cn",
".",
"stopRequestingPiece",
"(",
"piece",
")",
"\n",
"}",
"\n",
"prio",
":=",
"cn",
".",
"getPieceInclination",
"(",
")",
"[",
"piece",
"]",
"\n",
"switch",
"cn",
".",
"t",
".",
"requestStrategy",
"{",
"case",
"1",
":",
"switch",
"tpp",
"{",
"case",
"PiecePriorityNormal",
":",
"case",
"PiecePriorityReadahead",
":",
"prio",
"-=",
"int",
"(",
"cn",
".",
"t",
".",
"numPieces",
"(",
")",
")",
"\n",
"case",
"PiecePriorityNext",
",",
"PiecePriorityNow",
":",
"prio",
"-=",
"2",
"*",
"int",
"(",
"cn",
".",
"t",
".",
"numPieces",
"(",
")",
")",
"\n",
"default",
":",
"panic",
"(",
"tpp",
")",
"\n",
"}",
"\n",
"prio",
"+=",
"int",
"(",
"piece",
"/",
"3",
")",
"\n",
"default",
":",
"}",
"\n",
"return",
"cn",
".",
"pieceRequestOrder",
".",
"Set",
"(",
"bitmap",
".",
"BitIndex",
"(",
"piece",
")",
",",
"prio",
")",
"||",
"cn",
".",
"shouldRequestWithoutBias",
"(",
")",
"\n",
"}"
] |
// This is distinct from Torrent piece priority, which is the user's
// preference. Connection piece priority is specific to a connection and is
// used to pseudorandomly avoid connections always requesting the same pieces
// and thus wasting effort.
|
[
"This",
"is",
"distinct",
"from",
"Torrent",
"piece",
"priority",
"which",
"is",
"the",
"user",
"s",
"preference",
".",
"Connection",
"piece",
"priority",
"is",
"specific",
"to",
"a",
"connection",
"and",
"is",
"used",
"to",
"pseudorandomly",
"avoid",
"connections",
"always",
"requesting",
"the",
"same",
"pieces",
"and",
"thus",
"wasting",
"effort",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L819-L843
|
train
|
anacrolix/torrent
|
connection.go
|
postHandshakeStats
|
func (cn *connection) postHandshakeStats(f func(*ConnStats)) {
t := cn.t
f(&t.stats)
f(&t.cl.stats)
}
|
go
|
func (cn *connection) postHandshakeStats(f func(*ConnStats)) {
t := cn.t
f(&t.stats)
f(&t.cl.stats)
}
|
[
"func",
"(",
"cn",
"*",
"connection",
")",
"postHandshakeStats",
"(",
"f",
"func",
"(",
"*",
"ConnStats",
")",
")",
"{",
"t",
":=",
"cn",
".",
"t",
"\n",
"f",
"(",
"&",
"t",
".",
"stats",
")",
"\n",
"f",
"(",
"&",
"t",
".",
"cl",
".",
"stats",
")",
"\n",
"}"
] |
// After handshake, we know what Torrent and Client stats to include for a
// connection.
|
[
"After",
"handshake",
"we",
"know",
"what",
"Torrent",
"and",
"Client",
"stats",
"to",
"include",
"for",
"a",
"connection",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L962-L966
|
train
|
anacrolix/torrent
|
connection.go
|
allStats
|
func (cn *connection) allStats(f func(*ConnStats)) {
f(&cn.stats)
if cn.reconciledHandshakeStats {
cn.postHandshakeStats(f)
}
}
|
go
|
func (cn *connection) allStats(f func(*ConnStats)) {
f(&cn.stats)
if cn.reconciledHandshakeStats {
cn.postHandshakeStats(f)
}
}
|
[
"func",
"(",
"cn",
"*",
"connection",
")",
"allStats",
"(",
"f",
"func",
"(",
"*",
"ConnStats",
")",
")",
"{",
"f",
"(",
"&",
"cn",
".",
"stats",
")",
"\n",
"if",
"cn",
".",
"reconciledHandshakeStats",
"{",
"cn",
".",
"postHandshakeStats",
"(",
"f",
")",
"\n",
"}",
"\n",
"}"
] |
// All ConnStats that include this connection. Some objects are not known
// until the handshake is complete, after which it's expected to reconcile the
// differences.
|
[
"All",
"ConnStats",
"that",
"include",
"this",
"connection",
".",
"Some",
"objects",
"are",
"not",
"known",
"until",
"the",
"handshake",
"is",
"complete",
"after",
"which",
"it",
"s",
"expected",
"to",
"reconcile",
"the",
"differences",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L971-L976
|
train
|
anacrolix/torrent
|
connection.go
|
useful
|
func (c *connection) useful() bool {
t := c.t
if c.closed.IsSet() {
return false
}
if !t.haveInfo() {
return c.supportsExtension("ut_metadata")
}
if t.seeding() && c.PeerInterested {
return true
}
if c.peerHasWantedPieces() {
return true
}
return false
}
|
go
|
func (c *connection) useful() bool {
t := c.t
if c.closed.IsSet() {
return false
}
if !t.haveInfo() {
return c.supportsExtension("ut_metadata")
}
if t.seeding() && c.PeerInterested {
return true
}
if c.peerHasWantedPieces() {
return true
}
return false
}
|
[
"func",
"(",
"c",
"*",
"connection",
")",
"useful",
"(",
")",
"bool",
"{",
"t",
":=",
"c",
".",
"t",
"\n",
"if",
"c",
".",
"closed",
".",
"IsSet",
"(",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"!",
"t",
".",
"haveInfo",
"(",
")",
"{",
"return",
"c",
".",
"supportsExtension",
"(",
"\"ut_metadata\"",
")",
"\n",
"}",
"\n",
"if",
"t",
".",
"seeding",
"(",
")",
"&&",
"c",
".",
"PeerInterested",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"c",
".",
"peerHasWantedPieces",
"(",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// Returns whether the connection could be useful to us. We're seeding and
// they want data, we don't have metainfo and they can provide it, etc.
|
[
"Returns",
"whether",
"the",
"connection",
"could",
"be",
"useful",
"to",
"us",
".",
"We",
"re",
"seeding",
"and",
"they",
"want",
"data",
"we",
"don",
"t",
"have",
"metainfo",
"and",
"they",
"can",
"provide",
"it",
"etc",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L988-L1003
|
train
|
anacrolix/torrent
|
connection.go
|
setRW
|
func (cn *connection) setRW(rw io.ReadWriter) {
cn.r = rw
cn.w = rw
}
|
go
|
func (cn *connection) setRW(rw io.ReadWriter) {
cn.r = rw
cn.w = rw
}
|
[
"func",
"(",
"cn",
"*",
"connection",
")",
"setRW",
"(",
"rw",
"io",
".",
"ReadWriter",
")",
"{",
"cn",
".",
"r",
"=",
"rw",
"\n",
"cn",
".",
"w",
"=",
"rw",
"\n",
"}"
] |
// Set both the Reader and Writer for the connection from a single ReadWriter.
|
[
"Set",
"both",
"the",
"Reader",
"and",
"Writer",
"for",
"the",
"connection",
"from",
"a",
"single",
"ReadWriter",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L1253-L1256
|
train
|
anacrolix/torrent
|
connection.go
|
rw
|
func (cn *connection) rw() io.ReadWriter {
return struct {
io.Reader
io.Writer
}{cn.r, cn.w}
}
|
go
|
func (cn *connection) rw() io.ReadWriter {
return struct {
io.Reader
io.Writer
}{cn.r, cn.w}
}
|
[
"func",
"(",
"cn",
"*",
"connection",
")",
"rw",
"(",
")",
"io",
".",
"ReadWriter",
"{",
"return",
"struct",
"{",
"io",
".",
"Reader",
"\n",
"io",
".",
"Writer",
"\n",
"}",
"{",
"cn",
".",
"r",
",",
"cn",
".",
"w",
"}",
"\n",
"}"
] |
// Returns the Reader and Writer as a combined ReadWriter.
|
[
"Returns",
"the",
"Reader",
"and",
"Writer",
"as",
"a",
"combined",
"ReadWriter",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L1259-L1264
|
train
|
anacrolix/torrent
|
connection.go
|
upload
|
func (c *connection) upload(msg func(pp.Message) bool) bool {
// Breaking or completing this loop means we don't want to upload to the
// peer anymore, and we choke them.
another:
for c.uploadAllowed() {
// We want to upload to the peer.
if !c.Unchoke(msg) {
return false
}
for r := range c.PeerRequests {
res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
if !res.OK() {
panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
}
delay := res.Delay()
if delay > 0 {
res.Cancel()
c.setRetryUploadTimer(delay)
// Hard to say what to return here.
return true
}
more, err := c.sendChunk(r, msg)
if err != nil {
i := pieceIndex(r.Index)
if c.t.pieceComplete(i) {
c.t.updatePieceCompletion(i)
if !c.t.pieceComplete(i) {
// We had the piece, but not anymore.
break another
}
}
log.Str("error sending chunk to peer").AddValues(c, r, err).Log(c.t.logger)
// If we failed to send a chunk, choke the peer to ensure they
// flush all their requests. We've probably dropped a piece,
// but there's no way to communicate this to the peer. If they
// ask for it again, we'll kick them to allow us to send them
// an updated bitfield.
break another
}
delete(c.PeerRequests, r)
if !more {
return false
}
goto another
}
return true
}
return c.Choke(msg)
}
|
go
|
func (c *connection) upload(msg func(pp.Message) bool) bool {
// Breaking or completing this loop means we don't want to upload to the
// peer anymore, and we choke them.
another:
for c.uploadAllowed() {
// We want to upload to the peer.
if !c.Unchoke(msg) {
return false
}
for r := range c.PeerRequests {
res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
if !res.OK() {
panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
}
delay := res.Delay()
if delay > 0 {
res.Cancel()
c.setRetryUploadTimer(delay)
// Hard to say what to return here.
return true
}
more, err := c.sendChunk(r, msg)
if err != nil {
i := pieceIndex(r.Index)
if c.t.pieceComplete(i) {
c.t.updatePieceCompletion(i)
if !c.t.pieceComplete(i) {
// We had the piece, but not anymore.
break another
}
}
log.Str("error sending chunk to peer").AddValues(c, r, err).Log(c.t.logger)
// If we failed to send a chunk, choke the peer to ensure they
// flush all their requests. We've probably dropped a piece,
// but there's no way to communicate this to the peer. If they
// ask for it again, we'll kick them to allow us to send them
// an updated bitfield.
break another
}
delete(c.PeerRequests, r)
if !more {
return false
}
goto another
}
return true
}
return c.Choke(msg)
}
|
[
"func",
"(",
"c",
"*",
"connection",
")",
"upload",
"(",
"msg",
"func",
"(",
"pp",
".",
"Message",
")",
"bool",
")",
"bool",
"{",
"another",
":",
"for",
"c",
".",
"uploadAllowed",
"(",
")",
"{",
"if",
"!",
"c",
".",
"Unchoke",
"(",
"msg",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"r",
":=",
"range",
"c",
".",
"PeerRequests",
"{",
"res",
":=",
"c",
".",
"t",
".",
"cl",
".",
"config",
".",
"UploadRateLimiter",
".",
"ReserveN",
"(",
"time",
".",
"Now",
"(",
")",
",",
"int",
"(",
"r",
".",
"Length",
")",
")",
"\n",
"if",
"!",
"res",
".",
"OK",
"(",
")",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"upload rate limiter burst size < %d\"",
",",
"r",
".",
"Length",
")",
")",
"\n",
"}",
"\n",
"delay",
":=",
"res",
".",
"Delay",
"(",
")",
"\n",
"if",
"delay",
">",
"0",
"{",
"res",
".",
"Cancel",
"(",
")",
"\n",
"c",
".",
"setRetryUploadTimer",
"(",
"delay",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"more",
",",
"err",
":=",
"c",
".",
"sendChunk",
"(",
"r",
",",
"msg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"i",
":=",
"pieceIndex",
"(",
"r",
".",
"Index",
")",
"\n",
"if",
"c",
".",
"t",
".",
"pieceComplete",
"(",
"i",
")",
"{",
"c",
".",
"t",
".",
"updatePieceCompletion",
"(",
"i",
")",
"\n",
"if",
"!",
"c",
".",
"t",
".",
"pieceComplete",
"(",
"i",
")",
"{",
"break",
"another",
"\n",
"}",
"\n",
"}",
"\n",
"log",
".",
"Str",
"(",
"\"error sending chunk to peer\"",
")",
".",
"AddValues",
"(",
"c",
",",
"r",
",",
"err",
")",
".",
"Log",
"(",
"c",
".",
"t",
".",
"logger",
")",
"\n",
"break",
"another",
"\n",
"}",
"\n",
"delete",
"(",
"c",
".",
"PeerRequests",
",",
"r",
")",
"\n",
"if",
"!",
"more",
"{",
"return",
"false",
"\n",
"}",
"\n",
"goto",
"another",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"return",
"c",
".",
"Choke",
"(",
"msg",
")",
"\n",
"}"
] |
// Also handles choking and unchoking of the remote peer.
|
[
"Also",
"handles",
"choking",
"and",
"unchoking",
"of",
"the",
"remote",
"peer",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L1400-L1448
|
train
|
anacrolix/torrent
|
iplist/iplist.go
|
Lookup
|
func (ipl *IPList) Lookup(ip net.IP) (r Range, ok bool) {
if ipl == nil {
return
}
// TODO: Perhaps all addresses should be converted to IPv6, if the future
// of IP is to always be backwards compatible. But this will cost 4x the
// memory for IPv4 addresses?
v4 := ip.To4()
if v4 != nil {
r, ok = ipl.lookup(v4)
if ok {
return
}
}
v6 := ip.To16()
if v6 != nil {
return ipl.lookup(v6)
}
if v4 == nil && v6 == nil {
r = Range{
Description: "bad IP",
}
ok = true
}
return
}
|
go
|
func (ipl *IPList) Lookup(ip net.IP) (r Range, ok bool) {
if ipl == nil {
return
}
// TODO: Perhaps all addresses should be converted to IPv6, if the future
// of IP is to always be backwards compatible. But this will cost 4x the
// memory for IPv4 addresses?
v4 := ip.To4()
if v4 != nil {
r, ok = ipl.lookup(v4)
if ok {
return
}
}
v6 := ip.To16()
if v6 != nil {
return ipl.lookup(v6)
}
if v4 == nil && v6 == nil {
r = Range{
Description: "bad IP",
}
ok = true
}
return
}
|
[
"func",
"(",
"ipl",
"*",
"IPList",
")",
"Lookup",
"(",
"ip",
"net",
".",
"IP",
")",
"(",
"r",
"Range",
",",
"ok",
"bool",
")",
"{",
"if",
"ipl",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"v4",
":=",
"ip",
".",
"To4",
"(",
")",
"\n",
"if",
"v4",
"!=",
"nil",
"{",
"r",
",",
"ok",
"=",
"ipl",
".",
"lookup",
"(",
"v4",
")",
"\n",
"if",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"v6",
":=",
"ip",
".",
"To16",
"(",
")",
"\n",
"if",
"v6",
"!=",
"nil",
"{",
"return",
"ipl",
".",
"lookup",
"(",
"v6",
")",
"\n",
"}",
"\n",
"if",
"v4",
"==",
"nil",
"&&",
"v6",
"==",
"nil",
"{",
"r",
"=",
"Range",
"{",
"Description",
":",
"\"bad IP\"",
",",
"}",
"\n",
"ok",
"=",
"true",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Return the range the given IP is in. ok if false if no range is found.
|
[
"Return",
"the",
"range",
"the",
"given",
"IP",
"is",
"in",
".",
"ok",
"if",
"false",
"if",
"no",
"range",
"is",
"found",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/iplist/iplist.go#L53-L78
|
train
|
anacrolix/torrent
|
iplist/iplist.go
|
lookup
|
func lookup(
first func(i int) net.IP,
full func(i int) Range,
n int,
ip net.IP,
) (
r Range, ok bool,
) {
// Find the index of the first range for which the following range exceeds
// it.
i := sort.Search(n, func(i int) bool {
if i+1 >= n {
return true
}
return bytes.Compare(ip, first(i+1)) < 0
})
if i == n {
return
}
r = full(i)
ok = bytes.Compare(r.First, ip) <= 0 && bytes.Compare(ip, r.Last) <= 0
return
}
|
go
|
func lookup(
first func(i int) net.IP,
full func(i int) Range,
n int,
ip net.IP,
) (
r Range, ok bool,
) {
// Find the index of the first range for which the following range exceeds
// it.
i := sort.Search(n, func(i int) bool {
if i+1 >= n {
return true
}
return bytes.Compare(ip, first(i+1)) < 0
})
if i == n {
return
}
r = full(i)
ok = bytes.Compare(r.First, ip) <= 0 && bytes.Compare(ip, r.Last) <= 0
return
}
|
[
"func",
"lookup",
"(",
"first",
"func",
"(",
"i",
"int",
")",
"net",
".",
"IP",
",",
"full",
"func",
"(",
"i",
"int",
")",
"Range",
",",
"n",
"int",
",",
"ip",
"net",
".",
"IP",
",",
")",
"(",
"r",
"Range",
",",
"ok",
"bool",
",",
")",
"{",
"i",
":=",
"sort",
".",
"Search",
"(",
"n",
",",
"func",
"(",
"i",
"int",
")",
"bool",
"{",
"if",
"i",
"+",
"1",
">=",
"n",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"bytes",
".",
"Compare",
"(",
"ip",
",",
"first",
"(",
"i",
"+",
"1",
")",
")",
"<",
"0",
"\n",
"}",
")",
"\n",
"if",
"i",
"==",
"n",
"{",
"return",
"\n",
"}",
"\n",
"r",
"=",
"full",
"(",
"i",
")",
"\n",
"ok",
"=",
"bytes",
".",
"Compare",
"(",
"r",
".",
"First",
",",
"ip",
")",
"<=",
"0",
"&&",
"bytes",
".",
"Compare",
"(",
"ip",
",",
"r",
".",
"Last",
")",
"<=",
"0",
"\n",
"return",
"\n",
"}"
] |
// Return a range that contains ip, or nil.
|
[
"Return",
"a",
"range",
"that",
"contains",
"ip",
"or",
"nil",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/iplist/iplist.go#L81-L103
|
train
|
anacrolix/torrent
|
iplist/iplist.go
|
lookup
|
func (ipl *IPList) lookup(ip net.IP) (Range, bool) {
return lookup(func(i int) net.IP {
return ipl.ranges[i].First
}, func(i int) Range {
return ipl.ranges[i]
}, len(ipl.ranges), ip)
}
|
go
|
func (ipl *IPList) lookup(ip net.IP) (Range, bool) {
return lookup(func(i int) net.IP {
return ipl.ranges[i].First
}, func(i int) Range {
return ipl.ranges[i]
}, len(ipl.ranges), ip)
}
|
[
"func",
"(",
"ipl",
"*",
"IPList",
")",
"lookup",
"(",
"ip",
"net",
".",
"IP",
")",
"(",
"Range",
",",
"bool",
")",
"{",
"return",
"lookup",
"(",
"func",
"(",
"i",
"int",
")",
"net",
".",
"IP",
"{",
"return",
"ipl",
".",
"ranges",
"[",
"i",
"]",
".",
"First",
"\n",
"}",
",",
"func",
"(",
"i",
"int",
")",
"Range",
"{",
"return",
"ipl",
".",
"ranges",
"[",
"i",
"]",
"\n",
"}",
",",
"len",
"(",
"ipl",
".",
"ranges",
")",
",",
"ip",
")",
"\n",
"}"
] |
// Return the range the given IP is in. Returns nil if no range is found.
|
[
"Return",
"the",
"range",
"the",
"given",
"IP",
"is",
"in",
".",
"Returns",
"nil",
"if",
"no",
"range",
"is",
"found",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/iplist/iplist.go#L106-L112
|
train
|
anacrolix/torrent
|
iplist/iplist.go
|
NewFromReader
|
func NewFromReader(f io.Reader) (ret *IPList, err error) {
var ranges []Range
// There's a lot of similar descriptions, so we maintain a pool and reuse
// them to reduce memory overhead.
uniqStrs := make(map[string]string)
scanner := bufio.NewScanner(f)
lineNum := 1
for scanner.Scan() {
r, ok, lineErr := ParseBlocklistP2PLine(scanner.Bytes())
if lineErr != nil {
err = fmt.Errorf("error parsing line %d: %s", lineNum, lineErr)
return
}
lineNum++
if !ok {
continue
}
if s, ok := uniqStrs[r.Description]; ok {
r.Description = s
} else {
uniqStrs[r.Description] = r.Description
}
ranges = append(ranges, r)
}
err = scanner.Err()
if err != nil {
return
}
ret = New(ranges)
return
}
|
go
|
func NewFromReader(f io.Reader) (ret *IPList, err error) {
var ranges []Range
// There's a lot of similar descriptions, so we maintain a pool and reuse
// them to reduce memory overhead.
uniqStrs := make(map[string]string)
scanner := bufio.NewScanner(f)
lineNum := 1
for scanner.Scan() {
r, ok, lineErr := ParseBlocklistP2PLine(scanner.Bytes())
if lineErr != nil {
err = fmt.Errorf("error parsing line %d: %s", lineNum, lineErr)
return
}
lineNum++
if !ok {
continue
}
if s, ok := uniqStrs[r.Description]; ok {
r.Description = s
} else {
uniqStrs[r.Description] = r.Description
}
ranges = append(ranges, r)
}
err = scanner.Err()
if err != nil {
return
}
ret = New(ranges)
return
}
|
[
"func",
"NewFromReader",
"(",
"f",
"io",
".",
"Reader",
")",
"(",
"ret",
"*",
"IPList",
",",
"err",
"error",
")",
"{",
"var",
"ranges",
"[",
"]",
"Range",
"\n",
"uniqStrs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"scanner",
":=",
"bufio",
".",
"NewScanner",
"(",
"f",
")",
"\n",
"lineNum",
":=",
"1",
"\n",
"for",
"scanner",
".",
"Scan",
"(",
")",
"{",
"r",
",",
"ok",
",",
"lineErr",
":=",
"ParseBlocklistP2PLine",
"(",
"scanner",
".",
"Bytes",
"(",
")",
")",
"\n",
"if",
"lineErr",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"error parsing line %d: %s\"",
",",
"lineNum",
",",
"lineErr",
")",
"\n",
"return",
"\n",
"}",
"\n",
"lineNum",
"++",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"s",
",",
"ok",
":=",
"uniqStrs",
"[",
"r",
".",
"Description",
"]",
";",
"ok",
"{",
"r",
".",
"Description",
"=",
"s",
"\n",
"}",
"else",
"{",
"uniqStrs",
"[",
"r",
".",
"Description",
"]",
"=",
"r",
".",
"Description",
"\n",
"}",
"\n",
"ranges",
"=",
"append",
"(",
"ranges",
",",
"r",
")",
"\n",
"}",
"\n",
"err",
"=",
"scanner",
".",
"Err",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"ret",
"=",
"New",
"(",
"ranges",
")",
"\n",
"return",
"\n",
"}"
] |
// Creates an IPList from a line-delimited P2P Plaintext file.
|
[
"Creates",
"an",
"IPList",
"from",
"a",
"line",
"-",
"delimited",
"P2P",
"Plaintext",
"file",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/iplist/iplist.go#L155-L185
|
train
|
anacrolix/torrent
|
bencode/api.go
|
Unmarshal
|
func Unmarshal(data []byte, v interface{}) (err error) {
buf := bytes.NewBuffer(data)
e := Decoder{r: buf}
err = e.Decode(v)
if err == nil && buf.Len() != 0 {
err = ErrUnusedTrailingBytes{buf.Len()}
}
return
}
|
go
|
func Unmarshal(data []byte, v interface{}) (err error) {
buf := bytes.NewBuffer(data)
e := Decoder{r: buf}
err = e.Decode(v)
if err == nil && buf.Len() != 0 {
err = ErrUnusedTrailingBytes{buf.Len()}
}
return
}
|
[
"func",
"Unmarshal",
"(",
"data",
"[",
"]",
"byte",
",",
"v",
"interface",
"{",
"}",
")",
"(",
"err",
"error",
")",
"{",
"buf",
":=",
"bytes",
".",
"NewBuffer",
"(",
"data",
")",
"\n",
"e",
":=",
"Decoder",
"{",
"r",
":",
"buf",
"}",
"\n",
"err",
"=",
"e",
".",
"Decode",
"(",
"v",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"buf",
".",
"Len",
"(",
")",
"!=",
"0",
"{",
"err",
"=",
"ErrUnusedTrailingBytes",
"{",
"buf",
".",
"Len",
"(",
")",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Unmarshal the bencode value in the 'data' to a value pointed by the 'v'
// pointer, return a non-nil error if any.
|
[
"Unmarshal",
"the",
"bencode",
"value",
"in",
"the",
"data",
"to",
"a",
"value",
"pointed",
"by",
"the",
"v",
"pointer",
"return",
"a",
"non",
"-",
"nil",
"error",
"if",
"any",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/api.go#L133-L141
|
train
|
anacrolix/torrent
|
reader.go
|
SetResponsive
|
func (r *reader) SetResponsive() {
r.responsive = true
r.t.cl.event.Broadcast()
}
|
go
|
func (r *reader) SetResponsive() {
r.responsive = true
r.t.cl.event.Broadcast()
}
|
[
"func",
"(",
"r",
"*",
"reader",
")",
"SetResponsive",
"(",
")",
"{",
"r",
".",
"responsive",
"=",
"true",
"\n",
"r",
".",
"t",
".",
"cl",
".",
"event",
".",
"Broadcast",
"(",
")",
"\n",
"}"
] |
// Don't wait for pieces to complete and be verified. Read calls return as
// soon as they can when the underlying chunks become available.
|
[
"Don",
"t",
"wait",
"for",
"pieces",
"to",
"complete",
"and",
"be",
"verified",
".",
"Read",
"calls",
"return",
"as",
"soon",
"as",
"they",
"can",
"when",
"the",
"underlying",
"chunks",
"become",
"available",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/reader.go#L54-L57
|
train
|
anacrolix/torrent
|
reader.go
|
SetReadahead
|
func (r *reader) SetReadahead(readahead int64) {
r.mu.Lock()
r.readahead = readahead
r.mu.Unlock()
r.t.cl.lock()
defer r.t.cl.unlock()
r.posChanged()
}
|
go
|
func (r *reader) SetReadahead(readahead int64) {
r.mu.Lock()
r.readahead = readahead
r.mu.Unlock()
r.t.cl.lock()
defer r.t.cl.unlock()
r.posChanged()
}
|
[
"func",
"(",
"r",
"*",
"reader",
")",
"SetReadahead",
"(",
"readahead",
"int64",
")",
"{",
"r",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"r",
".",
"readahead",
"=",
"readahead",
"\n",
"r",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"r",
".",
"t",
".",
"cl",
".",
"lock",
"(",
")",
"\n",
"defer",
"r",
".",
"t",
".",
"cl",
".",
"unlock",
"(",
")",
"\n",
"r",
".",
"posChanged",
"(",
")",
"\n",
"}"
] |
// Configure the number of bytes ahead of a read that should also be
// prioritized in preparation for further reads.
|
[
"Configure",
"the",
"number",
"of",
"bytes",
"ahead",
"of",
"a",
"read",
"that",
"should",
"also",
"be",
"prioritized",
"in",
"preparation",
"for",
"further",
"reads",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/reader.go#L67-L74
|
train
|
anacrolix/torrent
|
reader.go
|
available
|
func (r *reader) available(off, max int64) (ret int64) {
off += r.offset
for max > 0 {
req, ok := r.t.offsetRequest(off)
if !ok {
break
}
if !r.t.haveChunk(req) {
break
}
len1 := int64(req.Length) - (off - r.t.requestOffset(req))
max -= len1
ret += len1
off += len1
}
// Ensure that ret hasn't exceeded our original max.
if max < 0 {
ret += max
}
return
}
|
go
|
func (r *reader) available(off, max int64) (ret int64) {
off += r.offset
for max > 0 {
req, ok := r.t.offsetRequest(off)
if !ok {
break
}
if !r.t.haveChunk(req) {
break
}
len1 := int64(req.Length) - (off - r.t.requestOffset(req))
max -= len1
ret += len1
off += len1
}
// Ensure that ret hasn't exceeded our original max.
if max < 0 {
ret += max
}
return
}
|
[
"func",
"(",
"r",
"*",
"reader",
")",
"available",
"(",
"off",
",",
"max",
"int64",
")",
"(",
"ret",
"int64",
")",
"{",
"off",
"+=",
"r",
".",
"offset",
"\n",
"for",
"max",
">",
"0",
"{",
"req",
",",
"ok",
":=",
"r",
".",
"t",
".",
"offsetRequest",
"(",
"off",
")",
"\n",
"if",
"!",
"ok",
"{",
"break",
"\n",
"}",
"\n",
"if",
"!",
"r",
".",
"t",
".",
"haveChunk",
"(",
"req",
")",
"{",
"break",
"\n",
"}",
"\n",
"len1",
":=",
"int64",
"(",
"req",
".",
"Length",
")",
"-",
"(",
"off",
"-",
"r",
".",
"t",
".",
"requestOffset",
"(",
"req",
")",
")",
"\n",
"max",
"-=",
"len1",
"\n",
"ret",
"+=",
"len1",
"\n",
"off",
"+=",
"len1",
"\n",
"}",
"\n",
"if",
"max",
"<",
"0",
"{",
"ret",
"+=",
"max",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// How many bytes are available to read. Max is the most we could require.
|
[
"How",
"many",
"bytes",
"are",
"available",
"to",
"read",
".",
"Max",
"is",
"the",
"most",
"we",
"could",
"require",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/reader.go#L91-L111
|
train
|
anacrolix/torrent
|
reader.go
|
piecesUncached
|
func (r *reader) piecesUncached() (ret pieceRange) {
ra := r.readahead
if ra < 1 {
// Needs to be at least 1, because [x, x) means we don't want
// anything.
ra = 1
}
if ra > r.length-r.pos {
ra = r.length - r.pos
}
ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
return
}
|
go
|
func (r *reader) piecesUncached() (ret pieceRange) {
ra := r.readahead
if ra < 1 {
// Needs to be at least 1, because [x, x) means we don't want
// anything.
ra = 1
}
if ra > r.length-r.pos {
ra = r.length - r.pos
}
ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
return
}
|
[
"func",
"(",
"r",
"*",
"reader",
")",
"piecesUncached",
"(",
")",
"(",
"ret",
"pieceRange",
")",
"{",
"ra",
":=",
"r",
".",
"readahead",
"\n",
"if",
"ra",
"<",
"1",
"{",
"ra",
"=",
"1",
"\n",
"}",
"\n",
"if",
"ra",
">",
"r",
".",
"length",
"-",
"r",
".",
"pos",
"{",
"ra",
"=",
"r",
".",
"length",
"-",
"r",
".",
"pos",
"\n",
"}",
"\n",
"ret",
".",
"begin",
",",
"ret",
".",
"end",
"=",
"r",
".",
"t",
".",
"byteRegionPieces",
"(",
"r",
".",
"torrentOffset",
"(",
"r",
".",
"pos",
")",
",",
"ra",
")",
"\n",
"return",
"\n",
"}"
] |
// Calculates the pieces this reader wants downloaded, ignoring the cached
// value at r.pieces.
|
[
"Calculates",
"the",
"pieces",
"this",
"reader",
"wants",
"downloaded",
"ignoring",
"the",
"cached",
"value",
"at",
"r",
".",
"pieces",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/reader.go#L121-L133
|
train
|
anacrolix/torrent
|
reader.go
|
waitAvailable
|
func (r *reader) waitAvailable(pos, wanted int64, ctxErr *error) (avail int64) {
r.t.cl.lock()
defer r.t.cl.unlock()
for !r.readable(pos) && *ctxErr == nil {
r.waitReadable(pos)
}
return r.available(pos, wanted)
}
|
go
|
func (r *reader) waitAvailable(pos, wanted int64, ctxErr *error) (avail int64) {
r.t.cl.lock()
defer r.t.cl.unlock()
for !r.readable(pos) && *ctxErr == nil {
r.waitReadable(pos)
}
return r.available(pos, wanted)
}
|
[
"func",
"(",
"r",
"*",
"reader",
")",
"waitAvailable",
"(",
"pos",
",",
"wanted",
"int64",
",",
"ctxErr",
"*",
"error",
")",
"(",
"avail",
"int64",
")",
"{",
"r",
".",
"t",
".",
"cl",
".",
"lock",
"(",
")",
"\n",
"defer",
"r",
".",
"t",
".",
"cl",
".",
"unlock",
"(",
")",
"\n",
"for",
"!",
"r",
".",
"readable",
"(",
"pos",
")",
"&&",
"*",
"ctxErr",
"==",
"nil",
"{",
"r",
".",
"waitReadable",
"(",
"pos",
")",
"\n",
"}",
"\n",
"return",
"r",
".",
"available",
"(",
"pos",
",",
"wanted",
")",
"\n",
"}"
] |
// Wait until some data should be available to read. Tickles the client if it
// isn't. Returns how much should be readable without blocking.
|
[
"Wait",
"until",
"some",
"data",
"should",
"be",
"available",
"to",
"read",
".",
"Tickles",
"the",
"client",
"if",
"it",
"isn",
"t",
".",
"Returns",
"how",
"much",
"should",
"be",
"readable",
"without",
"blocking",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/reader.go#L184-L191
|
train
|
anacrolix/torrent
|
reader.go
|
readOnceAt
|
func (r *reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) {
if pos >= r.length {
err = io.EOF
return
}
for {
avail := r.waitAvailable(pos, int64(len(b)), ctxErr)
if avail == 0 {
if r.t.closed.IsSet() {
err = errors.New("torrent closed")
return
}
if *ctxErr != nil {
err = *ctxErr
return
}
}
pi := pieceIndex(r.torrentOffset(pos) / r.t.info.PieceLength)
ip := r.t.info.Piece(pi)
po := r.torrentOffset(pos) % r.t.info.PieceLength
b1 := missinggo.LimitLen(b, ip.Length()-po, avail)
n, err = r.t.readAt(b1, r.torrentOffset(pos))
if n != 0 {
err = nil
return
}
r.t.cl.lock()
// TODO: Just reset pieces in the readahead window. This might help
// prevent thrashing with small caches and file and piece priorities.
log.Printf("error reading torrent %s piece %d offset %d, %d bytes: %v",
r.t.infoHash.HexString(), pi, po, len(b1), err)
if !r.t.updatePieceCompletion(pi) {
log.Printf("piece %d completion unchanged", pi)
}
r.t.cl.unlock()
}
}
|
go
|
func (r *reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) {
if pos >= r.length {
err = io.EOF
return
}
for {
avail := r.waitAvailable(pos, int64(len(b)), ctxErr)
if avail == 0 {
if r.t.closed.IsSet() {
err = errors.New("torrent closed")
return
}
if *ctxErr != nil {
err = *ctxErr
return
}
}
pi := pieceIndex(r.torrentOffset(pos) / r.t.info.PieceLength)
ip := r.t.info.Piece(pi)
po := r.torrentOffset(pos) % r.t.info.PieceLength
b1 := missinggo.LimitLen(b, ip.Length()-po, avail)
n, err = r.t.readAt(b1, r.torrentOffset(pos))
if n != 0 {
err = nil
return
}
r.t.cl.lock()
// TODO: Just reset pieces in the readahead window. This might help
// prevent thrashing with small caches and file and piece priorities.
log.Printf("error reading torrent %s piece %d offset %d, %d bytes: %v",
r.t.infoHash.HexString(), pi, po, len(b1), err)
if !r.t.updatePieceCompletion(pi) {
log.Printf("piece %d completion unchanged", pi)
}
r.t.cl.unlock()
}
}
|
[
"func",
"(",
"r",
"*",
"reader",
")",
"readOnceAt",
"(",
"b",
"[",
"]",
"byte",
",",
"pos",
"int64",
",",
"ctxErr",
"*",
"error",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"if",
"pos",
">=",
"r",
".",
"length",
"{",
"err",
"=",
"io",
".",
"EOF",
"\n",
"return",
"\n",
"}",
"\n",
"for",
"{",
"avail",
":=",
"r",
".",
"waitAvailable",
"(",
"pos",
",",
"int64",
"(",
"len",
"(",
"b",
")",
")",
",",
"ctxErr",
")",
"\n",
"if",
"avail",
"==",
"0",
"{",
"if",
"r",
".",
"t",
".",
"closed",
".",
"IsSet",
"(",
")",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"torrent closed\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"*",
"ctxErr",
"!=",
"nil",
"{",
"err",
"=",
"*",
"ctxErr",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"pi",
":=",
"pieceIndex",
"(",
"r",
".",
"torrentOffset",
"(",
"pos",
")",
"/",
"r",
".",
"t",
".",
"info",
".",
"PieceLength",
")",
"\n",
"ip",
":=",
"r",
".",
"t",
".",
"info",
".",
"Piece",
"(",
"pi",
")",
"\n",
"po",
":=",
"r",
".",
"torrentOffset",
"(",
"pos",
")",
"%",
"r",
".",
"t",
".",
"info",
".",
"PieceLength",
"\n",
"b1",
":=",
"missinggo",
".",
"LimitLen",
"(",
"b",
",",
"ip",
".",
"Length",
"(",
")",
"-",
"po",
",",
"avail",
")",
"\n",
"n",
",",
"err",
"=",
"r",
".",
"t",
".",
"readAt",
"(",
"b1",
",",
"r",
".",
"torrentOffset",
"(",
"pos",
")",
")",
"\n",
"if",
"n",
"!=",
"0",
"{",
"err",
"=",
"nil",
"\n",
"return",
"\n",
"}",
"\n",
"r",
".",
"t",
".",
"cl",
".",
"lock",
"(",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"error reading torrent %s piece %d offset %d, %d bytes: %v\"",
",",
"r",
".",
"t",
".",
"infoHash",
".",
"HexString",
"(",
")",
",",
"pi",
",",
"po",
",",
"len",
"(",
"b1",
")",
",",
"err",
")",
"\n",
"if",
"!",
"r",
".",
"t",
".",
"updatePieceCompletion",
"(",
"pi",
")",
"{",
"log",
".",
"Printf",
"(",
"\"piece %d completion unchanged\"",
",",
"pi",
")",
"\n",
"}",
"\n",
"r",
".",
"t",
".",
"cl",
".",
"unlock",
"(",
")",
"\n",
"}",
"\n",
"}"
] |
// Performs at most one successful read to torrent storage.
|
[
"Performs",
"at",
"most",
"one",
"successful",
"read",
"to",
"torrent",
"storage",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/reader.go#L198-L234
|
train
|
anacrolix/torrent
|
tracker/udp.go
|
write
|
func (c *udpAnnounce) write(h *RequestHeader, body interface{}, trailer []byte) (err error) {
var buf bytes.Buffer
err = binary.Write(&buf, binary.BigEndian, h)
if err != nil {
panic(err)
}
if body != nil {
err = binary.Write(&buf, binary.BigEndian, body)
if err != nil {
panic(err)
}
}
_, err = buf.Write(trailer)
if err != nil {
return
}
n, err := c.socket.Write(buf.Bytes())
if err != nil {
return
}
if n != buf.Len() {
panic("write should send all or error")
}
return
}
|
go
|
func (c *udpAnnounce) write(h *RequestHeader, body interface{}, trailer []byte) (err error) {
var buf bytes.Buffer
err = binary.Write(&buf, binary.BigEndian, h)
if err != nil {
panic(err)
}
if body != nil {
err = binary.Write(&buf, binary.BigEndian, body)
if err != nil {
panic(err)
}
}
_, err = buf.Write(trailer)
if err != nil {
return
}
n, err := c.socket.Write(buf.Bytes())
if err != nil {
return
}
if n != buf.Len() {
panic("write should send all or error")
}
return
}
|
[
"func",
"(",
"c",
"*",
"udpAnnounce",
")",
"write",
"(",
"h",
"*",
"RequestHeader",
",",
"body",
"interface",
"{",
"}",
",",
"trailer",
"[",
"]",
"byte",
")",
"(",
"err",
"error",
")",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"err",
"=",
"binary",
".",
"Write",
"(",
"&",
"buf",
",",
"binary",
".",
"BigEndian",
",",
"h",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"body",
"!=",
"nil",
"{",
"err",
"=",
"binary",
".",
"Write",
"(",
"&",
"buf",
",",
"binary",
".",
"BigEndian",
",",
"body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"buf",
".",
"Write",
"(",
"trailer",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"c",
".",
"socket",
".",
"Write",
"(",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"n",
"!=",
"buf",
".",
"Len",
"(",
")",
"{",
"panic",
"(",
"\"write should send all or error\"",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// body is the binary serializable request body. trailer is optional data
// following it, such as for BEP 41.
|
[
"body",
"is",
"the",
"binary",
"serializable",
"request",
"body",
".",
"trailer",
"is",
"optional",
"data",
"following",
"it",
"such",
"as",
"for",
"BEP",
"41",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/tracker/udp.go#L156-L180
|
train
|
anacrolix/torrent
|
tracker/udp.go
|
request
|
func (c *udpAnnounce) request(action Action, args interface{}, options []byte) (*bytes.Buffer, error) {
tid := newTransactionId()
if err := errors.Wrap(
c.write(
&RequestHeader{
ConnectionId: c.connectionId,
Action: action,
TransactionId: tid,
}, args, options),
"writing request",
); err != nil {
return nil, err
}
c.socket.SetReadDeadline(time.Now().Add(timeout(c.contiguousTimeouts)))
b := make([]byte, 0x800) // 2KiB
for {
var (
n int
readErr error
readDone = make(chan struct{})
)
go func() {
defer close(readDone)
n, readErr = c.socket.Read(b)
}()
ctx := c.a.Context
if ctx == nil {
ctx = context.Background()
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-readDone:
}
if opE, ok := readErr.(*net.OpError); ok && opE.Timeout() {
c.contiguousTimeouts++
}
if readErr != nil {
return nil, errors.Wrap(readErr, "reading from socket")
}
buf := bytes.NewBuffer(b[:n])
var h ResponseHeader
err := binary.Read(buf, binary.BigEndian, &h)
switch err {
default:
panic(err)
case io.ErrUnexpectedEOF, io.EOF:
continue
case nil:
}
if h.TransactionId != tid {
continue
}
c.contiguousTimeouts = 0
if h.Action == ActionError {
err = errors.New(buf.String())
}
return buf, err
}
}
|
go
|
func (c *udpAnnounce) request(action Action, args interface{}, options []byte) (*bytes.Buffer, error) {
tid := newTransactionId()
if err := errors.Wrap(
c.write(
&RequestHeader{
ConnectionId: c.connectionId,
Action: action,
TransactionId: tid,
}, args, options),
"writing request",
); err != nil {
return nil, err
}
c.socket.SetReadDeadline(time.Now().Add(timeout(c.contiguousTimeouts)))
b := make([]byte, 0x800) // 2KiB
for {
var (
n int
readErr error
readDone = make(chan struct{})
)
go func() {
defer close(readDone)
n, readErr = c.socket.Read(b)
}()
ctx := c.a.Context
if ctx == nil {
ctx = context.Background()
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-readDone:
}
if opE, ok := readErr.(*net.OpError); ok && opE.Timeout() {
c.contiguousTimeouts++
}
if readErr != nil {
return nil, errors.Wrap(readErr, "reading from socket")
}
buf := bytes.NewBuffer(b[:n])
var h ResponseHeader
err := binary.Read(buf, binary.BigEndian, &h)
switch err {
default:
panic(err)
case io.ErrUnexpectedEOF, io.EOF:
continue
case nil:
}
if h.TransactionId != tid {
continue
}
c.contiguousTimeouts = 0
if h.Action == ActionError {
err = errors.New(buf.String())
}
return buf, err
}
}
|
[
"func",
"(",
"c",
"*",
"udpAnnounce",
")",
"request",
"(",
"action",
"Action",
",",
"args",
"interface",
"{",
"}",
",",
"options",
"[",
"]",
"byte",
")",
"(",
"*",
"bytes",
".",
"Buffer",
",",
"error",
")",
"{",
"tid",
":=",
"newTransactionId",
"(",
")",
"\n",
"if",
"err",
":=",
"errors",
".",
"Wrap",
"(",
"c",
".",
"write",
"(",
"&",
"RequestHeader",
"{",
"ConnectionId",
":",
"c",
".",
"connectionId",
",",
"Action",
":",
"action",
",",
"TransactionId",
":",
"tid",
",",
"}",
",",
"args",
",",
"options",
")",
",",
"\"writing request\"",
",",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"c",
".",
"socket",
".",
"SetReadDeadline",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"timeout",
"(",
"c",
".",
"contiguousTimeouts",
")",
")",
")",
"\n",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0x800",
")",
"\n",
"for",
"{",
"var",
"(",
"n",
"int",
"\n",
"readErr",
"error",
"\n",
"readDone",
"=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"defer",
"close",
"(",
"readDone",
")",
"\n",
"n",
",",
"readErr",
"=",
"c",
".",
"socket",
".",
"Read",
"(",
"b",
")",
"\n",
"}",
"(",
")",
"\n",
"ctx",
":=",
"c",
".",
"a",
".",
"Context",
"\n",
"if",
"ctx",
"==",
"nil",
"{",
"ctx",
"=",
"context",
".",
"Background",
"(",
")",
"\n",
"}",
"\n",
"select",
"{",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"nil",
",",
"ctx",
".",
"Err",
"(",
")",
"\n",
"case",
"<-",
"readDone",
":",
"}",
"\n",
"if",
"opE",
",",
"ok",
":=",
"readErr",
".",
"(",
"*",
"net",
".",
"OpError",
")",
";",
"ok",
"&&",
"opE",
".",
"Timeout",
"(",
")",
"{",
"c",
".",
"contiguousTimeouts",
"++",
"\n",
"}",
"\n",
"if",
"readErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"readErr",
",",
"\"reading from socket\"",
")",
"\n",
"}",
"\n",
"buf",
":=",
"bytes",
".",
"NewBuffer",
"(",
"b",
"[",
":",
"n",
"]",
")",
"\n",
"var",
"h",
"ResponseHeader",
"\n",
"err",
":=",
"binary",
".",
"Read",
"(",
"buf",
",",
"binary",
".",
"BigEndian",
",",
"&",
"h",
")",
"\n",
"switch",
"err",
"{",
"default",
":",
"panic",
"(",
"err",
")",
"\n",
"case",
"io",
".",
"ErrUnexpectedEOF",
",",
"io",
".",
"EOF",
":",
"continue",
"\n",
"case",
"nil",
":",
"}",
"\n",
"if",
"h",
".",
"TransactionId",
"!=",
"tid",
"{",
"continue",
"\n",
"}",
"\n",
"c",
".",
"contiguousTimeouts",
"=",
"0",
"\n",
"if",
"h",
".",
"Action",
"==",
"ActionError",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"buf",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"buf",
",",
"err",
"\n",
"}",
"\n",
"}"
] |
// args is the binary serializable request body. trailer is optional data
// following it, such as for BEP 41.
|
[
"args",
"is",
"the",
"binary",
"serializable",
"request",
"body",
".",
"trailer",
"is",
"optional",
"data",
"following",
"it",
"such",
"as",
"for",
"BEP",
"41",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/tracker/udp.go#L192-L251
|
train
|
anacrolix/torrent
|
misc.go
|
metadataPieceSize
|
func metadataPieceSize(totalSize int, piece int) int {
ret := totalSize - piece*(1<<14)
if ret > 1<<14 {
ret = 1 << 14
}
return ret
}
|
go
|
func metadataPieceSize(totalSize int, piece int) int {
ret := totalSize - piece*(1<<14)
if ret > 1<<14 {
ret = 1 << 14
}
return ret
}
|
[
"func",
"metadataPieceSize",
"(",
"totalSize",
"int",
",",
"piece",
"int",
")",
"int",
"{",
"ret",
":=",
"totalSize",
"-",
"piece",
"*",
"(",
"1",
"<<",
"14",
")",
"\n",
"if",
"ret",
">",
"1",
"<<",
"14",
"{",
"ret",
"=",
"1",
"<<",
"14",
"\n",
"}",
"\n",
"return",
"ret",
"\n",
"}"
] |
// The size in bytes of a metadata extension piece.
|
[
"The",
"size",
"in",
"bytes",
"of",
"a",
"metadata",
"extension",
"piece",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/misc.go#L47-L53
|
train
|
anacrolix/torrent
|
misc.go
|
torrentOffsetRequest
|
func torrentOffsetRequest(torrentLength, pieceSize, chunkSize, offset int64) (
r request, ok bool) {
if offset < 0 || offset >= torrentLength {
return
}
r.Index = pp.Integer(offset / pieceSize)
r.Begin = pp.Integer(offset % pieceSize / chunkSize * chunkSize)
r.Length = pp.Integer(chunkSize)
pieceLeft := pp.Integer(pieceSize - int64(r.Begin))
if r.Length > pieceLeft {
r.Length = pieceLeft
}
torrentLeft := torrentLength - int64(r.Index)*pieceSize - int64(r.Begin)
if int64(r.Length) > torrentLeft {
r.Length = pp.Integer(torrentLeft)
}
ok = true
return
}
|
go
|
func torrentOffsetRequest(torrentLength, pieceSize, chunkSize, offset int64) (
r request, ok bool) {
if offset < 0 || offset >= torrentLength {
return
}
r.Index = pp.Integer(offset / pieceSize)
r.Begin = pp.Integer(offset % pieceSize / chunkSize * chunkSize)
r.Length = pp.Integer(chunkSize)
pieceLeft := pp.Integer(pieceSize - int64(r.Begin))
if r.Length > pieceLeft {
r.Length = pieceLeft
}
torrentLeft := torrentLength - int64(r.Index)*pieceSize - int64(r.Begin)
if int64(r.Length) > torrentLeft {
r.Length = pp.Integer(torrentLeft)
}
ok = true
return
}
|
[
"func",
"torrentOffsetRequest",
"(",
"torrentLength",
",",
"pieceSize",
",",
"chunkSize",
",",
"offset",
"int64",
")",
"(",
"r",
"request",
",",
"ok",
"bool",
")",
"{",
"if",
"offset",
"<",
"0",
"||",
"offset",
">=",
"torrentLength",
"{",
"return",
"\n",
"}",
"\n",
"r",
".",
"Index",
"=",
"pp",
".",
"Integer",
"(",
"offset",
"/",
"pieceSize",
")",
"\n",
"r",
".",
"Begin",
"=",
"pp",
".",
"Integer",
"(",
"offset",
"%",
"pieceSize",
"/",
"chunkSize",
"*",
"chunkSize",
")",
"\n",
"r",
".",
"Length",
"=",
"pp",
".",
"Integer",
"(",
"chunkSize",
")",
"\n",
"pieceLeft",
":=",
"pp",
".",
"Integer",
"(",
"pieceSize",
"-",
"int64",
"(",
"r",
".",
"Begin",
")",
")",
"\n",
"if",
"r",
".",
"Length",
">",
"pieceLeft",
"{",
"r",
".",
"Length",
"=",
"pieceLeft",
"\n",
"}",
"\n",
"torrentLeft",
":=",
"torrentLength",
"-",
"int64",
"(",
"r",
".",
"Index",
")",
"*",
"pieceSize",
"-",
"int64",
"(",
"r",
".",
"Begin",
")",
"\n",
"if",
"int64",
"(",
"r",
".",
"Length",
")",
">",
"torrentLeft",
"{",
"r",
".",
"Length",
"=",
"pp",
".",
"Integer",
"(",
"torrentLeft",
")",
"\n",
"}",
"\n",
"ok",
"=",
"true",
"\n",
"return",
"\n",
"}"
] |
// Return the request that would include the given offset into the torrent data.
|
[
"Return",
"the",
"request",
"that",
"would",
"include",
"the",
"given",
"offset",
"into",
"the",
"torrent",
"data",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/misc.go#L56-L74
|
train
|
anacrolix/torrent
|
peer_protocol/handshake.go
|
Handshake
|
func Handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions PeerExtensionBits) (res HandshakeResult, ok bool, err error) {
// Bytes to be sent to the peer. Should never block the sender.
postCh := make(chan []byte, 4)
// A single error value sent when the writer completes.
writeDone := make(chan error, 1)
// Performs writes to the socket and ensures posts don't block.
go handshakeWriter(sock, postCh, writeDone)
defer func() {
close(postCh) // Done writing.
if !ok {
return
}
if err != nil {
panic(err)
}
// Wait until writes complete before returning from handshake.
err = <-writeDone
if err != nil {
err = fmt.Errorf("error writing: %s", err)
}
}()
post := func(bb []byte) {
select {
case postCh <- bb:
default:
panic("mustn't block while posting")
}
}
post([]byte(Protocol))
post(extensions[:])
if ih != nil { // We already know what we want.
post(ih[:])
post(peerID[:])
}
var b [68]byte
_, err = io.ReadFull(sock, b[:68])
if err != nil {
err = nil
return
}
if string(b[:20]) != Protocol {
return
}
missinggo.CopyExact(&res.PeerExtensionBits, b[20:28])
missinggo.CopyExact(&res.Hash, b[28:48])
missinggo.CopyExact(&res.PeerID, b[48:68])
// peerExtensions.Add(res.PeerExtensionBits.String(), 1)
// TODO: Maybe we can just drop peers here if we're not interested. This
// could prevent them trying to reconnect, falsely believing there was
// just a problem.
if ih == nil { // We were waiting for the peer to tell us what they wanted.
post(res.Hash[:])
post(peerID[:])
}
ok = true
return
}
|
go
|
func Handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions PeerExtensionBits) (res HandshakeResult, ok bool, err error) {
// Bytes to be sent to the peer. Should never block the sender.
postCh := make(chan []byte, 4)
// A single error value sent when the writer completes.
writeDone := make(chan error, 1)
// Performs writes to the socket and ensures posts don't block.
go handshakeWriter(sock, postCh, writeDone)
defer func() {
close(postCh) // Done writing.
if !ok {
return
}
if err != nil {
panic(err)
}
// Wait until writes complete before returning from handshake.
err = <-writeDone
if err != nil {
err = fmt.Errorf("error writing: %s", err)
}
}()
post := func(bb []byte) {
select {
case postCh <- bb:
default:
panic("mustn't block while posting")
}
}
post([]byte(Protocol))
post(extensions[:])
if ih != nil { // We already know what we want.
post(ih[:])
post(peerID[:])
}
var b [68]byte
_, err = io.ReadFull(sock, b[:68])
if err != nil {
err = nil
return
}
if string(b[:20]) != Protocol {
return
}
missinggo.CopyExact(&res.PeerExtensionBits, b[20:28])
missinggo.CopyExact(&res.Hash, b[28:48])
missinggo.CopyExact(&res.PeerID, b[48:68])
// peerExtensions.Add(res.PeerExtensionBits.String(), 1)
// TODO: Maybe we can just drop peers here if we're not interested. This
// could prevent them trying to reconnect, falsely believing there was
// just a problem.
if ih == nil { // We were waiting for the peer to tell us what they wanted.
post(res.Hash[:])
post(peerID[:])
}
ok = true
return
}
|
[
"func",
"Handshake",
"(",
"sock",
"io",
".",
"ReadWriter",
",",
"ih",
"*",
"metainfo",
".",
"Hash",
",",
"peerID",
"[",
"20",
"]",
"byte",
",",
"extensions",
"PeerExtensionBits",
")",
"(",
"res",
"HandshakeResult",
",",
"ok",
"bool",
",",
"err",
"error",
")",
"{",
"postCh",
":=",
"make",
"(",
"chan",
"[",
"]",
"byte",
",",
"4",
")",
"\n",
"writeDone",
":=",
"make",
"(",
"chan",
"error",
",",
"1",
")",
"\n",
"go",
"handshakeWriter",
"(",
"sock",
",",
"postCh",
",",
"writeDone",
")",
"\n",
"defer",
"func",
"(",
")",
"{",
"close",
"(",
"postCh",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"<-",
"writeDone",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"error writing: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"post",
":=",
"func",
"(",
"bb",
"[",
"]",
"byte",
")",
"{",
"select",
"{",
"case",
"postCh",
"<-",
"bb",
":",
"default",
":",
"panic",
"(",
"\"mustn't block while posting\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"post",
"(",
"[",
"]",
"byte",
"(",
"Protocol",
")",
")",
"\n",
"post",
"(",
"extensions",
"[",
":",
"]",
")",
"\n",
"if",
"ih",
"!=",
"nil",
"{",
"post",
"(",
"ih",
"[",
":",
"]",
")",
"\n",
"post",
"(",
"peerID",
"[",
":",
"]",
")",
"\n",
"}",
"\n",
"var",
"b",
"[",
"68",
"]",
"byte",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"ReadFull",
"(",
"sock",
",",
"b",
"[",
":",
"68",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"nil",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"string",
"(",
"b",
"[",
":",
"20",
"]",
")",
"!=",
"Protocol",
"{",
"return",
"\n",
"}",
"\n",
"missinggo",
".",
"CopyExact",
"(",
"&",
"res",
".",
"PeerExtensionBits",
",",
"b",
"[",
"20",
":",
"28",
"]",
")",
"\n",
"missinggo",
".",
"CopyExact",
"(",
"&",
"res",
".",
"Hash",
",",
"b",
"[",
"28",
":",
"48",
"]",
")",
"\n",
"missinggo",
".",
"CopyExact",
"(",
"&",
"res",
".",
"PeerID",
",",
"b",
"[",
"48",
":",
"68",
"]",
")",
"\n",
"if",
"ih",
"==",
"nil",
"{",
"post",
"(",
"res",
".",
"Hash",
"[",
":",
"]",
")",
"\n",
"post",
"(",
"peerID",
"[",
":",
"]",
")",
"\n",
"}",
"\n",
"ok",
"=",
"true",
"\n",
"return",
"\n",
"}"
] |
// ih is nil if we expect the peer to declare the InfoHash, such as when the
// peer initiated the connection. Returns ok if the Handshake was successful,
// and err if there was an unexpected condition other than the peer simply
// abandoning the Handshake.
|
[
"ih",
"is",
"nil",
"if",
"we",
"expect",
"the",
"peer",
"to",
"declare",
"the",
"InfoHash",
"such",
"as",
"when",
"the",
"peer",
"initiated",
"the",
"connection",
".",
"Returns",
"ok",
"if",
"the",
"Handshake",
"was",
"successful",
"and",
"err",
"if",
"there",
"was",
"an",
"unexpected",
"condition",
"other",
"than",
"the",
"peer",
"simply",
"abandoning",
"the",
"Handshake",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/peer_protocol/handshake.go#L76-L137
|
train
|
anacrolix/torrent
|
bencode/decode.go
|
readUntil
|
func (d *Decoder) readUntil(sep byte) {
for {
b := d.readByte()
if b == sep {
return
}
d.buf.WriteByte(b)
}
}
|
go
|
func (d *Decoder) readUntil(sep byte) {
for {
b := d.readByte()
if b == sep {
return
}
d.buf.WriteByte(b)
}
}
|
[
"func",
"(",
"d",
"*",
"Decoder",
")",
"readUntil",
"(",
"sep",
"byte",
")",
"{",
"for",
"{",
"b",
":=",
"d",
".",
"readByte",
"(",
")",
"\n",
"if",
"b",
"==",
"sep",
"{",
"return",
"\n",
"}",
"\n",
"d",
".",
"buf",
".",
"WriteByte",
"(",
"b",
")",
"\n",
"}",
"\n",
"}"
] |
// reads data writing it to 'd.buf' until 'sep' byte is encountered, 'sep' byte
// is consumed, but not included into the 'd.buf'
|
[
"reads",
"data",
"writing",
"it",
"to",
"d",
".",
"buf",
"until",
"sep",
"byte",
"is",
"encountered",
"sep",
"byte",
"is",
"consumed",
"but",
"not",
"included",
"into",
"the",
"d",
".",
"buf"
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/decode.go#L78-L86
|
train
|
anacrolix/torrent
|
bencode/decode.go
|
parseInt
|
func (d *Decoder) parseInt(v reflect.Value) {
start := d.Offset - 1
d.readUntil('e')
if d.buf.Len() == 0 {
panic(&SyntaxError{
Offset: start,
What: errors.New("empty integer value"),
})
}
s := bytesAsString(d.buf.Bytes())
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n, err := strconv.ParseInt(s, 10, 64)
checkForIntParseError(err, start)
if v.OverflowInt(n) {
panic(&UnmarshalTypeError{
Value: "integer " + s,
Type: v.Type(),
})
}
v.SetInt(n)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n, err := strconv.ParseUint(s, 10, 64)
checkForIntParseError(err, start)
if v.OverflowUint(n) {
panic(&UnmarshalTypeError{
Value: "integer " + s,
Type: v.Type(),
})
}
v.SetUint(n)
case reflect.Bool:
v.SetBool(s != "0")
default:
panic(&UnmarshalTypeError{
Value: "integer " + s,
Type: v.Type(),
})
}
d.buf.Reset()
}
|
go
|
func (d *Decoder) parseInt(v reflect.Value) {
start := d.Offset - 1
d.readUntil('e')
if d.buf.Len() == 0 {
panic(&SyntaxError{
Offset: start,
What: errors.New("empty integer value"),
})
}
s := bytesAsString(d.buf.Bytes())
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n, err := strconv.ParseInt(s, 10, 64)
checkForIntParseError(err, start)
if v.OverflowInt(n) {
panic(&UnmarshalTypeError{
Value: "integer " + s,
Type: v.Type(),
})
}
v.SetInt(n)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n, err := strconv.ParseUint(s, 10, 64)
checkForIntParseError(err, start)
if v.OverflowUint(n) {
panic(&UnmarshalTypeError{
Value: "integer " + s,
Type: v.Type(),
})
}
v.SetUint(n)
case reflect.Bool:
v.SetBool(s != "0")
default:
panic(&UnmarshalTypeError{
Value: "integer " + s,
Type: v.Type(),
})
}
d.buf.Reset()
}
|
[
"func",
"(",
"d",
"*",
"Decoder",
")",
"parseInt",
"(",
"v",
"reflect",
".",
"Value",
")",
"{",
"start",
":=",
"d",
".",
"Offset",
"-",
"1",
"\n",
"d",
".",
"readUntil",
"(",
"'e'",
")",
"\n",
"if",
"d",
".",
"buf",
".",
"Len",
"(",
")",
"==",
"0",
"{",
"panic",
"(",
"&",
"SyntaxError",
"{",
"Offset",
":",
"start",
",",
"What",
":",
"errors",
".",
"New",
"(",
"\"empty integer value\"",
")",
",",
"}",
")",
"\n",
"}",
"\n",
"s",
":=",
"bytesAsString",
"(",
"d",
".",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n",
"switch",
"v",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Int",
",",
"reflect",
".",
"Int8",
",",
"reflect",
".",
"Int16",
",",
"reflect",
".",
"Int32",
",",
"reflect",
".",
"Int64",
":",
"n",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"s",
",",
"10",
",",
"64",
")",
"\n",
"checkForIntParseError",
"(",
"err",
",",
"start",
")",
"\n",
"if",
"v",
".",
"OverflowInt",
"(",
"n",
")",
"{",
"panic",
"(",
"&",
"UnmarshalTypeError",
"{",
"Value",
":",
"\"integer \"",
"+",
"s",
",",
"Type",
":",
"v",
".",
"Type",
"(",
")",
",",
"}",
")",
"\n",
"}",
"\n",
"v",
".",
"SetInt",
"(",
"n",
")",
"\n",
"case",
"reflect",
".",
"Uint",
",",
"reflect",
".",
"Uint8",
",",
"reflect",
".",
"Uint16",
",",
"reflect",
".",
"Uint32",
",",
"reflect",
".",
"Uint64",
":",
"n",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"s",
",",
"10",
",",
"64",
")",
"\n",
"checkForIntParseError",
"(",
"err",
",",
"start",
")",
"\n",
"if",
"v",
".",
"OverflowUint",
"(",
"n",
")",
"{",
"panic",
"(",
"&",
"UnmarshalTypeError",
"{",
"Value",
":",
"\"integer \"",
"+",
"s",
",",
"Type",
":",
"v",
".",
"Type",
"(",
")",
",",
"}",
")",
"\n",
"}",
"\n",
"v",
".",
"SetUint",
"(",
"n",
")",
"\n",
"case",
"reflect",
".",
"Bool",
":",
"v",
".",
"SetBool",
"(",
"s",
"!=",
"\"0\"",
")",
"\n",
"default",
":",
"panic",
"(",
"&",
"UnmarshalTypeError",
"{",
"Value",
":",
"\"integer \"",
"+",
"s",
",",
"Type",
":",
"v",
".",
"Type",
"(",
")",
",",
"}",
")",
"\n",
"}",
"\n",
"d",
".",
"buf",
".",
"Reset",
"(",
")",
"\n",
"}"
] |
// called when 'i' was consumed
|
[
"called",
"when",
"i",
"was",
"consumed"
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/decode.go#L105-L149
|
train
|
anacrolix/torrent
|
bencode/decode.go
|
getDictField
|
func getDictField(dict reflect.Value, key string) dictField {
// get valuev as a map value or as a struct field
switch dict.Kind() {
case reflect.Map:
value := reflect.New(dict.Type().Elem()).Elem()
return dictField{
Value: value,
Ok: true,
Set: func() {
if dict.IsNil() {
dict.Set(reflect.MakeMap(dict.Type()))
}
// Assigns the value into the map.
dict.SetMapIndex(reflect.ValueOf(key).Convert(dict.Type().Key()), value)
},
}
case reflect.Struct:
sf, ok := getStructFieldForKey(dict.Type(), key)
if !ok {
return dictField{}
}
if sf.r.PkgPath != "" {
panic(&UnmarshalFieldError{
Key: key,
Type: dict.Type(),
Field: sf.r,
})
}
return dictField{
Value: dict.FieldByIndex(sf.r.Index),
Ok: true,
Set: func() {},
IgnoreUnmarshalTypeError: sf.tag.IgnoreUnmarshalTypeError(),
}
default:
return dictField{}
}
}
|
go
|
func getDictField(dict reflect.Value, key string) dictField {
// get valuev as a map value or as a struct field
switch dict.Kind() {
case reflect.Map:
value := reflect.New(dict.Type().Elem()).Elem()
return dictField{
Value: value,
Ok: true,
Set: func() {
if dict.IsNil() {
dict.Set(reflect.MakeMap(dict.Type()))
}
// Assigns the value into the map.
dict.SetMapIndex(reflect.ValueOf(key).Convert(dict.Type().Key()), value)
},
}
case reflect.Struct:
sf, ok := getStructFieldForKey(dict.Type(), key)
if !ok {
return dictField{}
}
if sf.r.PkgPath != "" {
panic(&UnmarshalFieldError{
Key: key,
Type: dict.Type(),
Field: sf.r,
})
}
return dictField{
Value: dict.FieldByIndex(sf.r.Index),
Ok: true,
Set: func() {},
IgnoreUnmarshalTypeError: sf.tag.IgnoreUnmarshalTypeError(),
}
default:
return dictField{}
}
}
|
[
"func",
"getDictField",
"(",
"dict",
"reflect",
".",
"Value",
",",
"key",
"string",
")",
"dictField",
"{",
"switch",
"dict",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Map",
":",
"value",
":=",
"reflect",
".",
"New",
"(",
"dict",
".",
"Type",
"(",
")",
".",
"Elem",
"(",
")",
")",
".",
"Elem",
"(",
")",
"\n",
"return",
"dictField",
"{",
"Value",
":",
"value",
",",
"Ok",
":",
"true",
",",
"Set",
":",
"func",
"(",
")",
"{",
"if",
"dict",
".",
"IsNil",
"(",
")",
"{",
"dict",
".",
"Set",
"(",
"reflect",
".",
"MakeMap",
"(",
"dict",
".",
"Type",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"dict",
".",
"SetMapIndex",
"(",
"reflect",
".",
"ValueOf",
"(",
"key",
")",
".",
"Convert",
"(",
"dict",
".",
"Type",
"(",
")",
".",
"Key",
"(",
")",
")",
",",
"value",
")",
"\n",
"}",
",",
"}",
"\n",
"case",
"reflect",
".",
"Struct",
":",
"sf",
",",
"ok",
":=",
"getStructFieldForKey",
"(",
"dict",
".",
"Type",
"(",
")",
",",
"key",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"dictField",
"{",
"}",
"\n",
"}",
"\n",
"if",
"sf",
".",
"r",
".",
"PkgPath",
"!=",
"\"\"",
"{",
"panic",
"(",
"&",
"UnmarshalFieldError",
"{",
"Key",
":",
"key",
",",
"Type",
":",
"dict",
".",
"Type",
"(",
")",
",",
"Field",
":",
"sf",
".",
"r",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"dictField",
"{",
"Value",
":",
"dict",
".",
"FieldByIndex",
"(",
"sf",
".",
"r",
".",
"Index",
")",
",",
"Ok",
":",
"true",
",",
"Set",
":",
"func",
"(",
")",
"{",
"}",
",",
"IgnoreUnmarshalTypeError",
":",
"sf",
".",
"tag",
".",
"IgnoreUnmarshalTypeError",
"(",
")",
",",
"}",
"\n",
"default",
":",
"return",
"dictField",
"{",
"}",
"\n",
"}",
"\n",
"}"
] |
// Returns specifics for parsing a dict field value.
|
[
"Returns",
"specifics",
"for",
"parsing",
"a",
"dict",
"field",
"value",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/decode.go#L217-L254
|
train
|
anacrolix/torrent
|
bencode/decode.go
|
raiseUnknownValueType
|
func (d *Decoder) raiseUnknownValueType(b byte, offset int64) {
panic(&SyntaxError{
Offset: offset,
What: fmt.Errorf("unknown value type %+q", b),
})
}
|
go
|
func (d *Decoder) raiseUnknownValueType(b byte, offset int64) {
panic(&SyntaxError{
Offset: offset,
What: fmt.Errorf("unknown value type %+q", b),
})
}
|
[
"func",
"(",
"d",
"*",
"Decoder",
")",
"raiseUnknownValueType",
"(",
"b",
"byte",
",",
"offset",
"int64",
")",
"{",
"panic",
"(",
"&",
"SyntaxError",
"{",
"Offset",
":",
"offset",
",",
"What",
":",
"fmt",
".",
"Errorf",
"(",
"\"unknown value type %+q\"",
",",
"b",
")",
",",
"}",
")",
"\n",
"}"
] |
// An unknown bencode type character was encountered.
|
[
"An",
"unknown",
"bencode",
"type",
"character",
"was",
"encountered",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/decode.go#L520-L525
|
train
|
anacrolix/torrent
|
tracker_scraper.go
|
announce
|
func (me *trackerScraper) announce() (ret trackerAnnounceResult) {
defer func() {
ret.Completed = time.Now()
}()
ret.Interval = 5 * time.Minute
ip, err := me.getIp()
if err != nil {
ret.Err = fmt.Errorf("error getting ip: %s", err)
return
}
me.t.cl.lock()
req := me.t.announceRequest()
me.t.cl.unlock()
res, err := tracker.Announce{
HTTPProxy: me.t.cl.config.HTTPProxy,
UserAgent: me.t.cl.config.HTTPUserAgent,
TrackerUrl: me.trackerUrl(ip),
Request: req,
HostHeader: me.u.Host,
ServerName: me.u.Hostname(),
UdpNetwork: me.u.Scheme,
ClientIp4: krpc.NodeAddr{IP: me.t.cl.config.PublicIp4},
ClientIp6: krpc.NodeAddr{IP: me.t.cl.config.PublicIp6},
}.Do()
if err != nil {
ret.Err = fmt.Errorf("error announcing: %s", err)
return
}
me.t.AddPeers(Peers(nil).AppendFromTracker(res.Peers))
ret.NumPeers = len(res.Peers)
ret.Interval = time.Duration(res.Interval) * time.Second
return
}
|
go
|
func (me *trackerScraper) announce() (ret trackerAnnounceResult) {
defer func() {
ret.Completed = time.Now()
}()
ret.Interval = 5 * time.Minute
ip, err := me.getIp()
if err != nil {
ret.Err = fmt.Errorf("error getting ip: %s", err)
return
}
me.t.cl.lock()
req := me.t.announceRequest()
me.t.cl.unlock()
res, err := tracker.Announce{
HTTPProxy: me.t.cl.config.HTTPProxy,
UserAgent: me.t.cl.config.HTTPUserAgent,
TrackerUrl: me.trackerUrl(ip),
Request: req,
HostHeader: me.u.Host,
ServerName: me.u.Hostname(),
UdpNetwork: me.u.Scheme,
ClientIp4: krpc.NodeAddr{IP: me.t.cl.config.PublicIp4},
ClientIp6: krpc.NodeAddr{IP: me.t.cl.config.PublicIp6},
}.Do()
if err != nil {
ret.Err = fmt.Errorf("error announcing: %s", err)
return
}
me.t.AddPeers(Peers(nil).AppendFromTracker(res.Peers))
ret.NumPeers = len(res.Peers)
ret.Interval = time.Duration(res.Interval) * time.Second
return
}
|
[
"func",
"(",
"me",
"*",
"trackerScraper",
")",
"announce",
"(",
")",
"(",
"ret",
"trackerAnnounceResult",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"ret",
".",
"Completed",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"ret",
".",
"Interval",
"=",
"5",
"*",
"time",
".",
"Minute",
"\n",
"ip",
",",
"err",
":=",
"me",
".",
"getIp",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ret",
".",
"Err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"error getting ip: %s\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"me",
".",
"t",
".",
"cl",
".",
"lock",
"(",
")",
"\n",
"req",
":=",
"me",
".",
"t",
".",
"announceRequest",
"(",
")",
"\n",
"me",
".",
"t",
".",
"cl",
".",
"unlock",
"(",
")",
"\n",
"res",
",",
"err",
":=",
"tracker",
".",
"Announce",
"{",
"HTTPProxy",
":",
"me",
".",
"t",
".",
"cl",
".",
"config",
".",
"HTTPProxy",
",",
"UserAgent",
":",
"me",
".",
"t",
".",
"cl",
".",
"config",
".",
"HTTPUserAgent",
",",
"TrackerUrl",
":",
"me",
".",
"trackerUrl",
"(",
"ip",
")",
",",
"Request",
":",
"req",
",",
"HostHeader",
":",
"me",
".",
"u",
".",
"Host",
",",
"ServerName",
":",
"me",
".",
"u",
".",
"Hostname",
"(",
")",
",",
"UdpNetwork",
":",
"me",
".",
"u",
".",
"Scheme",
",",
"ClientIp4",
":",
"krpc",
".",
"NodeAddr",
"{",
"IP",
":",
"me",
".",
"t",
".",
"cl",
".",
"config",
".",
"PublicIp4",
"}",
",",
"ClientIp6",
":",
"krpc",
".",
"NodeAddr",
"{",
"IP",
":",
"me",
".",
"t",
".",
"cl",
".",
"config",
".",
"PublicIp6",
"}",
",",
"}",
".",
"Do",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ret",
".",
"Err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"error announcing: %s\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"me",
".",
"t",
".",
"AddPeers",
"(",
"Peers",
"(",
"nil",
")",
".",
"AppendFromTracker",
"(",
"res",
".",
"Peers",
")",
")",
"\n",
"ret",
".",
"NumPeers",
"=",
"len",
"(",
"res",
".",
"Peers",
")",
"\n",
"ret",
".",
"Interval",
"=",
"time",
".",
"Duration",
"(",
"res",
".",
"Interval",
")",
"*",
"time",
".",
"Second",
"\n",
"return",
"\n",
"}"
] |
// Return how long to wait before trying again. For most errors, we return 5
// minutes, a relatively quick turn around for DNS changes.
|
[
"Return",
"how",
"long",
"to",
"wait",
"before",
"trying",
"again",
".",
"For",
"most",
"errors",
"we",
"return",
"5",
"minutes",
"a",
"relatively",
"quick",
"turn",
"around",
"for",
"DNS",
"changes",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/tracker_scraper.go#L99-L131
|
train
|
anacrolix/torrent
|
iplist/cidr.go
|
IPNetLast
|
func IPNetLast(in *net.IPNet) (last net.IP) {
n := len(in.IP)
if n != len(in.Mask) {
panic("wat")
}
last = make(net.IP, n)
for i := 0; i < n; i++ {
last[i] = in.IP[i] | ^in.Mask[i]
}
return
}
|
go
|
func IPNetLast(in *net.IPNet) (last net.IP) {
n := len(in.IP)
if n != len(in.Mask) {
panic("wat")
}
last = make(net.IP, n)
for i := 0; i < n; i++ {
last[i] = in.IP[i] | ^in.Mask[i]
}
return
}
|
[
"func",
"IPNetLast",
"(",
"in",
"*",
"net",
".",
"IPNet",
")",
"(",
"last",
"net",
".",
"IP",
")",
"{",
"n",
":=",
"len",
"(",
"in",
".",
"IP",
")",
"\n",
"if",
"n",
"!=",
"len",
"(",
"in",
".",
"Mask",
")",
"{",
"panic",
"(",
"\"wat\"",
")",
"\n",
"}",
"\n",
"last",
"=",
"make",
"(",
"net",
".",
"IP",
",",
"n",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
"{",
"last",
"[",
"i",
"]",
"=",
"in",
".",
"IP",
"[",
"i",
"]",
"|",
"^",
"in",
".",
"Mask",
"[",
"i",
"]",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Returns the last, inclusive IP in a net.IPNet.
|
[
"Returns",
"the",
"last",
"inclusive",
"IP",
"in",
"a",
"net",
".",
"IPNet",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/iplist/cidr.go#L31-L41
|
train
|
anacrolix/torrent
|
bencode/encode.go
|
reflectMarshaler
|
func (e *Encoder) reflectMarshaler(v reflect.Value) bool {
if !v.Type().Implements(marshalerType) {
if v.Kind() != reflect.Ptr && v.CanAddr() && v.Addr().Type().Implements(marshalerType) {
v = v.Addr()
} else {
return false
}
}
m := v.Interface().(Marshaler)
data, err := m.MarshalBencode()
if err != nil {
panic(&MarshalerError{v.Type(), err})
}
e.write(data)
return true
}
|
go
|
func (e *Encoder) reflectMarshaler(v reflect.Value) bool {
if !v.Type().Implements(marshalerType) {
if v.Kind() != reflect.Ptr && v.CanAddr() && v.Addr().Type().Implements(marshalerType) {
v = v.Addr()
} else {
return false
}
}
m := v.Interface().(Marshaler)
data, err := m.MarshalBencode()
if err != nil {
panic(&MarshalerError{v.Type(), err})
}
e.write(data)
return true
}
|
[
"func",
"(",
"e",
"*",
"Encoder",
")",
"reflectMarshaler",
"(",
"v",
"reflect",
".",
"Value",
")",
"bool",
"{",
"if",
"!",
"v",
".",
"Type",
"(",
")",
".",
"Implements",
"(",
"marshalerType",
")",
"{",
"if",
"v",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"&&",
"v",
".",
"CanAddr",
"(",
")",
"&&",
"v",
".",
"Addr",
"(",
")",
".",
"Type",
"(",
")",
".",
"Implements",
"(",
"marshalerType",
")",
"{",
"v",
"=",
"v",
".",
"Addr",
"(",
")",
"\n",
"}",
"else",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"m",
":=",
"v",
".",
"Interface",
"(",
")",
".",
"(",
"Marshaler",
")",
"\n",
"data",
",",
"err",
":=",
"m",
".",
"MarshalBencode",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"&",
"MarshalerError",
"{",
"v",
".",
"Type",
"(",
")",
",",
"err",
"}",
")",
"\n",
"}",
"\n",
"e",
".",
"write",
"(",
"data",
")",
"\n",
"return",
"true",
"\n",
"}"
] |
// Returns true if the value implements Marshaler interface and marshaling was
// done successfully.
|
[
"Returns",
"true",
"if",
"the",
"value",
"implements",
"Marshaler",
"interface",
"and",
"marshaling",
"was",
"done",
"successfully",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/encode.go#L82-L97
|
train
|
anacrolix/torrent
|
file.go
|
DisplayPath
|
func (f *File) DisplayPath() string {
fip := f.FileInfo().Path
if len(fip) == 0 {
return f.t.info.Name
}
return strings.Join(fip, "/")
}
|
go
|
func (f *File) DisplayPath() string {
fip := f.FileInfo().Path
if len(fip) == 0 {
return f.t.info.Name
}
return strings.Join(fip, "/")
}
|
[
"func",
"(",
"f",
"*",
"File",
")",
"DisplayPath",
"(",
")",
"string",
"{",
"fip",
":=",
"f",
".",
"FileInfo",
"(",
")",
".",
"Path",
"\n",
"if",
"len",
"(",
"fip",
")",
"==",
"0",
"{",
"return",
"f",
".",
"t",
".",
"info",
".",
"Name",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Join",
"(",
"fip",
",",
"\"/\"",
")",
"\n",
"}"
] |
// The relative file path for a multi-file torrent, and the torrent name for a
// single-file torrent.
|
[
"The",
"relative",
"file",
"path",
"for",
"a",
"multi",
"-",
"file",
"torrent",
"and",
"the",
"torrent",
"name",
"for",
"a",
"single",
"-",
"file",
"torrent",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/file.go#L45-L52
|
train
|
anacrolix/torrent
|
file.go
|
State
|
func (f *File) State() (ret []FilePieceState) {
f.t.cl.rLock()
defer f.t.cl.rUnlock()
pieceSize := int64(f.t.usualPieceSize())
off := f.offset % pieceSize
remaining := f.length
for i := pieceIndex(f.offset / pieceSize); ; i++ {
if remaining == 0 {
break
}
len1 := pieceSize - off
if len1 > remaining {
len1 = remaining
}
ps := f.t.pieceState(i)
ret = append(ret, FilePieceState{len1, ps})
off = 0
remaining -= len1
}
return
}
|
go
|
func (f *File) State() (ret []FilePieceState) {
f.t.cl.rLock()
defer f.t.cl.rUnlock()
pieceSize := int64(f.t.usualPieceSize())
off := f.offset % pieceSize
remaining := f.length
for i := pieceIndex(f.offset / pieceSize); ; i++ {
if remaining == 0 {
break
}
len1 := pieceSize - off
if len1 > remaining {
len1 = remaining
}
ps := f.t.pieceState(i)
ret = append(ret, FilePieceState{len1, ps})
off = 0
remaining -= len1
}
return
}
|
[
"func",
"(",
"f",
"*",
"File",
")",
"State",
"(",
")",
"(",
"ret",
"[",
"]",
"FilePieceState",
")",
"{",
"f",
".",
"t",
".",
"cl",
".",
"rLock",
"(",
")",
"\n",
"defer",
"f",
".",
"t",
".",
"cl",
".",
"rUnlock",
"(",
")",
"\n",
"pieceSize",
":=",
"int64",
"(",
"f",
".",
"t",
".",
"usualPieceSize",
"(",
")",
")",
"\n",
"off",
":=",
"f",
".",
"offset",
"%",
"pieceSize",
"\n",
"remaining",
":=",
"f",
".",
"length",
"\n",
"for",
"i",
":=",
"pieceIndex",
"(",
"f",
".",
"offset",
"/",
"pieceSize",
")",
";",
";",
"i",
"++",
"{",
"if",
"remaining",
"==",
"0",
"{",
"break",
"\n",
"}",
"\n",
"len1",
":=",
"pieceSize",
"-",
"off",
"\n",
"if",
"len1",
">",
"remaining",
"{",
"len1",
"=",
"remaining",
"\n",
"}",
"\n",
"ps",
":=",
"f",
".",
"t",
".",
"pieceState",
"(",
"i",
")",
"\n",
"ret",
"=",
"append",
"(",
"ret",
",",
"FilePieceState",
"{",
"len1",
",",
"ps",
"}",
")",
"\n",
"off",
"=",
"0",
"\n",
"remaining",
"-=",
"len1",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Returns the state of pieces in this file.
|
[
"Returns",
"the",
"state",
"of",
"pieces",
"in",
"this",
"file",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/file.go#L61-L81
|
train
|
anacrolix/torrent
|
file.go
|
SetPriority
|
func (f *File) SetPriority(prio piecePriority) {
f.t.cl.lock()
defer f.t.cl.unlock()
if prio == f.prio {
return
}
f.prio = prio
f.t.updatePiecePriorities(f.firstPieceIndex(), f.endPieceIndex())
}
|
go
|
func (f *File) SetPriority(prio piecePriority) {
f.t.cl.lock()
defer f.t.cl.unlock()
if prio == f.prio {
return
}
f.prio = prio
f.t.updatePiecePriorities(f.firstPieceIndex(), f.endPieceIndex())
}
|
[
"func",
"(",
"f",
"*",
"File",
")",
"SetPriority",
"(",
"prio",
"piecePriority",
")",
"{",
"f",
".",
"t",
".",
"cl",
".",
"lock",
"(",
")",
"\n",
"defer",
"f",
".",
"t",
".",
"cl",
".",
"unlock",
"(",
")",
"\n",
"if",
"prio",
"==",
"f",
".",
"prio",
"{",
"return",
"\n",
"}",
"\n",
"f",
".",
"prio",
"=",
"prio",
"\n",
"f",
".",
"t",
".",
"updatePiecePriorities",
"(",
"f",
".",
"firstPieceIndex",
"(",
")",
",",
"f",
".",
"endPieceIndex",
"(",
")",
")",
"\n",
"}"
] |
// Sets the minimum priority for pieces in the File.
|
[
"Sets",
"the",
"minimum",
"priority",
"for",
"pieces",
"in",
"the",
"File",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/file.go#L112-L120
|
train
|
anacrolix/torrent
|
file.go
|
Priority
|
func (f *File) Priority() piecePriority {
f.t.cl.lock()
defer f.t.cl.unlock()
return f.prio
}
|
go
|
func (f *File) Priority() piecePriority {
f.t.cl.lock()
defer f.t.cl.unlock()
return f.prio
}
|
[
"func",
"(",
"f",
"*",
"File",
")",
"Priority",
"(",
")",
"piecePriority",
"{",
"f",
".",
"t",
".",
"cl",
".",
"lock",
"(",
")",
"\n",
"defer",
"f",
".",
"t",
".",
"cl",
".",
"unlock",
"(",
")",
"\n",
"return",
"f",
".",
"prio",
"\n",
"}"
] |
// Returns the priority per File.SetPriority.
|
[
"Returns",
"the",
"priority",
"per",
"File",
".",
"SetPriority",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/file.go#L123-L127
|
train
|
anacrolix/torrent
|
client.go
|
WriteStatus
|
func (cl *Client) WriteStatus(_w io.Writer) {
cl.rLock()
defer cl.rUnlock()
w := bufio.NewWriter(_w)
defer w.Flush()
fmt.Fprintf(w, "Listen port: %d\n", cl.LocalPort())
fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
fmt.Fprintf(w, "Announce key: %x\n", cl.announceKey())
fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
cl.eachDhtServer(func(s *dht.Server) {
fmt.Fprintf(w, "%s DHT server at %s:\n", s.Addr().Network(), s.Addr().String())
writeDhtServerStatus(w, s)
})
spew.Fdump(w, cl.stats)
fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrentsAsSlice()))
fmt.Fprintln(w)
for _, t := range slices.Sort(cl.torrentsAsSlice(), func(l, r *Torrent) bool {
return l.InfoHash().AsString() < r.InfoHash().AsString()
}).([]*Torrent) {
if t.name() == "" {
fmt.Fprint(w, "<unknown name>")
} else {
fmt.Fprint(w, t.name())
}
fmt.Fprint(w, "\n")
if t.info != nil {
fmt.Fprintf(w, "%f%% of %d bytes (%s)", 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())), t.length, humanize.Bytes(uint64(t.info.TotalLength())))
} else {
w.WriteString("<missing metainfo>")
}
fmt.Fprint(w, "\n")
t.writeStatus(w)
fmt.Fprintln(w)
}
}
|
go
|
func (cl *Client) WriteStatus(_w io.Writer) {
cl.rLock()
defer cl.rUnlock()
w := bufio.NewWriter(_w)
defer w.Flush()
fmt.Fprintf(w, "Listen port: %d\n", cl.LocalPort())
fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
fmt.Fprintf(w, "Announce key: %x\n", cl.announceKey())
fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
cl.eachDhtServer(func(s *dht.Server) {
fmt.Fprintf(w, "%s DHT server at %s:\n", s.Addr().Network(), s.Addr().String())
writeDhtServerStatus(w, s)
})
spew.Fdump(w, cl.stats)
fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrentsAsSlice()))
fmt.Fprintln(w)
for _, t := range slices.Sort(cl.torrentsAsSlice(), func(l, r *Torrent) bool {
return l.InfoHash().AsString() < r.InfoHash().AsString()
}).([]*Torrent) {
if t.name() == "" {
fmt.Fprint(w, "<unknown name>")
} else {
fmt.Fprint(w, t.name())
}
fmt.Fprint(w, "\n")
if t.info != nil {
fmt.Fprintf(w, "%f%% of %d bytes (%s)", 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())), t.length, humanize.Bytes(uint64(t.info.TotalLength())))
} else {
w.WriteString("<missing metainfo>")
}
fmt.Fprint(w, "\n")
t.writeStatus(w)
fmt.Fprintln(w)
}
}
|
[
"func",
"(",
"cl",
"*",
"Client",
")",
"WriteStatus",
"(",
"_w",
"io",
".",
"Writer",
")",
"{",
"cl",
".",
"rLock",
"(",
")",
"\n",
"defer",
"cl",
".",
"rUnlock",
"(",
")",
"\n",
"w",
":=",
"bufio",
".",
"NewWriter",
"(",
"_w",
")",
"\n",
"defer",
"w",
".",
"Flush",
"(",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"Listen port: %d\\n\"",
",",
"\\n",
")",
"\n",
"cl",
".",
"LocalPort",
"(",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"Peer ID: %+q\\n\"",
",",
"\\n",
")",
"\n",
"cl",
".",
"PeerID",
"(",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"Announce key: %x\\n\"",
",",
"\\n",
")",
"\n",
"cl",
".",
"announceKey",
"(",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"Banned IPs: %d\\n\"",
",",
"\\n",
")",
"\n",
"len",
"(",
"cl",
".",
"badPeerIPsLocked",
"(",
")",
")",
"\n",
"cl",
".",
"eachDhtServer",
"(",
"func",
"(",
"s",
"*",
"dht",
".",
"Server",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"%s DHT server at %s:\\n\"",
",",
"\\n",
",",
"s",
".",
"Addr",
"(",
")",
".",
"Network",
"(",
")",
")",
"\n",
"s",
".",
"Addr",
"(",
")",
".",
"String",
"(",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// Writes out a human readable status of the client, such as for writing to a
// HTTP status page.
|
[
"Writes",
"out",
"a",
"human",
"readable",
"status",
"of",
"the",
"client",
"such",
"as",
"for",
"writing",
"to",
"a",
"HTTP",
"status",
"page",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L118-L152
|
train
|
anacrolix/torrent
|
client.go
|
Close
|
func (cl *Client) Close() {
cl.lock()
defer cl.unlock()
cl.closed.Set()
cl.eachDhtServer(func(s *dht.Server) { s.Close() })
cl.closeSockets()
for _, t := range cl.torrents {
t.close()
}
for _, f := range cl.onClose {
f()
}
cl.event.Broadcast()
}
|
go
|
func (cl *Client) Close() {
cl.lock()
defer cl.unlock()
cl.closed.Set()
cl.eachDhtServer(func(s *dht.Server) { s.Close() })
cl.closeSockets()
for _, t := range cl.torrents {
t.close()
}
for _, f := range cl.onClose {
f()
}
cl.event.Broadcast()
}
|
[
"func",
"(",
"cl",
"*",
"Client",
")",
"Close",
"(",
")",
"{",
"cl",
".",
"lock",
"(",
")",
"\n",
"defer",
"cl",
".",
"unlock",
"(",
")",
"\n",
"cl",
".",
"closed",
".",
"Set",
"(",
")",
"\n",
"cl",
".",
"eachDhtServer",
"(",
"func",
"(",
"s",
"*",
"dht",
".",
"Server",
")",
"{",
"s",
".",
"Close",
"(",
")",
"}",
")",
"\n",
"cl",
".",
"closeSockets",
"(",
")",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"cl",
".",
"torrents",
"{",
"t",
".",
"close",
"(",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"cl",
".",
"onClose",
"{",
"f",
"(",
")",
"\n",
"}",
"\n",
"cl",
".",
"event",
".",
"Broadcast",
"(",
")",
"\n",
"}"
] |
// Stops the client. All connections to peers are closed and all activity will
// come to a halt.
|
[
"Stops",
"the",
"client",
".",
"All",
"connections",
"to",
"peers",
"are",
"closed",
"and",
"all",
"activity",
"will",
"come",
"to",
"a",
"halt",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L352-L365
|
train
|
anacrolix/torrent
|
client.go
|
Torrent
|
func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
cl.lock()
defer cl.unlock()
t, ok = cl.torrents[ih]
return
}
|
go
|
func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
cl.lock()
defer cl.unlock()
t, ok = cl.torrents[ih]
return
}
|
[
"func",
"(",
"cl",
"*",
"Client",
")",
"Torrent",
"(",
"ih",
"metainfo",
".",
"Hash",
")",
"(",
"t",
"*",
"Torrent",
",",
"ok",
"bool",
")",
"{",
"cl",
".",
"lock",
"(",
")",
"\n",
"defer",
"cl",
".",
"unlock",
"(",
")",
"\n",
"t",
",",
"ok",
"=",
"cl",
".",
"torrents",
"[",
"ih",
"]",
"\n",
"return",
"\n",
"}"
] |
// Returns a handle to the given torrent, if it's present in the client.
|
[
"Returns",
"a",
"handle",
"to",
"the",
"given",
"torrent",
"if",
"it",
"s",
"present",
"in",
"the",
"client",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L465-L470
|
train
|
anacrolix/torrent
|
client.go
|
dopplegangerAddr
|
func (cl *Client) dopplegangerAddr(addr string) bool {
_, ok := cl.dopplegangerAddrs[addr]
return ok
}
|
go
|
func (cl *Client) dopplegangerAddr(addr string) bool {
_, ok := cl.dopplegangerAddrs[addr]
return ok
}
|
[
"func",
"(",
"cl",
"*",
"Client",
")",
"dopplegangerAddr",
"(",
"addr",
"string",
")",
"bool",
"{",
"_",
",",
"ok",
":=",
"cl",
".",
"dopplegangerAddrs",
"[",
"addr",
"]",
"\n",
"return",
"ok",
"\n",
"}"
] |
// Returns whether an address is known to connect to a client with our own ID.
|
[
"Returns",
"whether",
"an",
"address",
"is",
"known",
"to",
"connect",
"to",
"a",
"client",
"with",
"our",
"own",
"ID",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L498-L501
|
train
|
anacrolix/torrent
|
client.go
|
dialFirst
|
func (cl *Client) dialFirst(ctx context.Context, addr string) dialResult {
ctx, cancel := context.WithCancel(ctx)
// As soon as we return one connection, cancel the others.
defer cancel()
left := 0
resCh := make(chan dialResult, left)
func() {
cl.lock()
defer cl.unlock()
cl.eachListener(func(s socket) bool {
network := s.Addr().Network()
if peerNetworkEnabled(parseNetworkString(network), cl.config) {
left++
go func() {
cte := cl.config.ConnTracker.Wait(
ctx,
conntrack.Entry{network, s.Addr().String(), addr},
"dial torrent client",
0,
)
// Try to avoid committing to a dial if the context is complete as it's
// difficult to determine which dial errors allow us to forget the connection
// tracking entry handle.
if ctx.Err() != nil {
if cte != nil {
cte.Forget()
}
resCh <- dialResult{}
return
}
c, err := s.dial(ctx, addr)
// This is a bit optimistic, but it looks non-trivial to thread
// this through the proxy code. Set it now in case we close the
// connection forthwith.
if tc, ok := c.(*net.TCPConn); ok {
tc.SetLinger(0)
}
countDialResult(err)
dr := dialResult{c, network}
if c == nil {
if err != nil && forgettableDialError(err) {
cte.Forget()
} else {
cte.Done()
}
} else {
dr.Conn = closeWrapper{c, func() error {
err := c.Close()
cte.Done()
return err
}}
}
resCh <- dr
}()
}
return true
})
}()
var res dialResult
// Wait for a successful connection.
func() {
defer perf.ScopeTimer()()
for ; left > 0 && res.Conn == nil; left-- {
res = <-resCh
}
}()
// There are still incompleted dials.
go func() {
for ; left > 0; left-- {
conn := (<-resCh).Conn
if conn != nil {
conn.Close()
}
}
}()
if res.Conn != nil {
go torrent.Add(fmt.Sprintf("network dialed first: %s", res.Conn.RemoteAddr().Network()), 1)
}
return res
}
|
go
|
func (cl *Client) dialFirst(ctx context.Context, addr string) dialResult {
ctx, cancel := context.WithCancel(ctx)
// As soon as we return one connection, cancel the others.
defer cancel()
left := 0
resCh := make(chan dialResult, left)
func() {
cl.lock()
defer cl.unlock()
cl.eachListener(func(s socket) bool {
network := s.Addr().Network()
if peerNetworkEnabled(parseNetworkString(network), cl.config) {
left++
go func() {
cte := cl.config.ConnTracker.Wait(
ctx,
conntrack.Entry{network, s.Addr().String(), addr},
"dial torrent client",
0,
)
// Try to avoid committing to a dial if the context is complete as it's
// difficult to determine which dial errors allow us to forget the connection
// tracking entry handle.
if ctx.Err() != nil {
if cte != nil {
cte.Forget()
}
resCh <- dialResult{}
return
}
c, err := s.dial(ctx, addr)
// This is a bit optimistic, but it looks non-trivial to thread
// this through the proxy code. Set it now in case we close the
// connection forthwith.
if tc, ok := c.(*net.TCPConn); ok {
tc.SetLinger(0)
}
countDialResult(err)
dr := dialResult{c, network}
if c == nil {
if err != nil && forgettableDialError(err) {
cte.Forget()
} else {
cte.Done()
}
} else {
dr.Conn = closeWrapper{c, func() error {
err := c.Close()
cte.Done()
return err
}}
}
resCh <- dr
}()
}
return true
})
}()
var res dialResult
// Wait for a successful connection.
func() {
defer perf.ScopeTimer()()
for ; left > 0 && res.Conn == nil; left-- {
res = <-resCh
}
}()
// There are still incompleted dials.
go func() {
for ; left > 0; left-- {
conn := (<-resCh).Conn
if conn != nil {
conn.Close()
}
}
}()
if res.Conn != nil {
go torrent.Add(fmt.Sprintf("network dialed first: %s", res.Conn.RemoteAddr().Network()), 1)
}
return res
}
|
[
"func",
"(",
"cl",
"*",
"Client",
")",
"dialFirst",
"(",
"ctx",
"context",
".",
"Context",
",",
"addr",
"string",
")",
"dialResult",
"{",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithCancel",
"(",
"ctx",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"left",
":=",
"0",
"\n",
"resCh",
":=",
"make",
"(",
"chan",
"dialResult",
",",
"left",
")",
"\n",
"func",
"(",
")",
"{",
"cl",
".",
"lock",
"(",
")",
"\n",
"defer",
"cl",
".",
"unlock",
"(",
")",
"\n",
"cl",
".",
"eachListener",
"(",
"func",
"(",
"s",
"socket",
")",
"bool",
"{",
"network",
":=",
"s",
".",
"Addr",
"(",
")",
".",
"Network",
"(",
")",
"\n",
"if",
"peerNetworkEnabled",
"(",
"parseNetworkString",
"(",
"network",
")",
",",
"cl",
".",
"config",
")",
"{",
"left",
"++",
"\n",
"go",
"func",
"(",
")",
"{",
"cte",
":=",
"cl",
".",
"config",
".",
"ConnTracker",
".",
"Wait",
"(",
"ctx",
",",
"conntrack",
".",
"Entry",
"{",
"network",
",",
"s",
".",
"Addr",
"(",
")",
".",
"String",
"(",
")",
",",
"addr",
"}",
",",
"\"dial torrent client\"",
",",
"0",
",",
")",
"\n",
"if",
"ctx",
".",
"Err",
"(",
")",
"!=",
"nil",
"{",
"if",
"cte",
"!=",
"nil",
"{",
"cte",
".",
"Forget",
"(",
")",
"\n",
"}",
"\n",
"resCh",
"<-",
"dialResult",
"{",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"c",
",",
"err",
":=",
"s",
".",
"dial",
"(",
"ctx",
",",
"addr",
")",
"\n",
"if",
"tc",
",",
"ok",
":=",
"c",
".",
"(",
"*",
"net",
".",
"TCPConn",
")",
";",
"ok",
"{",
"tc",
".",
"SetLinger",
"(",
"0",
")",
"\n",
"}",
"\n",
"countDialResult",
"(",
"err",
")",
"\n",
"dr",
":=",
"dialResult",
"{",
"c",
",",
"network",
"}",
"\n",
"if",
"c",
"==",
"nil",
"{",
"if",
"err",
"!=",
"nil",
"&&",
"forgettableDialError",
"(",
"err",
")",
"{",
"cte",
".",
"Forget",
"(",
")",
"\n",
"}",
"else",
"{",
"cte",
".",
"Done",
"(",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"dr",
".",
"Conn",
"=",
"closeWrapper",
"{",
"c",
",",
"func",
"(",
")",
"error",
"{",
"err",
":=",
"c",
".",
"Close",
"(",
")",
"\n",
"cte",
".",
"Done",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"}",
"\n",
"}",
"\n",
"resCh",
"<-",
"dr",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"}",
"(",
")",
"\n",
"var",
"res",
"dialResult",
"\n",
"func",
"(",
")",
"{",
"defer",
"perf",
".",
"ScopeTimer",
"(",
")",
"(",
")",
"\n",
"for",
";",
"left",
">",
"0",
"&&",
"res",
".",
"Conn",
"==",
"nil",
";",
"left",
"--",
"{",
"res",
"=",
"<-",
"resCh",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"for",
";",
"left",
">",
"0",
";",
"left",
"--",
"{",
"conn",
":=",
"(",
"<-",
"resCh",
")",
".",
"Conn",
"\n",
"if",
"conn",
"!=",
"nil",
"{",
"conn",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"if",
"res",
".",
"Conn",
"!=",
"nil",
"{",
"go",
"torrent",
".",
"Add",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"network dialed first: %s\"",
",",
"res",
".",
"Conn",
".",
"RemoteAddr",
"(",
")",
".",
"Network",
"(",
")",
")",
",",
"1",
")",
"\n",
"}",
"\n",
"return",
"res",
"\n",
"}"
] |
// Returns a connection over UTP or TCP, whichever is first to connect.
|
[
"Returns",
"a",
"connection",
"over",
"UTP",
"or",
"TCP",
"whichever",
"is",
"first",
"to",
"connect",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L504-L583
|
train
|
anacrolix/torrent
|
client.go
|
outgoingConnection
|
func (cl *Client) outgoingConnection(t *Torrent, addr IpPort, ps peerSource) {
cl.dialRateLimiter.Wait(context.Background())
c, err := cl.establishOutgoingConn(t, addr)
cl.lock()
defer cl.unlock()
// Don't release lock between here and addConnection, unless it's for
// failure.
cl.noLongerHalfOpen(t, addr.String())
if err != nil {
if cl.config.Debug {
cl.logger.Printf("error establishing outgoing connection: %s", err)
}
return
}
if c == nil {
return
}
defer c.Close()
c.Discovery = ps
cl.runHandshookConn(c, t)
}
|
go
|
func (cl *Client) outgoingConnection(t *Torrent, addr IpPort, ps peerSource) {
cl.dialRateLimiter.Wait(context.Background())
c, err := cl.establishOutgoingConn(t, addr)
cl.lock()
defer cl.unlock()
// Don't release lock between here and addConnection, unless it's for
// failure.
cl.noLongerHalfOpen(t, addr.String())
if err != nil {
if cl.config.Debug {
cl.logger.Printf("error establishing outgoing connection: %s", err)
}
return
}
if c == nil {
return
}
defer c.Close()
c.Discovery = ps
cl.runHandshookConn(c, t)
}
|
[
"func",
"(",
"cl",
"*",
"Client",
")",
"outgoingConnection",
"(",
"t",
"*",
"Torrent",
",",
"addr",
"IpPort",
",",
"ps",
"peerSource",
")",
"{",
"cl",
".",
"dialRateLimiter",
".",
"Wait",
"(",
"context",
".",
"Background",
"(",
")",
")",
"\n",
"c",
",",
"err",
":=",
"cl",
".",
"establishOutgoingConn",
"(",
"t",
",",
"addr",
")",
"\n",
"cl",
".",
"lock",
"(",
")",
"\n",
"defer",
"cl",
".",
"unlock",
"(",
")",
"\n",
"cl",
".",
"noLongerHalfOpen",
"(",
"t",
",",
"addr",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"cl",
".",
"config",
".",
"Debug",
"{",
"cl",
".",
"logger",
".",
"Printf",
"(",
"\"error establishing outgoing connection: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"c",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n",
"c",
".",
"Discovery",
"=",
"ps",
"\n",
"cl",
".",
"runHandshookConn",
"(",
"c",
",",
"t",
")",
"\n",
"}"
] |
// Called to dial out and run a connection. The addr we're given is already
// considered half-open.
|
[
"Called",
"to",
"dial",
"out",
"and",
"run",
"a",
"connection",
".",
"The",
"addr",
"we",
"re",
"given",
"is",
"already",
"considered",
"half",
"-",
"open",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L672-L692
|
train
|
anacrolix/torrent
|
client.go
|
forSkeys
|
func (cl *Client) forSkeys(f func([]byte) bool) {
cl.lock()
defer cl.unlock()
for ih := range cl.torrents {
if !f(ih[:]) {
break
}
}
}
|
go
|
func (cl *Client) forSkeys(f func([]byte) bool) {
cl.lock()
defer cl.unlock()
for ih := range cl.torrents {
if !f(ih[:]) {
break
}
}
}
|
[
"func",
"(",
"cl",
"*",
"Client",
")",
"forSkeys",
"(",
"f",
"func",
"(",
"[",
"]",
"byte",
")",
"bool",
")",
"{",
"cl",
".",
"lock",
"(",
")",
"\n",
"defer",
"cl",
".",
"unlock",
"(",
")",
"\n",
"for",
"ih",
":=",
"range",
"cl",
".",
"torrents",
"{",
"if",
"!",
"f",
"(",
"ih",
"[",
":",
"]",
")",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// Calls f with any secret keys.
|
[
"Calls",
"f",
"with",
"any",
"secret",
"keys",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L734-L742
|
train
|
anacrolix/torrent
|
client.go
|
receiveHandshakes
|
func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) {
defer perf.ScopeTimerErr(&err)()
var rw io.ReadWriter
rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.forSkeys, cl.config.EncryptionPolicy)
c.setRW(rw)
if err == nil || err == mse.ErrNoSecretKeyMatch {
if c.headerEncrypted {
torrent.Add("handshakes received encrypted", 1)
} else {
torrent.Add("handshakes received unencrypted", 1)
}
} else {
torrent.Add("handshakes received with error while handling encryption", 1)
}
if err != nil {
if err == mse.ErrNoSecretKeyMatch {
err = nil
}
return
}
if cl.config.ForceEncryption && !c.headerEncrypted {
err = errors.New("connection not encrypted")
return
}
ih, ok, err := cl.connBTHandshake(c, nil)
if err != nil {
err = fmt.Errorf("error during bt handshake: %s", err)
return
}
if !ok {
return
}
cl.lock()
t = cl.torrents[ih]
cl.unlock()
return
}
|
go
|
func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) {
defer perf.ScopeTimerErr(&err)()
var rw io.ReadWriter
rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.forSkeys, cl.config.EncryptionPolicy)
c.setRW(rw)
if err == nil || err == mse.ErrNoSecretKeyMatch {
if c.headerEncrypted {
torrent.Add("handshakes received encrypted", 1)
} else {
torrent.Add("handshakes received unencrypted", 1)
}
} else {
torrent.Add("handshakes received with error while handling encryption", 1)
}
if err != nil {
if err == mse.ErrNoSecretKeyMatch {
err = nil
}
return
}
if cl.config.ForceEncryption && !c.headerEncrypted {
err = errors.New("connection not encrypted")
return
}
ih, ok, err := cl.connBTHandshake(c, nil)
if err != nil {
err = fmt.Errorf("error during bt handshake: %s", err)
return
}
if !ok {
return
}
cl.lock()
t = cl.torrents[ih]
cl.unlock()
return
}
|
[
"func",
"(",
"cl",
"*",
"Client",
")",
"receiveHandshakes",
"(",
"c",
"*",
"connection",
")",
"(",
"t",
"*",
"Torrent",
",",
"err",
"error",
")",
"{",
"defer",
"perf",
".",
"ScopeTimerErr",
"(",
"&",
"err",
")",
"(",
")",
"\n",
"var",
"rw",
"io",
".",
"ReadWriter",
"\n",
"rw",
",",
"c",
".",
"headerEncrypted",
",",
"c",
".",
"cryptoMethod",
",",
"err",
"=",
"handleEncryption",
"(",
"c",
".",
"rw",
"(",
")",
",",
"cl",
".",
"forSkeys",
",",
"cl",
".",
"config",
".",
"EncryptionPolicy",
")",
"\n",
"c",
".",
"setRW",
"(",
"rw",
")",
"\n",
"if",
"err",
"==",
"nil",
"||",
"err",
"==",
"mse",
".",
"ErrNoSecretKeyMatch",
"{",
"if",
"c",
".",
"headerEncrypted",
"{",
"torrent",
".",
"Add",
"(",
"\"handshakes received encrypted\"",
",",
"1",
")",
"\n",
"}",
"else",
"{",
"torrent",
".",
"Add",
"(",
"\"handshakes received unencrypted\"",
",",
"1",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"torrent",
".",
"Add",
"(",
"\"handshakes received with error while handling encryption\"",
",",
"1",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"mse",
".",
"ErrNoSecretKeyMatch",
"{",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"cl",
".",
"config",
".",
"ForceEncryption",
"&&",
"!",
"c",
".",
"headerEncrypted",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"connection not encrypted\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"ih",
",",
"ok",
",",
"err",
":=",
"cl",
".",
"connBTHandshake",
"(",
"c",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"error during bt handshake: %s\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"cl",
".",
"lock",
"(",
")",
"\n",
"t",
"=",
"cl",
".",
"torrents",
"[",
"ih",
"]",
"\n",
"cl",
".",
"unlock",
"(",
")",
"\n",
"return",
"\n",
"}"
] |
// Do encryption and bittorrent handshakes as receiver.
|
[
"Do",
"encryption",
"and",
"bittorrent",
"handshakes",
"as",
"receiver",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L745-L781
|
train
|
anacrolix/torrent
|
client.go
|
connBTHandshake
|
func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) {
res, ok, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.extensionBytes)
if err != nil || !ok {
return
}
ret = res.Hash
c.PeerExtensionBytes = res.PeerExtensionBits
c.PeerID = res.PeerID
c.completedHandshake = time.Now()
return
}
|
go
|
func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) {
res, ok, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.extensionBytes)
if err != nil || !ok {
return
}
ret = res.Hash
c.PeerExtensionBytes = res.PeerExtensionBits
c.PeerID = res.PeerID
c.completedHandshake = time.Now()
return
}
|
[
"func",
"(",
"cl",
"*",
"Client",
")",
"connBTHandshake",
"(",
"c",
"*",
"connection",
",",
"ih",
"*",
"metainfo",
".",
"Hash",
")",
"(",
"ret",
"metainfo",
".",
"Hash",
",",
"ok",
"bool",
",",
"err",
"error",
")",
"{",
"res",
",",
"ok",
",",
"err",
":=",
"pp",
".",
"Handshake",
"(",
"c",
".",
"rw",
"(",
")",
",",
"ih",
",",
"cl",
".",
"peerID",
",",
"cl",
".",
"extensionBytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"ret",
"=",
"res",
".",
"Hash",
"\n",
"c",
".",
"PeerExtensionBytes",
"=",
"res",
".",
"PeerExtensionBits",
"\n",
"c",
".",
"PeerID",
"=",
"res",
".",
"PeerID",
"\n",
"c",
".",
"completedHandshake",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"return",
"\n",
"}"
] |
// Returns !ok if handshake failed for valid reasons.
|
[
"Returns",
"!ok",
"if",
"handshake",
"failed",
"for",
"valid",
"reasons",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L784-L794
|
train
|
anacrolix/torrent
|
client.go
|
sendInitialMessages
|
func (cl *Client) sendInitialMessages(conn *connection, torrent *Torrent) {
if conn.PeerExtensionBytes.SupportsExtended() && cl.extensionBytes.SupportsExtended() {
conn.Post(pp.Message{
Type: pp.Extended,
ExtendedID: pp.HandshakeExtendedID,
ExtendedPayload: func() []byte {
msg := pp.ExtendedHandshakeMessage{
M: map[pp.ExtensionName]pp.ExtensionNumber{
pp.ExtensionNameMetadata: metadataExtendedId,
},
V: cl.config.ExtendedHandshakeClientVersion,
Reqq: 64, // TODO: Really?
YourIp: pp.CompactIp(conn.remoteAddr.IP),
Encryption: !cl.config.DisableEncryption,
Port: cl.incomingPeerPort(),
MetadataSize: torrent.metadataSize(),
// TODO: We can figured these out specific to the socket
// used.
Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
Ipv6: cl.config.PublicIp6.To16(),
}
if !cl.config.DisablePEX {
msg.M[pp.ExtensionNamePex] = pexExtendedId
}
return bencode.MustMarshal(msg)
}(),
})
}
func() {
if conn.fastEnabled() {
if torrent.haveAllPieces() {
conn.Post(pp.Message{Type: pp.HaveAll})
conn.sentHaves.AddRange(0, bitmap.BitIndex(conn.t.NumPieces()))
return
} else if !torrent.haveAnyPieces() {
conn.Post(pp.Message{Type: pp.HaveNone})
conn.sentHaves.Clear()
return
}
}
conn.PostBitfield()
}()
if conn.PeerExtensionBytes.SupportsDHT() && cl.extensionBytes.SupportsDHT() && cl.haveDhtServer() {
conn.Post(pp.Message{
Type: pp.Port,
Port: cl.dhtPort(),
})
}
}
|
go
|
func (cl *Client) sendInitialMessages(conn *connection, torrent *Torrent) {
if conn.PeerExtensionBytes.SupportsExtended() && cl.extensionBytes.SupportsExtended() {
conn.Post(pp.Message{
Type: pp.Extended,
ExtendedID: pp.HandshakeExtendedID,
ExtendedPayload: func() []byte {
msg := pp.ExtendedHandshakeMessage{
M: map[pp.ExtensionName]pp.ExtensionNumber{
pp.ExtensionNameMetadata: metadataExtendedId,
},
V: cl.config.ExtendedHandshakeClientVersion,
Reqq: 64, // TODO: Really?
YourIp: pp.CompactIp(conn.remoteAddr.IP),
Encryption: !cl.config.DisableEncryption,
Port: cl.incomingPeerPort(),
MetadataSize: torrent.metadataSize(),
// TODO: We can figured these out specific to the socket
// used.
Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
Ipv6: cl.config.PublicIp6.To16(),
}
if !cl.config.DisablePEX {
msg.M[pp.ExtensionNamePex] = pexExtendedId
}
return bencode.MustMarshal(msg)
}(),
})
}
func() {
if conn.fastEnabled() {
if torrent.haveAllPieces() {
conn.Post(pp.Message{Type: pp.HaveAll})
conn.sentHaves.AddRange(0, bitmap.BitIndex(conn.t.NumPieces()))
return
} else if !torrent.haveAnyPieces() {
conn.Post(pp.Message{Type: pp.HaveNone})
conn.sentHaves.Clear()
return
}
}
conn.PostBitfield()
}()
if conn.PeerExtensionBytes.SupportsDHT() && cl.extensionBytes.SupportsDHT() && cl.haveDhtServer() {
conn.Post(pp.Message{
Type: pp.Port,
Port: cl.dhtPort(),
})
}
}
|
[
"func",
"(",
"cl",
"*",
"Client",
")",
"sendInitialMessages",
"(",
"conn",
"*",
"connection",
",",
"torrent",
"*",
"Torrent",
")",
"{",
"if",
"conn",
".",
"PeerExtensionBytes",
".",
"SupportsExtended",
"(",
")",
"&&",
"cl",
".",
"extensionBytes",
".",
"SupportsExtended",
"(",
")",
"{",
"conn",
".",
"Post",
"(",
"pp",
".",
"Message",
"{",
"Type",
":",
"pp",
".",
"Extended",
",",
"ExtendedID",
":",
"pp",
".",
"HandshakeExtendedID",
",",
"ExtendedPayload",
":",
"func",
"(",
")",
"[",
"]",
"byte",
"{",
"msg",
":=",
"pp",
".",
"ExtendedHandshakeMessage",
"{",
"M",
":",
"map",
"[",
"pp",
".",
"ExtensionName",
"]",
"pp",
".",
"ExtensionNumber",
"{",
"pp",
".",
"ExtensionNameMetadata",
":",
"metadataExtendedId",
",",
"}",
",",
"V",
":",
"cl",
".",
"config",
".",
"ExtendedHandshakeClientVersion",
",",
"Reqq",
":",
"64",
",",
"YourIp",
":",
"pp",
".",
"CompactIp",
"(",
"conn",
".",
"remoteAddr",
".",
"IP",
")",
",",
"Encryption",
":",
"!",
"cl",
".",
"config",
".",
"DisableEncryption",
",",
"Port",
":",
"cl",
".",
"incomingPeerPort",
"(",
")",
",",
"MetadataSize",
":",
"torrent",
".",
"metadataSize",
"(",
")",
",",
"Ipv4",
":",
"pp",
".",
"CompactIp",
"(",
"cl",
".",
"config",
".",
"PublicIp4",
".",
"To4",
"(",
")",
")",
",",
"Ipv6",
":",
"cl",
".",
"config",
".",
"PublicIp6",
".",
"To16",
"(",
")",
",",
"}",
"\n",
"if",
"!",
"cl",
".",
"config",
".",
"DisablePEX",
"{",
"msg",
".",
"M",
"[",
"pp",
".",
"ExtensionNamePex",
"]",
"=",
"pexExtendedId",
"\n",
"}",
"\n",
"return",
"bencode",
".",
"MustMarshal",
"(",
"msg",
")",
"\n",
"}",
"(",
")",
",",
"}",
")",
"\n",
"}",
"\n",
"func",
"(",
")",
"{",
"if",
"conn",
".",
"fastEnabled",
"(",
")",
"{",
"if",
"torrent",
".",
"haveAllPieces",
"(",
")",
"{",
"conn",
".",
"Post",
"(",
"pp",
".",
"Message",
"{",
"Type",
":",
"pp",
".",
"HaveAll",
"}",
")",
"\n",
"conn",
".",
"sentHaves",
".",
"AddRange",
"(",
"0",
",",
"bitmap",
".",
"BitIndex",
"(",
"conn",
".",
"t",
".",
"NumPieces",
"(",
")",
")",
")",
"\n",
"return",
"\n",
"}",
"else",
"if",
"!",
"torrent",
".",
"haveAnyPieces",
"(",
")",
"{",
"conn",
".",
"Post",
"(",
"pp",
".",
"Message",
"{",
"Type",
":",
"pp",
".",
"HaveNone",
"}",
")",
"\n",
"conn",
".",
"sentHaves",
".",
"Clear",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"conn",
".",
"PostBitfield",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"if",
"conn",
".",
"PeerExtensionBytes",
".",
"SupportsDHT",
"(",
")",
"&&",
"cl",
".",
"extensionBytes",
".",
"SupportsDHT",
"(",
")",
"&&",
"cl",
".",
"haveDhtServer",
"(",
")",
"{",
"conn",
".",
"Post",
"(",
"pp",
".",
"Message",
"{",
"Type",
":",
"pp",
".",
"Port",
",",
"Port",
":",
"cl",
".",
"dhtPort",
"(",
")",
",",
"}",
")",
"\n",
"}",
"\n",
"}"
] |
// See the order given in Transmission's tr_peerMsgsNew.
|
[
"See",
"the",
"order",
"given",
"in",
"Transmission",
"s",
"tr_peerMsgsNew",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L864-L912
|
train
|
anacrolix/torrent
|
client.go
|
gotMetadataExtensionMsg
|
func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) error {
var d map[string]int
err := bencode.Unmarshal(payload, &d)
if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
} else if err != nil {
return fmt.Errorf("error unmarshalling bencode: %s", err)
}
msgType, ok := d["msg_type"]
if !ok {
return errors.New("missing msg_type field")
}
piece := d["piece"]
switch msgType {
case pp.DataMetadataExtensionMsgType:
c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
if !c.requestedMetadataPiece(piece) {
return fmt.Errorf("got unexpected piece %d", piece)
}
c.metadataRequests[piece] = false
begin := len(payload) - metadataPieceSize(d["total_size"], piece)
if begin < 0 || begin >= len(payload) {
return fmt.Errorf("data has bad offset in payload: %d", begin)
}
t.saveMetadataPiece(piece, payload[begin:])
c.lastUsefulChunkReceived = time.Now()
return t.maybeCompleteMetadata()
case pp.RequestMetadataExtensionMsgType:
if !t.haveMetadataPiece(piece) {
c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
return nil
}
start := (1 << 14) * piece
c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
return nil
case pp.RejectMetadataExtensionMsgType:
return nil
default:
return errors.New("unknown msg_type value")
}
}
|
go
|
func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) error {
var d map[string]int
err := bencode.Unmarshal(payload, &d)
if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
} else if err != nil {
return fmt.Errorf("error unmarshalling bencode: %s", err)
}
msgType, ok := d["msg_type"]
if !ok {
return errors.New("missing msg_type field")
}
piece := d["piece"]
switch msgType {
case pp.DataMetadataExtensionMsgType:
c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
if !c.requestedMetadataPiece(piece) {
return fmt.Errorf("got unexpected piece %d", piece)
}
c.metadataRequests[piece] = false
begin := len(payload) - metadataPieceSize(d["total_size"], piece)
if begin < 0 || begin >= len(payload) {
return fmt.Errorf("data has bad offset in payload: %d", begin)
}
t.saveMetadataPiece(piece, payload[begin:])
c.lastUsefulChunkReceived = time.Now()
return t.maybeCompleteMetadata()
case pp.RequestMetadataExtensionMsgType:
if !t.haveMetadataPiece(piece) {
c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
return nil
}
start := (1 << 14) * piece
c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
return nil
case pp.RejectMetadataExtensionMsgType:
return nil
default:
return errors.New("unknown msg_type value")
}
}
|
[
"func",
"(",
"cl",
"*",
"Client",
")",
"gotMetadataExtensionMsg",
"(",
"payload",
"[",
"]",
"byte",
",",
"t",
"*",
"Torrent",
",",
"c",
"*",
"connection",
")",
"error",
"{",
"var",
"d",
"map",
"[",
"string",
"]",
"int",
"\n",
"err",
":=",
"bencode",
".",
"Unmarshal",
"(",
"payload",
",",
"&",
"d",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"bencode",
".",
"ErrUnusedTrailingBytes",
")",
";",
"ok",
"{",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"error unmarshalling bencode: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"msgType",
",",
"ok",
":=",
"d",
"[",
"\"msg_type\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
"New",
"(",
"\"missing msg_type field\"",
")",
"\n",
"}",
"\n",
"piece",
":=",
"d",
"[",
"\"piece\"",
"]",
"\n",
"switch",
"msgType",
"{",
"case",
"pp",
".",
"DataMetadataExtensionMsgType",
":",
"c",
".",
"allStats",
"(",
"add",
"(",
"1",
",",
"func",
"(",
"cs",
"*",
"ConnStats",
")",
"*",
"Count",
"{",
"return",
"&",
"cs",
".",
"MetadataChunksRead",
"}",
")",
")",
"\n",
"if",
"!",
"c",
".",
"requestedMetadataPiece",
"(",
"piece",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"got unexpected piece %d\"",
",",
"piece",
")",
"\n",
"}",
"\n",
"c",
".",
"metadataRequests",
"[",
"piece",
"]",
"=",
"false",
"\n",
"begin",
":=",
"len",
"(",
"payload",
")",
"-",
"metadataPieceSize",
"(",
"d",
"[",
"\"total_size\"",
"]",
",",
"piece",
")",
"\n",
"if",
"begin",
"<",
"0",
"||",
"begin",
">=",
"len",
"(",
"payload",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"data has bad offset in payload: %d\"",
",",
"begin",
")",
"\n",
"}",
"\n",
"t",
".",
"saveMetadataPiece",
"(",
"piece",
",",
"payload",
"[",
"begin",
":",
"]",
")",
"\n",
"c",
".",
"lastUsefulChunkReceived",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"return",
"t",
".",
"maybeCompleteMetadata",
"(",
")",
"\n",
"case",
"pp",
".",
"RequestMetadataExtensionMsgType",
":",
"if",
"!",
"t",
".",
"haveMetadataPiece",
"(",
"piece",
")",
"{",
"c",
".",
"Post",
"(",
"t",
".",
"newMetadataExtensionMessage",
"(",
"c",
",",
"pp",
".",
"RejectMetadataExtensionMsgType",
",",
"d",
"[",
"\"piece\"",
"]",
",",
"nil",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"start",
":=",
"(",
"1",
"<<",
"14",
")",
"*",
"piece",
"\n",
"c",
".",
"Post",
"(",
"t",
".",
"newMetadataExtensionMessage",
"(",
"c",
",",
"pp",
".",
"DataMetadataExtensionMsgType",
",",
"piece",
",",
"t",
".",
"metadataBytes",
"[",
"start",
":",
"start",
"+",
"t",
".",
"metadataPieceSize",
"(",
"piece",
")",
"]",
")",
")",
"\n",
"return",
"nil",
"\n",
"case",
"pp",
".",
"RejectMetadataExtensionMsgType",
":",
"return",
"nil",
"\n",
"default",
":",
"return",
"errors",
".",
"New",
"(",
"\"unknown msg_type value\"",
")",
"\n",
"}",
"\n",
"}"
] |
// Process incoming ut_metadata message.
|
[
"Process",
"incoming",
"ut_metadata",
"message",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L929-L968
|
train
|
anacrolix/torrent
|
client.go
|
newTorrent
|
func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
// use provided storage, if provided
storageClient := cl.defaultStorage
if specStorage != nil {
storageClient = storage.NewClient(specStorage)
}
t = &Torrent{
cl: cl,
infoHash: ih,
peers: prioritizedPeers{
om: btree.New(32),
getPrio: func(p Peer) peerPriority {
return bep40PriorityIgnoreError(cl.publicAddr(p.IP), p.addr())
},
},
conns: make(map[*connection]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
halfOpen: make(map[string]Peer),
pieceStateChanges: pubsub.NewPubSub(),
storageOpener: storageClient,
maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
networkingEnabled: true,
requestStrategy: 2,
metadataChanged: sync.Cond{
L: cl.locker(),
},
duplicateRequestTimeout: 1 * time.Second,
}
t.logger = cl.logger.Clone().AddValue(t)
t.setChunkSize(defaultChunkSize)
return
}
|
go
|
func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
// use provided storage, if provided
storageClient := cl.defaultStorage
if specStorage != nil {
storageClient = storage.NewClient(specStorage)
}
t = &Torrent{
cl: cl,
infoHash: ih,
peers: prioritizedPeers{
om: btree.New(32),
getPrio: func(p Peer) peerPriority {
return bep40PriorityIgnoreError(cl.publicAddr(p.IP), p.addr())
},
},
conns: make(map[*connection]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
halfOpen: make(map[string]Peer),
pieceStateChanges: pubsub.NewPubSub(),
storageOpener: storageClient,
maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
networkingEnabled: true,
requestStrategy: 2,
metadataChanged: sync.Cond{
L: cl.locker(),
},
duplicateRequestTimeout: 1 * time.Second,
}
t.logger = cl.logger.Clone().AddValue(t)
t.setChunkSize(defaultChunkSize)
return
}
|
[
"func",
"(",
"cl",
"*",
"Client",
")",
"newTorrent",
"(",
"ih",
"metainfo",
".",
"Hash",
",",
"specStorage",
"storage",
".",
"ClientImpl",
")",
"(",
"t",
"*",
"Torrent",
")",
"{",
"storageClient",
":=",
"cl",
".",
"defaultStorage",
"\n",
"if",
"specStorage",
"!=",
"nil",
"{",
"storageClient",
"=",
"storage",
".",
"NewClient",
"(",
"specStorage",
")",
"\n",
"}",
"\n",
"t",
"=",
"&",
"Torrent",
"{",
"cl",
":",
"cl",
",",
"infoHash",
":",
"ih",
",",
"peers",
":",
"prioritizedPeers",
"{",
"om",
":",
"btree",
".",
"New",
"(",
"32",
")",
",",
"getPrio",
":",
"func",
"(",
"p",
"Peer",
")",
"peerPriority",
"{",
"return",
"bep40PriorityIgnoreError",
"(",
"cl",
".",
"publicAddr",
"(",
"p",
".",
"IP",
")",
",",
"p",
".",
"addr",
"(",
")",
")",
"\n",
"}",
",",
"}",
",",
"conns",
":",
"make",
"(",
"map",
"[",
"*",
"connection",
"]",
"struct",
"{",
"}",
",",
"2",
"*",
"cl",
".",
"config",
".",
"EstablishedConnsPerTorrent",
")",
",",
"halfOpen",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"Peer",
")",
",",
"pieceStateChanges",
":",
"pubsub",
".",
"NewPubSub",
"(",
")",
",",
"storageOpener",
":",
"storageClient",
",",
"maxEstablishedConns",
":",
"cl",
".",
"config",
".",
"EstablishedConnsPerTorrent",
",",
"networkingEnabled",
":",
"true",
",",
"requestStrategy",
":",
"2",
",",
"metadataChanged",
":",
"sync",
".",
"Cond",
"{",
"L",
":",
"cl",
".",
"locker",
"(",
")",
",",
"}",
",",
"duplicateRequestTimeout",
":",
"1",
"*",
"time",
".",
"Second",
",",
"}",
"\n",
"t",
".",
"logger",
"=",
"cl",
".",
"logger",
".",
"Clone",
"(",
")",
".",
"AddValue",
"(",
"t",
")",
"\n",
"t",
".",
"setChunkSize",
"(",
"defaultChunkSize",
")",
"\n",
"return",
"\n",
"}"
] |
// Return a Torrent ready for insertion into a Client.
|
[
"Return",
"a",
"Torrent",
"ready",
"for",
"insertion",
"into",
"a",
"Client",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L987-L1021
|
train
|
anacrolix/torrent
|
client.go
|
AddTorrentInfoHashWithStorage
|
func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
cl.lock()
defer cl.unlock()
t, ok := cl.torrents[infoHash]
if ok {
return
}
new = true
t = cl.newTorrent(infoHash, specStorage)
cl.eachDhtServer(func(s *dht.Server) {
go t.dhtAnnouncer(s)
})
cl.torrents[infoHash] = t
cl.clearAcceptLimits()
t.updateWantPeersEvent()
// Tickle Client.waitAccept, new torrent may want conns.
cl.event.Broadcast()
return
}
|
go
|
func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
cl.lock()
defer cl.unlock()
t, ok := cl.torrents[infoHash]
if ok {
return
}
new = true
t = cl.newTorrent(infoHash, specStorage)
cl.eachDhtServer(func(s *dht.Server) {
go t.dhtAnnouncer(s)
})
cl.torrents[infoHash] = t
cl.clearAcceptLimits()
t.updateWantPeersEvent()
// Tickle Client.waitAccept, new torrent may want conns.
cl.event.Broadcast()
return
}
|
[
"func",
"(",
"cl",
"*",
"Client",
")",
"AddTorrentInfoHashWithStorage",
"(",
"infoHash",
"metainfo",
".",
"Hash",
",",
"specStorage",
"storage",
".",
"ClientImpl",
")",
"(",
"t",
"*",
"Torrent",
",",
"new",
"bool",
")",
"{",
"cl",
".",
"lock",
"(",
")",
"\n",
"defer",
"cl",
".",
"unlock",
"(",
")",
"\n",
"t",
",",
"ok",
":=",
"cl",
".",
"torrents",
"[",
"infoHash",
"]",
"\n",
"if",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"new",
"=",
"true",
"\n",
"t",
"=",
"cl",
".",
"newTorrent",
"(",
"infoHash",
",",
"specStorage",
")",
"\n",
"cl",
".",
"eachDhtServer",
"(",
"func",
"(",
"s",
"*",
"dht",
".",
"Server",
")",
"{",
"go",
"t",
".",
"dhtAnnouncer",
"(",
"s",
")",
"\n",
"}",
")",
"\n",
"cl",
".",
"torrents",
"[",
"infoHash",
"]",
"=",
"t",
"\n",
"cl",
".",
"clearAcceptLimits",
"(",
")",
"\n",
"t",
".",
"updateWantPeersEvent",
"(",
")",
"\n",
"cl",
".",
"event",
".",
"Broadcast",
"(",
")",
"\n",
"return",
"\n",
"}"
] |
// Adds a torrent by InfoHash with a custom Storage implementation.
// If the torrent already exists then this Storage is ignored and the
// existing torrent returned with `new` set to `false`
|
[
"Adds",
"a",
"torrent",
"by",
"InfoHash",
"with",
"a",
"custom",
"Storage",
"implementation",
".",
"If",
"the",
"torrent",
"already",
"exists",
"then",
"this",
"Storage",
"is",
"ignored",
"and",
"the",
"existing",
"torrent",
"returned",
"with",
"new",
"set",
"to",
"false"
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L1038-L1057
|
train
|
anacrolix/torrent
|
client.go
|
WaitAll
|
func (cl *Client) WaitAll() bool {
cl.lock()
defer cl.unlock()
for !cl.allTorrentsCompleted() {
if cl.closed.IsSet() {
return false
}
cl.event.Wait()
}
return true
}
|
go
|
func (cl *Client) WaitAll() bool {
cl.lock()
defer cl.unlock()
for !cl.allTorrentsCompleted() {
if cl.closed.IsSet() {
return false
}
cl.event.Wait()
}
return true
}
|
[
"func",
"(",
"cl",
"*",
"Client",
")",
"WaitAll",
"(",
")",
"bool",
"{",
"cl",
".",
"lock",
"(",
")",
"\n",
"defer",
"cl",
".",
"unlock",
"(",
")",
"\n",
"for",
"!",
"cl",
".",
"allTorrentsCompleted",
"(",
")",
"{",
"if",
"cl",
".",
"closed",
".",
"IsSet",
"(",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"cl",
".",
"event",
".",
"Wait",
"(",
")",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// Returns true when all torrents are completely downloaded and false if the
// client is stopped before that.
|
[
"Returns",
"true",
"when",
"all",
"torrents",
"are",
"completely",
"downloaded",
"and",
"false",
"if",
"the",
"client",
"is",
"stopped",
"before",
"that",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L1114-L1124
|
train
|
anacrolix/torrent
|
client.go
|
Torrents
|
func (cl *Client) Torrents() []*Torrent {
cl.lock()
defer cl.unlock()
return cl.torrentsAsSlice()
}
|
go
|
func (cl *Client) Torrents() []*Torrent {
cl.lock()
defer cl.unlock()
return cl.torrentsAsSlice()
}
|
[
"func",
"(",
"cl",
"*",
"Client",
")",
"Torrents",
"(",
")",
"[",
"]",
"*",
"Torrent",
"{",
"cl",
".",
"lock",
"(",
")",
"\n",
"defer",
"cl",
".",
"unlock",
"(",
")",
"\n",
"return",
"cl",
".",
"torrentsAsSlice",
"(",
")",
"\n",
"}"
] |
// Returns handles to all the torrents loaded in the Client.
|
[
"Returns",
"handles",
"to",
"all",
"the",
"torrents",
"loaded",
"in",
"the",
"Client",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L1127-L1131
|
train
|
anacrolix/torrent
|
client.go
|
publicAddr
|
func (cl *Client) publicAddr(peer net.IP) IpPort {
return IpPort{cl.publicIp(peer), uint16(cl.incomingPeerPort())}
}
|
go
|
func (cl *Client) publicAddr(peer net.IP) IpPort {
return IpPort{cl.publicIp(peer), uint16(cl.incomingPeerPort())}
}
|
[
"func",
"(",
"cl",
"*",
"Client",
")",
"publicAddr",
"(",
"peer",
"net",
".",
"IP",
")",
"IpPort",
"{",
"return",
"IpPort",
"{",
"cl",
".",
"publicIp",
"(",
"peer",
")",
",",
"uint16",
"(",
"cl",
".",
"incomingPeerPort",
"(",
")",
")",
"}",
"\n",
"}"
] |
// Our IP as a peer should see it.
|
[
"Our",
"IP",
"as",
"a",
"peer",
"should",
"see",
"it",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L1277-L1279
|
train
|
anacrolix/torrent
|
mse/mse.go
|
postY
|
func (h *handshake) postY(x *big.Int) error {
var y big.Int
y.Exp(&g, x, &p)
return h.postWrite(paddedLeft(y.Bytes(), 96))
}
|
go
|
func (h *handshake) postY(x *big.Int) error {
var y big.Int
y.Exp(&g, x, &p)
return h.postWrite(paddedLeft(y.Bytes(), 96))
}
|
[
"func",
"(",
"h",
"*",
"handshake",
")",
"postY",
"(",
"x",
"*",
"big",
".",
"Int",
")",
"error",
"{",
"var",
"y",
"big",
".",
"Int",
"\n",
"y",
".",
"Exp",
"(",
"&",
"g",
",",
"x",
",",
"&",
"p",
")",
"\n",
"return",
"h",
".",
"postWrite",
"(",
"paddedLeft",
"(",
"y",
".",
"Bytes",
"(",
")",
",",
"96",
")",
")",
"\n",
"}"
] |
// Calculate, and send Y, our public key.
|
[
"Calculate",
"and",
"send",
"Y",
"our",
"public",
"key",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/mse/mse.go#L175-L179
|
train
|
anacrolix/torrent
|
mse/mse.go
|
suffixMatchLen
|
func suffixMatchLen(a, b []byte) int {
if len(b) > len(a) {
b = b[:len(a)]
}
// i is how much of b to try to match
for i := len(b); i > 0; i-- {
// j is how many chars we've compared
j := 0
for ; j < i; j++ {
if b[i-1-j] != a[len(a)-1-j] {
goto shorter
}
}
return j
shorter:
}
return 0
}
|
go
|
func suffixMatchLen(a, b []byte) int {
if len(b) > len(a) {
b = b[:len(a)]
}
// i is how much of b to try to match
for i := len(b); i > 0; i-- {
// j is how many chars we've compared
j := 0
for ; j < i; j++ {
if b[i-1-j] != a[len(a)-1-j] {
goto shorter
}
}
return j
shorter:
}
return 0
}
|
[
"func",
"suffixMatchLen",
"(",
"a",
",",
"b",
"[",
"]",
"byte",
")",
"int",
"{",
"if",
"len",
"(",
"b",
")",
">",
"len",
"(",
"a",
")",
"{",
"b",
"=",
"b",
"[",
":",
"len",
"(",
"a",
")",
"]",
"\n",
"}",
"\n",
"for",
"i",
":=",
"len",
"(",
"b",
")",
";",
"i",
">",
"0",
";",
"i",
"--",
"{",
"j",
":=",
"0",
"\n",
"for",
";",
"j",
"<",
"i",
";",
"j",
"++",
"{",
"if",
"b",
"[",
"i",
"-",
"1",
"-",
"j",
"]",
"!=",
"a",
"[",
"len",
"(",
"a",
")",
"-",
"1",
"-",
"j",
"]",
"{",
"goto",
"shorter",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"j",
"\n",
"shorter",
":",
"}",
"\n",
"return",
"0",
"\n",
"}"
] |
// Looking for b at the end of a.
|
[
"Looking",
"for",
"b",
"at",
"the",
"end",
"of",
"a",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/mse/mse.go#L322-L339
|
train
|
anacrolix/torrent
|
mse/mse.go
|
readUntil
|
func readUntil(r io.Reader, b []byte) error {
b1 := make([]byte, len(b))
i := 0
for {
_, err := io.ReadFull(r, b1[i:])
if err != nil {
return err
}
i = suffixMatchLen(b1, b)
if i == len(b) {
break
}
if copy(b1, b1[len(b1)-i:]) != i {
panic("wat")
}
}
return nil
}
|
go
|
func readUntil(r io.Reader, b []byte) error {
b1 := make([]byte, len(b))
i := 0
for {
_, err := io.ReadFull(r, b1[i:])
if err != nil {
return err
}
i = suffixMatchLen(b1, b)
if i == len(b) {
break
}
if copy(b1, b1[len(b1)-i:]) != i {
panic("wat")
}
}
return nil
}
|
[
"func",
"readUntil",
"(",
"r",
"io",
".",
"Reader",
",",
"b",
"[",
"]",
"byte",
")",
"error",
"{",
"b1",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"b",
")",
")",
"\n",
"i",
":=",
"0",
"\n",
"for",
"{",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"b1",
"[",
"i",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"i",
"=",
"suffixMatchLen",
"(",
"b1",
",",
"b",
")",
"\n",
"if",
"i",
"==",
"len",
"(",
"b",
")",
"{",
"break",
"\n",
"}",
"\n",
"if",
"copy",
"(",
"b1",
",",
"b1",
"[",
"len",
"(",
"b1",
")",
"-",
"i",
":",
"]",
")",
"!=",
"i",
"{",
"panic",
"(",
"\"wat\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Reads from r until b has been seen. Keeps the minimum amount of data in
// memory.
|
[
"Reads",
"from",
"r",
"until",
"b",
"has",
"been",
"seen",
".",
"Keeps",
"the",
"minimum",
"amount",
"of",
"data",
"in",
"memory",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/mse/mse.go#L343-L360
|
train
|
anacrolix/torrent
|
tracker/peer.go
|
fromDictInterface
|
func (p *Peer) fromDictInterface(d map[string]interface{}) {
p.IP = net.ParseIP(d["ip"].(string))
if _, ok := d["peer id"]; ok {
p.ID = []byte(d["peer id"].(string))
}
p.Port = int(d["port"].(int64))
}
|
go
|
func (p *Peer) fromDictInterface(d map[string]interface{}) {
p.IP = net.ParseIP(d["ip"].(string))
if _, ok := d["peer id"]; ok {
p.ID = []byte(d["peer id"].(string))
}
p.Port = int(d["port"].(int64))
}
|
[
"func",
"(",
"p",
"*",
"Peer",
")",
"fromDictInterface",
"(",
"d",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"{",
"p",
".",
"IP",
"=",
"net",
".",
"ParseIP",
"(",
"d",
"[",
"\"ip\"",
"]",
".",
"(",
"string",
")",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"d",
"[",
"\"peer id\"",
"]",
";",
"ok",
"{",
"p",
".",
"ID",
"=",
"[",
"]",
"byte",
"(",
"d",
"[",
"\"peer id\"",
"]",
".",
"(",
"string",
")",
")",
"\n",
"}",
"\n",
"p",
".",
"Port",
"=",
"int",
"(",
"d",
"[",
"\"port\"",
"]",
".",
"(",
"int64",
")",
")",
"\n",
"}"
] |
// Set from the non-compact form in BEP 3.
|
[
"Set",
"from",
"the",
"non",
"-",
"compact",
"form",
"in",
"BEP",
"3",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/tracker/peer.go#L16-L22
|
train
|
anacrolix/torrent
|
metainfo/announcelist.go
|
OverridesAnnounce
|
func (al AnnounceList) OverridesAnnounce(announce string) bool {
for _, tier := range al {
for _, url := range tier {
if url != "" || announce == "" {
return true
}
}
}
return false
}
|
go
|
func (al AnnounceList) OverridesAnnounce(announce string) bool {
for _, tier := range al {
for _, url := range tier {
if url != "" || announce == "" {
return true
}
}
}
return false
}
|
[
"func",
"(",
"al",
"AnnounceList",
")",
"OverridesAnnounce",
"(",
"announce",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"tier",
":=",
"range",
"al",
"{",
"for",
"_",
",",
"url",
":=",
"range",
"tier",
"{",
"if",
"url",
"!=",
"\"\"",
"||",
"announce",
"==",
"\"\"",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// Whether the AnnounceList should be preferred over a single URL announce.
|
[
"Whether",
"the",
"AnnounceList",
"should",
"be",
"preferred",
"over",
"a",
"single",
"URL",
"announce",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/announcelist.go#L6-L15
|
train
|
anacrolix/torrent
|
prioritized_peers.go
|
Add
|
func (me *prioritizedPeers) Add(p Peer) bool {
return me.om.ReplaceOrInsert(prioritizedPeersItem{me.getPrio(p), p}) != nil
}
|
go
|
func (me *prioritizedPeers) Add(p Peer) bool {
return me.om.ReplaceOrInsert(prioritizedPeersItem{me.getPrio(p), p}) != nil
}
|
[
"func",
"(",
"me",
"*",
"prioritizedPeers",
")",
"Add",
"(",
"p",
"Peer",
")",
"bool",
"{",
"return",
"me",
".",
"om",
".",
"ReplaceOrInsert",
"(",
"prioritizedPeersItem",
"{",
"me",
".",
"getPrio",
"(",
"p",
")",
",",
"p",
"}",
")",
"!=",
"nil",
"\n",
"}"
] |
// Returns true if a peer is replaced.
|
[
"Returns",
"true",
"if",
"a",
"peer",
"is",
"replaced",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/prioritized_peers.go#L33-L35
|
train
|
anacrolix/torrent
|
storage/file.go
|
defaultPathMaker
|
func defaultPathMaker(baseDir string, info *metainfo.Info, infoHash metainfo.Hash) string {
return baseDir
}
|
go
|
func defaultPathMaker(baseDir string, info *metainfo.Info, infoHash metainfo.Hash) string {
return baseDir
}
|
[
"func",
"defaultPathMaker",
"(",
"baseDir",
"string",
",",
"info",
"*",
"metainfo",
".",
"Info",
",",
"infoHash",
"metainfo",
".",
"Hash",
")",
"string",
"{",
"return",
"baseDir",
"\n",
"}"
] |
// The Default path maker just returns the current path
|
[
"The",
"Default",
"path",
"maker",
"just",
"returns",
"the",
"current",
"path"
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/storage/file.go#L21-L23
|
train
|
anacrolix/torrent
|
storage/file.go
|
NewFileWithCustomPathMaker
|
func NewFileWithCustomPathMaker(baseDir string, pathMaker func(baseDir string, info *metainfo.Info, infoHash metainfo.Hash) string) ClientImpl {
return newFileWithCustomPathMakerAndCompletion(baseDir, pathMaker, pieceCompletionForDir(baseDir))
}
|
go
|
func NewFileWithCustomPathMaker(baseDir string, pathMaker func(baseDir string, info *metainfo.Info, infoHash metainfo.Hash) string) ClientImpl {
return newFileWithCustomPathMakerAndCompletion(baseDir, pathMaker, pieceCompletionForDir(baseDir))
}
|
[
"func",
"NewFileWithCustomPathMaker",
"(",
"baseDir",
"string",
",",
"pathMaker",
"func",
"(",
"baseDir",
"string",
",",
"info",
"*",
"metainfo",
".",
"Info",
",",
"infoHash",
"metainfo",
".",
"Hash",
")",
"string",
")",
"ClientImpl",
"{",
"return",
"newFileWithCustomPathMakerAndCompletion",
"(",
"baseDir",
",",
"pathMaker",
",",
"pieceCompletionForDir",
"(",
"baseDir",
")",
")",
"\n",
"}"
] |
// Allows passing a function to determine the path for storing torrent data
|
[
"Allows",
"passing",
"a",
"function",
"to",
"determine",
"the",
"path",
"for",
"storing",
"torrent",
"data"
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/storage/file.go#L44-L46
|
train
|
anacrolix/torrent
|
storage/file.go
|
CreateNativeZeroLengthFiles
|
func CreateNativeZeroLengthFiles(info *metainfo.Info, dir string) (err error) {
for _, fi := range info.UpvertedFiles() {
if fi.Length != 0 {
continue
}
name := filepath.Join(append([]string{dir, info.Name}, fi.Path...)...)
os.MkdirAll(filepath.Dir(name), 0777)
var f io.Closer
f, err = os.Create(name)
if err != nil {
break
}
f.Close()
}
return
}
|
go
|
func CreateNativeZeroLengthFiles(info *metainfo.Info, dir string) (err error) {
for _, fi := range info.UpvertedFiles() {
if fi.Length != 0 {
continue
}
name := filepath.Join(append([]string{dir, info.Name}, fi.Path...)...)
os.MkdirAll(filepath.Dir(name), 0777)
var f io.Closer
f, err = os.Create(name)
if err != nil {
break
}
f.Close()
}
return
}
|
[
"func",
"CreateNativeZeroLengthFiles",
"(",
"info",
"*",
"metainfo",
".",
"Info",
",",
"dir",
"string",
")",
"(",
"err",
"error",
")",
"{",
"for",
"_",
",",
"fi",
":=",
"range",
"info",
".",
"UpvertedFiles",
"(",
")",
"{",
"if",
"fi",
".",
"Length",
"!=",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"name",
":=",
"filepath",
".",
"Join",
"(",
"append",
"(",
"[",
"]",
"string",
"{",
"dir",
",",
"info",
".",
"Name",
"}",
",",
"fi",
".",
"Path",
"...",
")",
"...",
")",
"\n",
"os",
".",
"MkdirAll",
"(",
"filepath",
".",
"Dir",
"(",
"name",
")",
",",
"0777",
")",
"\n",
"var",
"f",
"io",
".",
"Closer",
"\n",
"f",
",",
"err",
"=",
"os",
".",
"Create",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"f",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Creates natives files for any zero-length file entries in the info. This is
// a helper for file-based storages, which don't address or write to zero-
// length files because they have no corresponding pieces.
|
[
"Creates",
"natives",
"files",
"for",
"any",
"zero",
"-",
"length",
"file",
"entries",
"in",
"the",
"info",
".",
"This",
"is",
"a",
"helper",
"for",
"file",
"-",
"based",
"storages",
"which",
"don",
"t",
"address",
"or",
"write",
"to",
"zero",
"-",
"length",
"files",
"because",
"they",
"have",
"no",
"corresponding",
"pieces",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/storage/file.go#L103-L118
|
train
|
anacrolix/torrent
|
storage/file.go
|
readFileAt
|
func (fst *fileTorrentImplIO) readFileAt(fi metainfo.FileInfo, b []byte, off int64) (n int, err error) {
f, err := os.Open(fst.fts.fileInfoName(fi))
if os.IsNotExist(err) {
// File missing is treated the same as a short file.
err = io.EOF
return
}
if err != nil {
return
}
defer f.Close()
// Limit the read to within the expected bounds of this file.
if int64(len(b)) > fi.Length-off {
b = b[:fi.Length-off]
}
for off < fi.Length && len(b) != 0 {
n1, err1 := f.ReadAt(b, off)
b = b[n1:]
n += n1
off += int64(n1)
if n1 == 0 {
err = err1
break
}
}
return
}
|
go
|
func (fst *fileTorrentImplIO) readFileAt(fi metainfo.FileInfo, b []byte, off int64) (n int, err error) {
f, err := os.Open(fst.fts.fileInfoName(fi))
if os.IsNotExist(err) {
// File missing is treated the same as a short file.
err = io.EOF
return
}
if err != nil {
return
}
defer f.Close()
// Limit the read to within the expected bounds of this file.
if int64(len(b)) > fi.Length-off {
b = b[:fi.Length-off]
}
for off < fi.Length && len(b) != 0 {
n1, err1 := f.ReadAt(b, off)
b = b[n1:]
n += n1
off += int64(n1)
if n1 == 0 {
err = err1
break
}
}
return
}
|
[
"func",
"(",
"fst",
"*",
"fileTorrentImplIO",
")",
"readFileAt",
"(",
"fi",
"metainfo",
".",
"FileInfo",
",",
"b",
"[",
"]",
"byte",
",",
"off",
"int64",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"fst",
".",
"fts",
".",
"fileInfoName",
"(",
"fi",
")",
")",
"\n",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"err",
"=",
"io",
".",
"EOF",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"if",
"int64",
"(",
"len",
"(",
"b",
")",
")",
">",
"fi",
".",
"Length",
"-",
"off",
"{",
"b",
"=",
"b",
"[",
":",
"fi",
".",
"Length",
"-",
"off",
"]",
"\n",
"}",
"\n",
"for",
"off",
"<",
"fi",
".",
"Length",
"&&",
"len",
"(",
"b",
")",
"!=",
"0",
"{",
"n1",
",",
"err1",
":=",
"f",
".",
"ReadAt",
"(",
"b",
",",
"off",
")",
"\n",
"b",
"=",
"b",
"[",
"n1",
":",
"]",
"\n",
"n",
"+=",
"n1",
"\n",
"off",
"+=",
"int64",
"(",
"n1",
")",
"\n",
"if",
"n1",
"==",
"0",
"{",
"err",
"=",
"err1",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Returns EOF on short or missing file.
|
[
"Returns",
"EOF",
"on",
"short",
"or",
"missing",
"file",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/storage/file.go#L126-L152
|
train
|
anacrolix/torrent
|
storage/file.go
|
ReadAt
|
func (fst fileTorrentImplIO) ReadAt(b []byte, off int64) (n int, err error) {
for _, fi := range fst.fts.info.UpvertedFiles() {
for off < fi.Length {
n1, err1 := fst.readFileAt(fi, b, off)
n += n1
off += int64(n1)
b = b[n1:]
if len(b) == 0 {
// Got what we need.
return
}
if n1 != 0 {
// Made progress.
continue
}
err = err1
if err == io.EOF {
// Lies.
err = io.ErrUnexpectedEOF
}
return
}
off -= fi.Length
}
err = io.EOF
return
}
|
go
|
func (fst fileTorrentImplIO) ReadAt(b []byte, off int64) (n int, err error) {
for _, fi := range fst.fts.info.UpvertedFiles() {
for off < fi.Length {
n1, err1 := fst.readFileAt(fi, b, off)
n += n1
off += int64(n1)
b = b[n1:]
if len(b) == 0 {
// Got what we need.
return
}
if n1 != 0 {
// Made progress.
continue
}
err = err1
if err == io.EOF {
// Lies.
err = io.ErrUnexpectedEOF
}
return
}
off -= fi.Length
}
err = io.EOF
return
}
|
[
"func",
"(",
"fst",
"fileTorrentImplIO",
")",
"ReadAt",
"(",
"b",
"[",
"]",
"byte",
",",
"off",
"int64",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"for",
"_",
",",
"fi",
":=",
"range",
"fst",
".",
"fts",
".",
"info",
".",
"UpvertedFiles",
"(",
")",
"{",
"for",
"off",
"<",
"fi",
".",
"Length",
"{",
"n1",
",",
"err1",
":=",
"fst",
".",
"readFileAt",
"(",
"fi",
",",
"b",
",",
"off",
")",
"\n",
"n",
"+=",
"n1",
"\n",
"off",
"+=",
"int64",
"(",
"n1",
")",
"\n",
"b",
"=",
"b",
"[",
"n1",
":",
"]",
"\n",
"if",
"len",
"(",
"b",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"if",
"n1",
"!=",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"err",
"=",
"err1",
"\n",
"if",
"err",
"==",
"io",
".",
"EOF",
"{",
"err",
"=",
"io",
".",
"ErrUnexpectedEOF",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"off",
"-=",
"fi",
".",
"Length",
"\n",
"}",
"\n",
"err",
"=",
"io",
".",
"EOF",
"\n",
"return",
"\n",
"}"
] |
// Only returns EOF at the end of the torrent. Premature EOF is ErrUnexpectedEOF.
|
[
"Only",
"returns",
"EOF",
"at",
"the",
"end",
"of",
"the",
"torrent",
".",
"Premature",
"EOF",
"is",
"ErrUnexpectedEOF",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/storage/file.go#L155-L181
|
train
|
anacrolix/torrent
|
t.go
|
Info
|
func (t *Torrent) Info() *metainfo.Info {
t.cl.lock()
defer t.cl.unlock()
return t.info
}
|
go
|
func (t *Torrent) Info() *metainfo.Info {
t.cl.lock()
defer t.cl.unlock()
return t.info
}
|
[
"func",
"(",
"t",
"*",
"Torrent",
")",
"Info",
"(",
")",
"*",
"metainfo",
".",
"Info",
"{",
"t",
".",
"cl",
".",
"lock",
"(",
")",
"\n",
"defer",
"t",
".",
"cl",
".",
"unlock",
"(",
")",
"\n",
"return",
"t",
".",
"info",
"\n",
"}"
] |
// Returns the metainfo info dictionary, or nil if it's not yet available.
|
[
"Returns",
"the",
"metainfo",
"info",
"dictionary",
"or",
"nil",
"if",
"it",
"s",
"not",
"yet",
"available",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L26-L30
|
train
|
anacrolix/torrent
|
t.go
|
NewReader
|
func (t *Torrent) NewReader() Reader {
r := reader{
mu: t.cl.locker(),
t: t,
readahead: 5 * 1024 * 1024,
length: *t.length,
}
t.addReader(&r)
return &r
}
|
go
|
func (t *Torrent) NewReader() Reader {
r := reader{
mu: t.cl.locker(),
t: t,
readahead: 5 * 1024 * 1024,
length: *t.length,
}
t.addReader(&r)
return &r
}
|
[
"func",
"(",
"t",
"*",
"Torrent",
")",
"NewReader",
"(",
")",
"Reader",
"{",
"r",
":=",
"reader",
"{",
"mu",
":",
"t",
".",
"cl",
".",
"locker",
"(",
")",
",",
"t",
":",
"t",
",",
"readahead",
":",
"5",
"*",
"1024",
"*",
"1024",
",",
"length",
":",
"*",
"t",
".",
"length",
",",
"}",
"\n",
"t",
".",
"addReader",
"(",
"&",
"r",
")",
"\n",
"return",
"&",
"r",
"\n",
"}"
] |
// Returns a Reader bound to the torrent's data. All read calls block until
// the data requested is actually available.
|
[
"Returns",
"a",
"Reader",
"bound",
"to",
"the",
"torrent",
"s",
"data",
".",
"All",
"read",
"calls",
"block",
"until",
"the",
"data",
"requested",
"is",
"actually",
"available",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L34-L43
|
train
|
anacrolix/torrent
|
t.go
|
PieceStateRuns
|
func (t *Torrent) PieceStateRuns() []PieceStateRun {
t.cl.rLock()
defer t.cl.rUnlock()
return t.pieceStateRuns()
}
|
go
|
func (t *Torrent) PieceStateRuns() []PieceStateRun {
t.cl.rLock()
defer t.cl.rUnlock()
return t.pieceStateRuns()
}
|
[
"func",
"(",
"t",
"*",
"Torrent",
")",
"PieceStateRuns",
"(",
")",
"[",
"]",
"PieceStateRun",
"{",
"t",
".",
"cl",
".",
"rLock",
"(",
")",
"\n",
"defer",
"t",
".",
"cl",
".",
"rUnlock",
"(",
")",
"\n",
"return",
"t",
".",
"pieceStateRuns",
"(",
")",
"\n",
"}"
] |
// Returns the state of pieces of the torrent. They are grouped into runs of
// same state. The sum of the state run lengths is the number of pieces
// in the torrent.
|
[
"Returns",
"the",
"state",
"of",
"pieces",
"of",
"the",
"torrent",
".",
"They",
"are",
"grouped",
"into",
"runs",
"of",
"same",
"state",
".",
"The",
"sum",
"of",
"the",
"state",
"run",
"lengths",
"is",
"the",
"number",
"of",
"pieces",
"in",
"the",
"torrent",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L48-L52
|
train
|
anacrolix/torrent
|
t.go
|
PieceBytesMissing
|
func (t *Torrent) PieceBytesMissing(piece int) int64 {
t.cl.lock()
defer t.cl.unlock()
return int64(t.pieces[piece].bytesLeft())
}
|
go
|
func (t *Torrent) PieceBytesMissing(piece int) int64 {
t.cl.lock()
defer t.cl.unlock()
return int64(t.pieces[piece].bytesLeft())
}
|
[
"func",
"(",
"t",
"*",
"Torrent",
")",
"PieceBytesMissing",
"(",
"piece",
"int",
")",
"int64",
"{",
"t",
".",
"cl",
".",
"lock",
"(",
")",
"\n",
"defer",
"t",
".",
"cl",
".",
"unlock",
"(",
")",
"\n",
"return",
"int64",
"(",
"t",
".",
"pieces",
"[",
"piece",
"]",
".",
"bytesLeft",
"(",
")",
")",
"\n",
"}"
] |
// Get missing bytes count for specific piece.
|
[
"Get",
"missing",
"bytes",
"count",
"for",
"specific",
"piece",
"."
] |
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
|
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L67-L72
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.