repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L47-L50
go
train
// Anon mocks base method
func (m *MockIndex) Anon(arg0 string)
// Anon mocks base method func (m *MockIndex) Anon(arg0 string)
{ m.ctrl.T.Helper() m.ctrl.Call(m, "Anon", arg0) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L53-L56
go
train
// Anon indicates an expected call of Anon
func (mr *MockIndexMockRecorder) Anon(arg0 interface{}) *gomock.Call
// Anon indicates an expected call of Anon func (mr *MockIndexMockRecorder) Anon(arg0 interface{}) *gomock.Call
{ mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Anon", reflect.TypeOf((*MockIndex)(nil).Anon), arg0) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L59-L62
go
train
// Chan mocks base method
func (m *MockIndex) Chan(arg0 chan int, arg1 chan<- hash.Hash)
// Chan mocks base method func (m *MockIndex) Chan(arg0 chan int, arg1 chan<- hash.Hash)
{ m.ctrl.T.Helper() m.ctrl.Call(m, "Chan", arg0, arg1) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L71-L76
go
train
// ConcreteRet mocks base method
func (m *MockIndex) ConcreteRet() chan<- bool
// ConcreteRet mocks base method func (m *MockIndex) ConcreteRet() chan<- bool
{ m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ConcreteRet") ret0, _ := ret[0].(chan<- bool) return ret0 }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L95-L99
go
train
// Ellip indicates an expected call of Ellip
func (mr *MockIndexMockRecorder) Ellip(arg0 interface{}, arg1 ...interface{}) *gomock.Call
// Ellip indicates an expected call of Ellip func (mr *MockIndexMockRecorder) Ellip(arg0 interface{}, arg1 ...interface{}) *gomock.Call
{ mr.mock.ctrl.T.Helper() varargs := append([]interface{}{arg0}, arg1...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ellip", reflect.TypeOf((*MockIndex)(nil).Ellip), varargs...) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L102-L109
go
train
// EllipOnly mocks base method
func (m *MockIndex) EllipOnly(arg0 ...string)
// EllipOnly mocks base method func (m *MockIndex) EllipOnly(arg0 ...string)
{ m.ctrl.T.Helper() varargs := []interface{}{} for _, a := range arg0 { varargs = append(varargs, a) } m.ctrl.Call(m, "EllipOnly", varargs...) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L118-L121
go
train
// ForeignFour mocks base method
func (m *MockIndex) ForeignFour(arg0 imp4.Imp4)
// ForeignFour mocks base method func (m *MockIndex) ForeignFour(arg0 imp4.Imp4)
{ m.ctrl.T.Helper() m.ctrl.Call(m, "ForeignFour", arg0) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L130-L133
go
train
// ForeignOne mocks base method
func (m *MockIndex) ForeignOne(arg0 imp1.Imp1)
// ForeignOne mocks base method func (m *MockIndex) ForeignOne(arg0 imp1.Imp1)
{ m.ctrl.T.Helper() m.ctrl.Call(m, "ForeignOne", arg0) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L142-L145
go
train
// ForeignThree mocks base method
func (m *MockIndex) ForeignThree(arg0 imp3.Imp3)
// ForeignThree mocks base method func (m *MockIndex) ForeignThree(arg0 imp3.Imp3)
{ m.ctrl.T.Helper() m.ctrl.Call(m, "ForeignThree", arg0) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L154-L157
go
train
// ForeignTwo mocks base method
func (m *MockIndex) ForeignTwo(arg0 imp2.Imp2)
// ForeignTwo mocks base method func (m *MockIndex) ForeignTwo(arg0 imp2.Imp2)
{ m.ctrl.T.Helper() m.ctrl.Call(m, "ForeignTwo", arg0) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L166-L169
go
train
// Func mocks base method
func (m *MockIndex) Func(arg0 func(http.Request) (int, bool))
// Func mocks base method func (m *MockIndex) Func(arg0 func(http.Request) (int, bool))
{ m.ctrl.T.Helper() m.ctrl.Call(m, "Func", arg0) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L178-L183
go
train
// Get mocks base method
func (m *MockIndex) Get(arg0 string) interface{}
// Get mocks base method func (m *MockIndex) Get(arg0 string) interface{}
{ m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Get", arg0) ret0, _ := ret[0].(interface{}) return ret0 }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L192-L198
go
train
// GetTwo mocks base method
func (m *MockIndex) GetTwo(arg0, arg1 string) (interface{}, interface{})
// GetTwo mocks base method func (m *MockIndex) GetTwo(arg0, arg1 string) (interface{}, interface{})
{ m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetTwo", arg0, arg1) ret0, _ := ret[0].(interface{}) ret1, _ := ret[1].(interface{}) return ret0, ret1 }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L207-L210
go
train
// Map mocks base method
func (m *MockIndex) Map(arg0 map[int]hash.Hash)
// Map mocks base method func (m *MockIndex) Map(arg0 map[int]hash.Hash)
{ m.ctrl.T.Helper() m.ctrl.Call(m, "Map", arg0) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L219-L224
go
train
// NillableRet mocks base method
func (m *MockIndex) NillableRet() error
// NillableRet mocks base method func (m *MockIndex) NillableRet() error
{ m.ctrl.T.Helper() ret := m.ctrl.Call(m, "NillableRet") ret0, _ := ret[0].(error) return ret0 }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L233-L238
go
train
// Other mocks base method
func (m *MockIndex) Other() hash.Hash
// Other mocks base method func (m *MockIndex) Other() hash.Hash
{ m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Other") ret0, _ := ret[0].(hash.Hash) return ret0 }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L247-L250
go
train
// Ptr mocks base method
func (m *MockIndex) Ptr(arg0 *int)
// Ptr mocks base method func (m *MockIndex) Ptr(arg0 *int)
{ m.ctrl.T.Helper() m.ctrl.Call(m, "Ptr", arg0) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L259-L262
go
train
// Put mocks base method
func (m *MockIndex) Put(arg0 string, arg1 interface{})
// Put mocks base method func (m *MockIndex) Put(arg0 string, arg1 interface{})
{ m.ctrl.T.Helper() m.ctrl.Call(m, "Put", arg0, arg1) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L271-L276
go
train
// Slice mocks base method
func (m *MockIndex) Slice(arg0 []int, arg1 []byte) [3]int
// Slice mocks base method func (m *MockIndex) Slice(arg0 []int, arg1 []byte) [3]int
{ m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Slice", arg0, arg1) ret0, _ := ret[0].([3]int) return ret0 }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L285-L288
go
train
// Struct mocks base method
func (m *MockIndex) Struct(arg0 struct{})
// Struct mocks base method func (m *MockIndex) Struct(arg0 struct{})
{ m.ctrl.T.Helper() m.ctrl.Call(m, "Struct", arg0) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L297-L300
go
train
// StructChan mocks base method
func (m *MockIndex) StructChan(arg0 chan struct{})
// StructChan mocks base method func (m *MockIndex) StructChan(arg0 chan struct{})
{ m.ctrl.T.Helper() m.ctrl.Call(m, "StructChan", arg0) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L309-L312
go
train
// Summary mocks base method
func (m *MockIndex) Summary(arg0 *bytes.Buffer, arg1 io.Writer)
// Summary mocks base method func (m *MockIndex) Summary(arg0 *bytes.Buffer, arg1 io.Writer)
{ m.ctrl.T.Helper() m.ctrl.Call(m, "Summary", arg0, arg1) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L321-L324
go
train
// Templates mocks base method
func (m *MockIndex) Templates(arg0 template.CSS, arg1 template0.FuncMap)
// Templates mocks base method func (m *MockIndex) Templates(arg0 template.CSS, arg1 template0.FuncMap)
{ m.ctrl.T.Helper() m.ctrl.Call(m, "Templates", arg0, arg1) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L344-L348
go
train
// NewMockEmbed creates a new mock instance
func NewMockEmbed(ctrl *gomock.Controller) *MockEmbed
// NewMockEmbed creates a new mock instance func NewMockEmbed(ctrl *gomock.Controller) *MockEmbed
{ mock := &MockEmbed{ctrl: ctrl} mock.recorder = &MockEmbedMockRecorder{mock} return mock }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L356-L359
go
train
// EmbeddedMethod mocks base method
func (m *MockEmbed) EmbeddedMethod()
// EmbeddedMethod mocks base method func (m *MockEmbed) EmbeddedMethod()
{ m.ctrl.T.Helper() m.ctrl.Call(m, "EmbeddedMethod") }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L368-L373
go
train
// ForeignEmbeddedMethod mocks base method
func (m *MockEmbed) ForeignEmbeddedMethod() *bufio.Reader
// ForeignEmbeddedMethod mocks base method func (m *MockEmbed) ForeignEmbeddedMethod() *bufio.Reader
{ m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ForeignEmbeddedMethod") ret0, _ := ret[0].(*bufio.Reader) return ret0 }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L376-L379
go
train
// ForeignEmbeddedMethod indicates an expected call of ForeignEmbeddedMethod
func (mr *MockEmbedMockRecorder) ForeignEmbeddedMethod() *gomock.Call
// ForeignEmbeddedMethod indicates an expected call of ForeignEmbeddedMethod func (mr *MockEmbedMockRecorder) ForeignEmbeddedMethod() *gomock.Call
{ mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ForeignEmbeddedMethod", reflect.TypeOf((*MockEmbed)(nil).ForeignEmbeddedMethod)) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L382-L385
go
train
// ImplicitPackage mocks base method
func (m *MockEmbed) ImplicitPackage(arg0 string, arg1 imp1.ImpT, arg2 []imp1.ImpT, arg3 *imp1.ImpT, arg4 chan imp1.ImpT)
// ImplicitPackage mocks base method func (m *MockEmbed) ImplicitPackage(arg0 string, arg1 imp1.ImpT, arg2 []imp1.ImpT, arg3 *imp1.ImpT, arg4 chan imp1.ImpT)
{ m.ctrl.T.Helper() m.ctrl.Call(m, "ImplicitPackage", arg0, arg1, arg2, arg3, arg4) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L388-L391
go
train
// ImplicitPackage indicates an expected call of ImplicitPackage
func (mr *MockEmbedMockRecorder) ImplicitPackage(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call
// ImplicitPackage indicates an expected call of ImplicitPackage func (mr *MockEmbedMockRecorder) ImplicitPackage(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call
{ mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ImplicitPackage", reflect.TypeOf((*MockEmbed)(nil).ImplicitPackage), arg0, arg1, arg2, arg3, arg4) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L394-L397
go
train
// RegularMethod mocks base method
func (m *MockEmbed) RegularMethod()
// RegularMethod mocks base method func (m *MockEmbed) RegularMethod()
{ m.ctrl.T.Helper() m.ctrl.Call(m, "RegularMethod") }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L417-L421
go
train
// NewMockEmbedded creates a new mock instance
func NewMockEmbedded(ctrl *gomock.Controller) *MockEmbedded
// NewMockEmbedded creates a new mock instance func NewMockEmbedded(ctrl *gomock.Controller) *MockEmbedded
{ mock := &MockEmbedded{ctrl: ctrl} mock.recorder = &MockEmbeddedMockRecorder{mock} return mock }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L429-L432
go
train
// EmbeddedMethod mocks base method
func (m *MockEmbedded) EmbeddedMethod()
// EmbeddedMethod mocks base method func (m *MockEmbedded) EmbeddedMethod()
{ m.ctrl.T.Helper() m.ctrl.Call(m, "EmbeddedMethod") }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
sample/mock_user/mock_user.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L435-L438
go
train
// EmbeddedMethod indicates an expected call of EmbeddedMethod
func (mr *MockEmbeddedMockRecorder) EmbeddedMethod() *gomock.Call
// EmbeddedMethod indicates an expected call of EmbeddedMethod func (mr *MockEmbeddedMockRecorder) EmbeddedMethod() *gomock.Call
{ mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EmbeddedMethod", reflect.TypeOf((*MockEmbedded)(nil).EmbeddedMethod)) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
gomock/internal/mock_gomock/mock_matcher.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/internal/mock_gomock/mock_matcher.go#L24-L28
go
train
// NewMockMatcher creates a new mock instance
func NewMockMatcher(ctrl *gomock.Controller) *MockMatcher
// NewMockMatcher creates a new mock instance func NewMockMatcher(ctrl *gomock.Controller) *MockMatcher
{ mock := &MockMatcher{ctrl: ctrl} mock.recorder = &MockMatcherMockRecorder{mock} return mock }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
gomock/internal/mock_gomock/mock_matcher.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/internal/mock_gomock/mock_matcher.go#L36-L41
go
train
// Matches mocks base method
func (m *MockMatcher) Matches(arg0 interface{}) bool
// Matches mocks base method func (m *MockMatcher) Matches(arg0 interface{}) bool
{ m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Matches", arg0) ret0, _ := ret[0].(bool) return ret0 }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
gomock/internal/mock_gomock/mock_matcher.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/internal/mock_gomock/mock_matcher.go#L44-L47
go
train
// Matches indicates an expected call of Matches
func (mr *MockMatcherMockRecorder) Matches(arg0 interface{}) *gomock.Call
// Matches indicates an expected call of 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) }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
gomock/internal/mock_gomock/mock_matcher.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/internal/mock_gomock/mock_matcher.go#L50-L55
go
train
// String mocks base method
func (m *MockMatcher) String() string
// String mocks base method func (m *MockMatcher) String() string
{ m.ctrl.T.Helper() ret := m.ctrl.Call(m, "String") ret0, _ := ret[0].(string) return ret0 }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
mockgen/parse.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/parse.go#L44-L108
go
train
// TODO: simplify error reporting
func parseFile(source string) (*model.Package, error)
// TODO: simplify error reporting func parseFile(source string) (*model.Package, error)
{ srcDir, err := filepath.Abs(filepath.Dir(source)) if err != nil { return nil, fmt.Errorf("failed getting source directory: %v", err) } cfg := &packages.Config{Mode: packages.LoadSyntax, Tests: true} pkgs, err := packages.Load(cfg, "file="+source) if err != nil { return nil, err } if packages.PrintErrors(pkgs) > 0 || len(pkgs) == 0 { return nil, errors.New("loading package failed") } packageImport := pkgs[0].PkgPath // It is illegal to import a _test package. packageImport = strings.TrimSuffix(packageImport, "_test") fs := token.NewFileSet() file, err := parser.ParseFile(fs, source, nil, 0) if err != nil { return nil, fmt.Errorf("failed parsing source file %v: %v", source, err) } p := &fileParser{ fileSet: fs, imports: make(map[string]string), importedInterfaces: make(map[string]map[string]*ast.InterfaceType), auxInterfaces: make(map[string]map[string]*ast.InterfaceType), srcDir: srcDir, } // Handle -imports. dotImports := make(map[string]bool) if *imports != "" { for _, kv := range strings.Split(*imports, ",") { eq := strings.Index(kv, "=") k, v := kv[:eq], kv[eq+1:] if k == "." { // TODO: Catch dupes? dotImports[v] = true } else { // TODO: Catch dupes? p.imports[k] = v } } } // Handle -aux_files. if err := p.parseAuxFiles(*auxFiles); err != nil { return nil, err } p.addAuxInterfacesFromFile(packageImport, file) // this file pkg, err := p.parseFile(packageImport, file) if err != nil { return nil, err } for path := range dotImports { pkg.DotImports = append(pkg.DotImports, path) } return pkg, nil }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
mockgen/parse.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/parse.go#L161-L193
go
train
// parseFile loads all file imports and auxiliary files import into the // fileParser, parses all file interfaces and returns package model.
func (p *fileParser) parseFile(importPath string, file *ast.File) (*model.Package, error)
// parseFile loads all file imports and auxiliary files import into the // fileParser, parses all file interfaces and returns package model. 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 }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
mockgen/parse.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/parse.go#L197-L220
go
train
// parsePackage loads package specified by path, parses it and populates // corresponding imports and importedInterfaces into the fileParser.
func (p *fileParser) parsePackage(path string) error
// parsePackage loads package specified by path, parses it and populates // corresponding imports and importedInterfaces into the fileParser. 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 }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
mockgen/parse.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/parse.go#L444-L481
go
train
// importsOfFile returns a map of package name to import path // of the imports in file.
func importsOfFile(file *ast.File) (normalImports map[string]string, dotImports []string)
// importsOfFile returns a map of package name to import path // of the imports in file. 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 }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
mockgen/parse.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/parse.go#L489-L513
go
train
// Create an iterator over all interfaces in file.
func iterInterfaces(file *ast.File) <-chan namedInterface
// Create an iterator over all interfaces in file. 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 }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
mockgen/parse.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/parse.go#L516-L523
go
train
// isVariadic returns whether the function is variadic.
func isVariadic(f *ast.FuncType) bool
// isVariadic returns whether the function is variadic. 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 }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
gomock/controller.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/controller.go#L118-L128
go
train
// NewController returns a new Controller. It is the preferred way to create a // Controller.
func NewController(t TestReporter) *Controller
// NewController returns a new Controller. It is the preferred way to create a // Controller. func NewController(t TestReporter) *Controller
{ h, ok := t.(TestHelper) if !ok { h = nopTestHelper{t} } return &Controller{ T: h, expectedCalls: newCallSet(), } }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
gomock/controller.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/controller.go#L145-L153
go
train
// WithContext returns a new Controller and a Context, which is cancelled on any // fatal failure.
func WithContext(ctx context.Context, t TestReporter) (*Controller, context.Context)
// WithContext returns a new Controller and a Context, which is cancelled on any // fatal failure. 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 }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
gomock/controller.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/controller.go#L162-L173
go
train
// RecordCall is called by a mock. It should not be called by user code.
func (ctrl *Controller) RecordCall(receiver interface{}, method string, args ...interface{}) *Call
// RecordCall is called by a mock. It should not be called by user code. 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") }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
gomock/controller.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/controller.go#L176-L186
go
train
// RecordCallWithMethodType is called by a mock. It should not be called by user code.
func (ctrl *Controller) RecordCallWithMethodType(receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call
// RecordCallWithMethodType is called by a mock. It should not be called by user code. 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 }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
gomock/controller.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/controller.go#L189-L227
go
train
// Call is called by a mock. It should not be called by user code.
func (ctrl *Controller) Call(receiver interface{}, method string, args ...interface{}) []interface{}
// Call is called by a mock. It should not be called by user code. 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 }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
gomock/controller.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/controller.go#L232-L257
go
train
// 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.
func (ctrl *Controller) Finish()
// 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. 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)") } }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
gomock/matchers.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/matchers.go#L125-L130
go
train
// Not reverses the results of its given child matcher. // // Example usage: // Not(Eq(5)).Matches(4) // returns true // Not(Eq(5)).Matches(5) // returns false
func Not(x interface{}) Matcher
// Not reverses the results of its given child matcher. // // Example usage: // Not(Eq(5)).Matches(4) // returns true // Not(Eq(5)).Matches(5) // returns false func Not(x interface{}) Matcher
{ if m, ok := x.(Matcher); ok { return notMatcher{m} } return notMatcher{Eq(x)} }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
mockgen/model/model.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/model/model.go#L44-L50
go
train
// Imports returns the imports needed by the Package as a set of import paths.
func (pkg *Package) Imports() map[string]bool
// Imports returns the imports needed by the Package as a set of import paths. func (pkg *Package) Imports() map[string]bool
{ im := make(map[string]bool) for _, intf := range pkg.Interfaces { intf.addImports(im) } return im }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
mockgen/model/model.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/model/model.go#L286-L309
go
train
// The following code is intended to be called by the program generated by ../reflect.go.
func InterfaceFromInterfaceType(it reflect.Type) (*Interface, error)
// The following code is intended to be called by the program generated by ../reflect.go. func InterfaceFromInterfaceType(it reflect.Type) (*Interface, error)
{ if it.Kind() != reflect.Interface { return nil, fmt.Errorf("%v is not an interface", it) } intf := &Interface{} for i := 0; i < it.NumMethod(); i++ { mt := it.Method(i) // TODO: need to skip unexported methods? or just raise an error? m := &Method{ Name: mt.Name, } var err error m.In, m.Variadic, m.Out, err = funcArgsFromType(mt.Type) if err != nil { return nil, err } intf.Methods = append(intf.Methods, m) } return intf, nil }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
mockgen/model/model.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/model/model.go#L312-L340
go
train
// t's Kind must be a reflect.Func.
func funcArgsFromType(t reflect.Type) (in []*Parameter, variadic *Parameter, out []*Parameter, err error)
// t's Kind must be a reflect.Func. 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 }
golang/mock
937870445b8bddd7f05ea90e81c58ebe83681534
mockgen/model/model.go
https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/model/model.go#L453-L461
go
train
// impPath sanitizes the package path returned by `PkgPath` method of a reflect Type so that // it is importable. PkgPath might return a path that includes "vendor". These paths do not // compile, so we need to remove everything up to and including "/vendor/". // See https://github.com/golang/go/issues/12019.
func impPath(imp string) string
// impPath sanitizes the package path returned by `PkgPath` method of a reflect Type so that // it is importable. PkgPath might return a path that includes "vendor". These paths do not // compile, so we need to remove everything up to and including "/vendor/". // See https://github.com/golang/go/issues/12019. func impPath(imp string) string
{ if strings.HasPrefix(imp, "vendor/") { imp = "/" + imp } if i := strings.LastIndex(imp, "/vendor/"); i != -1 { imp = imp[i+len("/vendor/"):] } return imp }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
metainfo/magnet.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/magnet.go#L35-L77
go
train
// ParseMagnetURI parses Magnet-formatted URIs into a Magnet instance
func ParseMagnetURI(uri string) (m Magnet, err error)
// ParseMagnetURI parses Magnet-formatted URIs into a Magnet instance 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 }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
metainfo/metainfo.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/metainfo.go#L25-L33
go
train
// Load a MetaInfo from an io.Reader. Returns a non-nil error in case of // failure.
func Load(r io.Reader) (*MetaInfo, error)
// Load a MetaInfo from an io.Reader. Returns a non-nil error in case of // failure. 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 }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
metainfo/metainfo.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/metainfo.go#L36-L43
go
train
// Convenience function for loading a MetaInfo from a file.
func LoadFromFile(filename string) (*MetaInfo, error)
// Convenience function for loading a MetaInfo from a file. func LoadFromFile(filename string) (*MetaInfo, error)
{ f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close() return Load(f) }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
metainfo/metainfo.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/metainfo.go#L55-L57
go
train
// Encode to bencoded form.
func (mi MetaInfo) Write(w io.Writer) error
// Encode to bencoded form. func (mi MetaInfo) Write(w io.Writer) error
{ return bencode.NewEncoder(w).Encode(mi) }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
metainfo/metainfo.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/metainfo.go#L60-L65
go
train
// Set good default values in preparation for creating a new MetaInfo file.
func (mi *MetaInfo) SetDefaults()
// Set good default values in preparation for creating a new MetaInfo file. func (mi *MetaInfo) SetDefaults()
{ mi.Comment = "yoloham" mi.CreatedBy = "github.com/anacrolix/torrent" mi.CreationDate = time.Now().Unix() // mi.Info.PieceLength = 256 * 1024 }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
metainfo/metainfo.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/metainfo.go#L68-L75
go
train
// Creates a Magnet from a MetaInfo.
func (mi *MetaInfo) Magnet(displayName string, infoHash Hash) (m Magnet)
// Creates a Magnet from a MetaInfo. 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 }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
metainfo/metainfo.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/metainfo.go#L79-L87
go
train
// Returns the announce list converted from the old single announce field if // necessary.
func (mi *MetaInfo) UpvertedAnnounceList() AnnounceList
// Returns the announce list converted from the old single announce field if // necessary. func (mi *MetaInfo) UpvertedAnnounceList() AnnounceList
{ if mi.AnnounceList.OverridesAnnounce(mi.Announce) { return mi.AnnounceList } if mi.Announce != "" { return [][]string{[]string{mi.Announce}} } return nil }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
cmd/torrent-pick/main.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/cmd/torrent-pick/main.go#L26-L39
go
train
// fmt.Fprintf(os.Stderr, "Usage: %s \n", os.Args[0])
func resolvedPeerAddrs(ss []string) (ret []torrent.Peer, err error)
// fmt.Fprintf(os.Stderr, "Usage: %s \n", os.Args[0]) func resolvedPeerAddrs(ss []string) (ret []torrent.Peer, err error)
{ for _, s := range ss { var addr *net.TCPAddr addr, err = net.ResolveTCPAddr("tcp", s) if err != nil { return } ret = append(ret, torrent.Peer{ IP: addr.IP, Port: addr.Port, }) } return }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
cmd/torrent-pick/main.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/cmd/torrent-pick/main.go#L51-L68
go
train
// Returns an estimate of the total bytes for all torrents.
func totalBytesEstimate(tc *torrent.Client) (ret int64)
// Returns an estimate of the total bytes for all torrents. 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 }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L137-L143
go
train
// Returns true if the connection is over IPv6.
func (cn *connection) ipv6() bool
// Returns true if the connection is over IPv6. func (cn *connection) ipv6() bool
{ ip := cn.remoteAddr.IP if ip.To4() != nil { return false } return len(ip) == net.IPv6len }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L147-L149
go
train
// Returns true the dialer has the lower client peer ID. TODO: Find the // specification for this.
func (cn *connection) isPreferredDirection() bool
// Returns true the dialer has the lower client peer ID. TODO: Find the // specification for this. func (cn *connection) isPreferredDirection() bool
{ return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L154-L160
go
train
// 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.
func (l *connection) hasPreferredNetworkOver(r *connection) (left, ok bool)
// 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. 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() }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L194-L199
go
train
// The best guess at number of pieces in the torrent for this peer.
func (cn *connection) bestPeerNumPieces() pieceIndex
// The best guess at number of pieces in the torrent for this peer. func (cn *connection) bestPeerNumPieces() pieceIndex
{ if cn.t.haveInfo() { return cn.t.numPieces() } return cn.peerMinPieces }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L212-L216
go
train
// Correct the PeerPieces slice length. Return false if the existing slice is // invalid, such as by receiving badly sized BITFIELD, or invalid HAVE // messages.
func (cn *connection) setNumPieces(num pieceIndex) error
// Correct the PeerPieces slice length. Return false if the existing slice is // invalid, such as by receiving badly sized BITFIELD, or invalid HAVE // messages. func (cn *connection) setNumPieces(num pieceIndex) error
{ cn.peerPieces.RemoveRange(bitmap.BitIndex(num), bitmap.ToEnd) cn.peerPiecesChanged() return nil }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L246-L266
go
train
// Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
func (cn *connection) statusFlags() (ret string)
// Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text. func (cn *connection) statusFlags() (ret string)
{ c := func(b byte) { ret += string([]byte{b}) } if cn.Interested { c('i') } if cn.Choked { c('c') } c('-') ret += cn.connectionFlags() c('-') if cn.PeerInterested { c('i') } if cn.PeerChoked { c('c') } return }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L274-L276
go
train
// func (cn *connection) String() string { // var buf bytes.Buffer // cn.WriteStatus(&buf, nil) // return buf.String() // }
func (cn *connection) downloadRate() float64
// func (cn *connection) String() string { // var buf bytes.Buffer // cn.WriteStatus(&buf, nil) // return buf.String() // } func (cn *connection) downloadRate() float64
{ return float64(cn.stats.BytesReadUsefulData.Int64()) / cn.cumInterest().Seconds() }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L330-L340
go
train
// Writes a message into the write buffer.
func (cn *connection) Post(msg pp.Message)
// Writes a message into the write buffer. 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() }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L375-L402
go
train
// The actual value to use as the maximum outbound requests.
func (cn *connection) nominalMaxRequests() (ret int)
// The actual value to use as the maximum outbound requests. 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())))) }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L482-L535
go
train
// Proxies the messageWriter's response.
func (cn *connection) request(r request, mw messageWriter) bool
// Proxies the messageWriter's response. 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, }) }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L593-L649
go
train
// 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.
func (cn *connection) writer(keepAliveTimeout time.Duration)
// 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. 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() } }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L684-L695
go
train
// 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.
func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func
// 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. 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 } } } }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L738-L752
go
train
// 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.
func (cn *connection) shouldRequestWithoutBias() bool
// 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. 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 }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L811-L813
go
train
// check callers updaterequests
func (cn *connection) stopRequestingPiece(piece pieceIndex) bool
// check callers updaterequests func (cn *connection) stopRequestingPiece(piece pieceIndex) bool
{ return cn.pieceRequestOrder.Remove(bitmap.BitIndex(piece)) }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L819-L843
go
train
// 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.
func (cn *connection) updatePiecePriority(piece pieceIndex) bool
// 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. 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() }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L962-L966
go
train
// After handshake, we know what Torrent and Client stats to include for a // connection.
func (cn *connection) postHandshakeStats(f func(*ConnStats))
// After handshake, we know what Torrent and Client stats to include for a // connection. func (cn *connection) postHandshakeStats(f func(*ConnStats))
{ t := cn.t f(&t.stats) f(&t.cl.stats) }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L971-L976
go
train
// 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.
func (cn *connection) allStats(f func(*ConnStats))
// 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. func (cn *connection) allStats(f func(*ConnStats))
{ f(&cn.stats) if cn.reconciledHandshakeStats { cn.postHandshakeStats(f) } }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L988-L1003
go
train
// 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.
func (c *connection) useful() bool
// 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. 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 }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L1068-L1180
go
train
// Processes incoming bittorrent messages. The client lock is held upon entry // and exit. Returning will end the connection.
func (c *connection) mainReadLoop() (err error)
// Processes incoming bittorrent messages. The client lock is held upon entry // and exit. Returning will end the connection. func (c *connection) mainReadLoop() (err error)
{ defer func() { if err != nil { torrent.Add("connection.mainReadLoop returned with error", 1) } else { torrent.Add("connection.mainReadLoop returned with no error", 1) } }() t := c.t cl := t.cl decoder := pp.Decoder{ R: bufio.NewReaderSize(c.r, 1<<17), MaxLength: 256 * 1024, Pool: t.chunkPool, } for { var msg pp.Message func() { cl.unlock() defer cl.lock() err = decoder.Decode(&msg) }() if t.closed.IsSet() || c.closed.IsSet() || err == io.EOF { return nil } if err != nil { return err } c.readMsg(&msg) c.lastMessageReceived = time.Now() if msg.Keepalive { receivedKeepalives.Add(1) continue } messageTypesReceived.Add(msg.Type.String(), 1) if msg.Type.FastExtension() && !c.fastEnabled() { return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type) } switch msg.Type { case pp.Choke: c.PeerChoked = true c.deleteAllRequests() // We can then reset our interest. c.updateRequests() c.updateExpectingChunks() case pp.Reject: c.deleteRequest(newRequestFromMessage(&msg)) delete(c.validReceiveChunks, newRequestFromMessage(&msg)) case pp.Unchoke: c.PeerChoked = false c.tickleWriter() c.updateExpectingChunks() case pp.Interested: c.PeerInterested = true c.tickleWriter() case pp.NotInterested: c.PeerInterested = false // We don't clear their requests since it isn't clear in the spec. // We'll probably choke them for this, which will clear them if // appropriate, and is clearly specified. case pp.Have: err = c.peerSentHave(pieceIndex(msg.Index)) case pp.Request: r := newRequestFromMessage(&msg) err = c.onReadRequest(r) case pp.Cancel: req := newRequestFromMessage(&msg) c.onPeerSentCancel(req) case pp.Bitfield: err = c.peerSentBitfield(msg.Bitfield) case pp.HaveAll: err = c.onPeerSentHaveAll() case pp.HaveNone: err = c.peerSentHaveNone() case pp.Piece: err = c.receiveChunk(&msg) if len(msg.Piece) == int(t.chunkSize) { t.chunkPool.Put(&msg.Piece) } if err != nil { err = fmt.Errorf("receiving chunk: %s", err) } case pp.Extended: err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload) case pp.Port: pingAddr := net.UDPAddr{ IP: c.remoteAddr.IP, Port: int(c.remoteAddr.Port), } if msg.Port != 0 { pingAddr.Port = int(msg.Port) } cl.eachDhtServer(func(s *dht.Server) { go s.Ping(&pingAddr, nil) }) case pp.AllowedFast: torrent.Add("allowed fasts received", 1) log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c, debugLogValue).Log(c.t.logger) c.peerAllowedFast.Add(int(msg.Index)) c.updateRequests() case pp.Suggest: torrent.Add("suggests received", 1) log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index, debugLogValue).Log(c.t.logger) c.updateRequests() default: err = fmt.Errorf("received unknown message type: %#v", msg.Type) } if err != nil { return err } } }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L1253-L1256
go
train
// Set both the Reader and Writer for the connection from a single ReadWriter.
func (cn *connection) setRW(rw io.ReadWriter)
// Set both the Reader and Writer for the connection from a single ReadWriter. func (cn *connection) setRW(rw io.ReadWriter)
{ cn.r = rw cn.w = rw }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L1259-L1264
go
train
// Returns the Reader and Writer as a combined ReadWriter.
func (cn *connection) rw() io.ReadWriter
// Returns the Reader and Writer as a combined ReadWriter. func (cn *connection) rw() io.ReadWriter
{ return struct { io.Reader io.Writer }{cn.r, cn.w} }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L1267-L1360
go
train
// Handle a received chunk from a peer.
func (c *connection) receiveChunk(msg *pp.Message) error
// Handle a received chunk from a peer. func (c *connection) receiveChunk(msg *pp.Message) error
{ t := c.t cl := t.cl torrent.Add("chunks received", 1) req := newRequestFromMessage(msg) if c.PeerChoked { torrent.Add("chunks received while choked", 1) } if _, ok := c.validReceiveChunks[req]; !ok { torrent.Add("chunks received unexpected", 1) return errors.New("received unexpected chunk") } delete(c.validReceiveChunks, req) if c.PeerChoked && c.peerAllowedFast.Get(int(req.Index)) { torrent.Add("chunks received due to allowed fast", 1) } // Request has been satisfied. if c.deleteRequest(req) { if c.expectingChunks() { c.chunksReceivedWhileExpecting++ } } else { torrent.Add("chunks received unwanted", 1) } // Do we actually want this chunk? if t.haveChunk(req) { torrent.Add("chunks received wasted", 1) c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted })) return nil } piece := &t.pieces[req.Index] c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful })) c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData })) c.lastUsefulChunkReceived = time.Now() // if t.fastestConn != c { // log.Printf("setting fastest connection %p", c) // } t.fastestConn = c // Need to record that it hasn't been written yet, before we attempt to do // anything with it. piece.incrementPendingWrites() // Record that we have the chunk, so we aren't trying to download it while // waiting for it to be written to storage. piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize)) // Cancel pending requests for this chunk. for c := range t.conns { c.postCancel(req) } err := func() error { cl.unlock() defer cl.lock() // Write the chunk out. Note that the upper bound on chunk writing // concurrency will be the number of connections. We write inline with // receiving the chunk (with this lock dance), because we want to // handle errors synchronously and I haven't thought of a nice way to // defer any concurrency to the storage and have that notify the // client of errors. TODO: Do that instead. return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece) }() piece.decrementPendingWrites() if err != nil { panic(fmt.Sprintf("error writing chunk: %v", err)) t.pendRequest(req) t.updatePieceCompletion(pieceIndex(msg.Index)) return nil } // It's important that the piece is potentially queued before we check if // the piece is still wanted, because if it is queued, it won't be wanted. if t.pieceAllDirty(pieceIndex(req.Index)) { t.queuePieceCheck(pieceIndex(req.Index)) t.pendAllChunkSpecs(pieceIndex(req.Index)) } c.onDirtiedPiece(pieceIndex(req.Index)) cl.event.Broadcast() t.publishPieceChange(pieceIndex(req.Index)) return nil }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
connection.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L1400-L1448
go
train
// Also handles choking and unchoking of the remote peer.
func (c *connection) upload(msg func(pp.Message) bool) bool
// Also handles choking and unchoking of the remote peer. 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) }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
iplist/iplist.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/iplist/iplist.go#L53-L78
go
train
// Return the range the given IP is in. ok if false if no range is found.
func (ipl *IPList) Lookup(ip net.IP) (r Range, ok bool)
// Return the range the given IP is in. ok if false if no range is found. 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 }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
iplist/iplist.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/iplist/iplist.go#L81-L103
go
train
// Return a range that contains ip, or nil.
func lookup( first func(i int) net.IP, full func(i int) Range, n int, ip net.IP, ) ( r Range, ok bool, )
// Return a range that contains ip, or nil. 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 }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
iplist/iplist.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/iplist/iplist.go#L106-L112
go
train
// Return the range the given IP is in. Returns nil if no range is found.
func (ipl *IPList) lookup(ip net.IP) (Range, bool)
// Return the range the given IP is in. Returns nil if no range is found. 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) }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
iplist/iplist.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/iplist/iplist.go#L124-L152
go
train
// Parse a line of the PeerGuardian Text Lists (P2P) Format. Returns !ok but // no error if a line doesn't contain a range but isn't erroneous, such as // comment and blank lines.
func ParseBlocklistP2PLine(l []byte) (r Range, ok bool, err error)
// Parse a line of the PeerGuardian Text Lists (P2P) Format. Returns !ok but // no error if a line doesn't contain a range but isn't erroneous, such as // comment and blank lines. func ParseBlocklistP2PLine(l []byte) (r Range, ok bool, err error)
{ l = bytes.TrimSpace(l) if len(l) == 0 || bytes.HasPrefix(l, []byte("#")) { return } // TODO: Check this when IPv6 blocklists are available. colon := bytes.LastIndexAny(l, ":") if colon == -1 { err = errors.New("missing colon") return } hyphen := bytes.IndexByte(l[colon+1:], '-') if hyphen == -1 { err = errors.New("missing hyphen") return } hyphen += colon + 1 r.Description = string(l[:colon]) r.First = net.ParseIP(string(l[colon+1 : hyphen])) minifyIP(&r.First) r.Last = net.ParseIP(string(l[hyphen+1:])) minifyIP(&r.Last) if r.First == nil || r.Last == nil || len(r.First) != len(r.Last) { err = errors.New("bad IP range") return } ok = true return }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
iplist/iplist.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/iplist/iplist.go#L155-L185
go
train
// Creates an IPList from a line-delimited P2P Plaintext file.
func NewFromReader(f io.Reader) (ret *IPList, err error)
// Creates an IPList from a line-delimited P2P Plaintext file. 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 }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
bencode/api.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/api.go#L115-L123
go
train
// Marshal the value 'v' to the bencode form, return the result as []byte and // an error if any.
func Marshal(v interface{}) ([]byte, error)
// Marshal the value 'v' to the bencode form, return the result as []byte and // an error if any. func Marshal(v interface{}) ([]byte, error)
{ var buf bytes.Buffer e := Encoder{w: &buf} err := e.Encode(v) if err != nil { return nil, err } return buf.Bytes(), nil }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
bencode/api.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/api.go#L133-L141
go
train
// Unmarshal the bencode value in the 'data' to a value pointed by the 'v' // pointer, return a non-nil error if any.
func Unmarshal(data []byte, v interface{}) (err error)
// Unmarshal the bencode value in the 'data' to a value pointed by the 'v' // pointer, return a non-nil error if any. 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 }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
reader.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/reader.go#L54-L57
go
train
// Don't wait for pieces to complete and be verified. Read calls return as // soon as they can when the underlying chunks become available.
func (r *reader) SetResponsive()
// Don't wait for pieces to complete and be verified. Read calls return as // soon as they can when the underlying chunks become available. func (r *reader) SetResponsive()
{ r.responsive = true r.t.cl.event.Broadcast() }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
reader.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/reader.go#L60-L63
go
train
// Disable responsive mode. TODO: Remove?
func (r *reader) SetNonResponsive()
// Disable responsive mode. TODO: Remove? func (r *reader) SetNonResponsive()
{ r.responsive = false r.t.cl.event.Broadcast() }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
reader.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/reader.go#L67-L74
go
train
// Configure the number of bytes ahead of a read that should also be // prioritized in preparation for further reads.
func (r *reader) SetReadahead(readahead int64)
// Configure the number of bytes ahead of a read that should also be // prioritized in preparation for further reads. 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() }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
reader.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/reader.go#L91-L111
go
train
// How many bytes are available to read. Max is the most we could require.
func (r *reader) available(off, max int64) (ret int64)
// How many bytes are available to read. Max is the most we could require. 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 }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
reader.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/reader.go#L121-L133
go
train
// Calculates the pieces this reader wants downloaded, ignoring the cached // value at r.pieces.
func (r *reader) piecesUncached() (ret pieceRange)
// Calculates the pieces this reader wants downloaded, ignoring the cached // value at r.pieces. 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 }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
reader.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/reader.go#L184-L191
go
train
// Wait until some data should be available to read. Tickles the client if it // isn't. Returns how much should be readable without blocking.
func (r *reader) waitAvailable(pos, wanted int64, ctxErr *error) (avail int64)
// Wait until some data should be available to read. Tickles the client if it // isn't. Returns how much should be readable without blocking. 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) }
anacrolix/torrent
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
reader.go
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/reader.go#L198-L234
go
train
// Performs at most one successful read to torrent storage.
func (r *reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error)
// Performs at most one successful read to torrent storage. 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() } }