repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1
value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
shiyanhui/dht | bencode.go | find | func find(data []byte, start int, target rune) (index int) {
index = bytes.IndexRune(data[start:], target)
if index != -1 {
return index + start
}
return index
} | go | func find(data []byte, start int, target rune) (index int) {
index = bytes.IndexRune(data[start:], target)
if index != -1 {
return index + start
}
return index
} | [
"func",
"find",
"(",
"data",
"[",
"]",
"byte",
",",
"start",
"int",
",",
"target",
"rune",
")",
"(",
"index",
"int",
")",
"{",
"index",
"=",
"bytes",
".",
"IndexRune",
"(",
"data",
"[",
"start",
":",
"]",
",",
"target",
")",
"\n",
"if",
"index",
... | // find returns the index of first target in data starting from `start`.
// It returns -1 if target not found. | [
"find",
"returns",
"the",
"index",
"of",
"first",
"target",
"in",
"data",
"starting",
"from",
"start",
".",
"It",
"returns",
"-",
"1",
"if",
"target",
"not",
"found",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/bencode.go#L14-L20 | train |
shiyanhui/dht | bencode.go | DecodeInt | func DecodeInt(data []byte, start int) (
result interface{}, index int, err error) {
if start >= len(data) || data[start] != 'i' {
err = errors.New("invalid int bencode")
return
}
index = find(data, start+1, 'e')
if index == -1 {
err = errors.New("':' not found when decode int")
return
}
result, err ... | go | func DecodeInt(data []byte, start int) (
result interface{}, index int, err error) {
if start >= len(data) || data[start] != 'i' {
err = errors.New("invalid int bencode")
return
}
index = find(data, start+1, 'e')
if index == -1 {
err = errors.New("':' not found when decode int")
return
}
result, err ... | [
"func",
"DecodeInt",
"(",
"data",
"[",
"]",
"byte",
",",
"start",
"int",
")",
"(",
"result",
"interface",
"{",
"}",
",",
"index",
"int",
",",
"err",
"error",
")",
"{",
"if",
"start",
">=",
"len",
"(",
"data",
")",
"||",
"data",
"[",
"start",
"]",... | // DecodeInt decodes int value in the data. | [
"DecodeInt",
"decodes",
"int",
"value",
"in",
"the",
"data",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/bencode.go#L60-L82 | train |
shiyanhui/dht | bencode.go | decodeItem | func decodeItem(data []byte, i int) (
result interface{}, index int, err error) {
var decodeFunc = []func([]byte, int) (interface{}, int, error){
DecodeString, DecodeInt, DecodeList, DecodeDict,
}
for _, f := range decodeFunc {
result, index, err = f(data, i)
if err == nil {
return
}
}
err = errors.... | go | func decodeItem(data []byte, i int) (
result interface{}, index int, err error) {
var decodeFunc = []func([]byte, int) (interface{}, int, error){
DecodeString, DecodeInt, DecodeList, DecodeDict,
}
for _, f := range decodeFunc {
result, index, err = f(data, i)
if err == nil {
return
}
}
err = errors.... | [
"func",
"decodeItem",
"(",
"data",
"[",
"]",
"byte",
",",
"i",
"int",
")",
"(",
"result",
"interface",
"{",
"}",
",",
"index",
"int",
",",
"err",
"error",
")",
"{",
"var",
"decodeFunc",
"=",
"[",
"]",
"func",
"(",
"[",
"]",
"byte",
",",
"int",
... | // decodeItem decodes an item of dict or list. | [
"decodeItem",
"decodes",
"an",
"item",
"of",
"dict",
"or",
"list",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/bencode.go#L85-L101 | train |
shiyanhui/dht | bencode.go | DecodeList | func DecodeList(data []byte, start int) (
result interface{}, index int, err error) {
if start >= len(data) || data[start] != 'l' {
err = errors.New("invalid list bencode")
return
}
var item interface{}
r := make([]interface{}, 0, 8)
index = start + 1
for index < len(data) {
char, _ := utf8.DecodeRune(d... | go | func DecodeList(data []byte, start int) (
result interface{}, index int, err error) {
if start >= len(data) || data[start] != 'l' {
err = errors.New("invalid list bencode")
return
}
var item interface{}
r := make([]interface{}, 0, 8)
index = start + 1
for index < len(data) {
char, _ := utf8.DecodeRune(d... | [
"func",
"DecodeList",
"(",
"data",
"[",
"]",
"byte",
",",
"start",
"int",
")",
"(",
"result",
"interface",
"{",
"}",
",",
"index",
"int",
",",
"err",
"error",
")",
"{",
"if",
"start",
">=",
"len",
"(",
"data",
")",
"||",
"data",
"[",
"start",
"]"... | // DecodeList decodes a list value. | [
"DecodeList",
"decodes",
"a",
"list",
"value",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/bencode.go#L104-L137 | train |
shiyanhui/dht | bencode.go | DecodeDict | func DecodeDict(data []byte, start int) (
result interface{}, index int, err error) {
if start >= len(data) || data[start] != 'd' {
err = errors.New("invalid dict bencode")
return
}
var item, key interface{}
r := make(map[string]interface{})
index = start + 1
for index < len(data) {
char, _ := utf8.Deco... | go | func DecodeDict(data []byte, start int) (
result interface{}, index int, err error) {
if start >= len(data) || data[start] != 'd' {
err = errors.New("invalid dict bencode")
return
}
var item, key interface{}
r := make(map[string]interface{})
index = start + 1
for index < len(data) {
char, _ := utf8.Deco... | [
"func",
"DecodeDict",
"(",
"data",
"[",
"]",
"byte",
",",
"start",
"int",
")",
"(",
"result",
"interface",
"{",
"}",
",",
"index",
"int",
",",
"err",
"error",
")",
"{",
"if",
"start",
">=",
"len",
"(",
"data",
")",
"||",
"data",
"[",
"start",
"]"... | // DecodeDict decodes a map value. | [
"DecodeDict",
"decodes",
"a",
"map",
"value",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/bencode.go#L140-L189 | train |
shiyanhui/dht | bencode.go | Decode | func Decode(data []byte) (result interface{}, err error) {
result, _, err = decodeItem(data, 0)
return
} | go | func Decode(data []byte) (result interface{}, err error) {
result, _, err = decodeItem(data, 0)
return
} | [
"func",
"Decode",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"result",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"result",
",",
"_",
",",
"err",
"=",
"decodeItem",
"(",
"data",
",",
"0",
")",
"\n",
"return",
"\n",
"}"
] | // Decode decodes a bencoded string to string, int, list or map. | [
"Decode",
"decodes",
"a",
"bencoded",
"string",
"to",
"string",
"int",
"list",
"or",
"map",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/bencode.go#L192-L195 | train |
shiyanhui/dht | bencode.go | EncodeString | func EncodeString(data string) string {
return strings.Join([]string{strconv.Itoa(len(data)), data}, ":")
} | go | func EncodeString(data string) string {
return strings.Join([]string{strconv.Itoa(len(data)), data}, ":")
} | [
"func",
"EncodeString",
"(",
"data",
"string",
")",
"string",
"{",
"return",
"strings",
".",
"Join",
"(",
"[",
"]",
"string",
"{",
"strconv",
".",
"Itoa",
"(",
"len",
"(",
"data",
")",
")",
",",
"data",
"}",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // EncodeString encodes a string value. | [
"EncodeString",
"encodes",
"a",
"string",
"value",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/bencode.go#L198-L200 | train |
shiyanhui/dht | bencode.go | EncodeInt | func EncodeInt(data int) string {
return strings.Join([]string{"i", strconv.Itoa(data), "e"}, "")
} | go | func EncodeInt(data int) string {
return strings.Join([]string{"i", strconv.Itoa(data), "e"}, "")
} | [
"func",
"EncodeInt",
"(",
"data",
"int",
")",
"string",
"{",
"return",
"strings",
".",
"Join",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"strconv",
".",
"Itoa",
"(",
"data",
")",
",",
"\"",
"\"",
"}",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // EncodeInt encodes a int value. | [
"EncodeInt",
"encodes",
"a",
"int",
"value",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/bencode.go#L203-L205 | train |
shiyanhui/dht | bencode.go | encodeItem | func encodeItem(data interface{}) (item string) {
switch v := data.(type) {
case string:
item = EncodeString(v)
case int:
item = EncodeInt(v)
case []interface{}:
item = EncodeList(v)
case map[string]interface{}:
item = EncodeDict(v)
default:
panic("invalid type when encode item")
}
return
} | go | func encodeItem(data interface{}) (item string) {
switch v := data.(type) {
case string:
item = EncodeString(v)
case int:
item = EncodeInt(v)
case []interface{}:
item = EncodeList(v)
case map[string]interface{}:
item = EncodeDict(v)
default:
panic("invalid type when encode item")
}
return
} | [
"func",
"encodeItem",
"(",
"data",
"interface",
"{",
"}",
")",
"(",
"item",
"string",
")",
"{",
"switch",
"v",
":=",
"data",
".",
"(",
"type",
")",
"{",
"case",
"string",
":",
"item",
"=",
"EncodeString",
"(",
"v",
")",
"\n",
"case",
"int",
":",
... | // EncodeItem encodes an item of dict or list. | [
"EncodeItem",
"encodes",
"an",
"item",
"of",
"dict",
"or",
"list",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/bencode.go#L208-L222 | train |
shiyanhui/dht | bencode.go | EncodeList | func EncodeList(data []interface{}) string {
result := make([]string, len(data))
for i, item := range data {
result[i] = encodeItem(item)
}
return strings.Join([]string{"l", strings.Join(result, ""), "e"}, "")
} | go | func EncodeList(data []interface{}) string {
result := make([]string, len(data))
for i, item := range data {
result[i] = encodeItem(item)
}
return strings.Join([]string{"l", strings.Join(result, ""), "e"}, "")
} | [
"func",
"EncodeList",
"(",
"data",
"[",
"]",
"interface",
"{",
"}",
")",
"string",
"{",
"result",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"data",
")",
")",
"\n\n",
"for",
"i",
",",
"item",
":=",
"range",
"data",
"{",
"result",
"["... | // EncodeList encodes a list value. | [
"EncodeList",
"encodes",
"a",
"list",
"value",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/bencode.go#L225-L233 | train |
shiyanhui/dht | bencode.go | EncodeDict | func EncodeDict(data map[string]interface{}) string {
result, i := make([]string, len(data)), 0
for key, val := range data {
result[i] = strings.Join(
[]string{EncodeString(key), encodeItem(val)},
"")
i++
}
return strings.Join([]string{"d", strings.Join(result, ""), "e"}, "")
} | go | func EncodeDict(data map[string]interface{}) string {
result, i := make([]string, len(data)), 0
for key, val := range data {
result[i] = strings.Join(
[]string{EncodeString(key), encodeItem(val)},
"")
i++
}
return strings.Join([]string{"d", strings.Join(result, ""), "e"}, "")
} | [
"func",
"EncodeDict",
"(",
"data",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"string",
"{",
"result",
",",
"i",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"data",
")",
")",
",",
"0",
"\n\n",
"for",
"key",
",",
"val",
"... | // EncodeDict encodes a dict value. | [
"EncodeDict",
"encodes",
"a",
"dict",
"value",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/bencode.go#L236-L247 | train |
shiyanhui/dht | bencode.go | Encode | func Encode(data interface{}) string {
switch v := data.(type) {
case string:
return EncodeString(v)
case int:
return EncodeInt(v)
case []interface{}:
return EncodeList(v)
case map[string]interface{}:
return EncodeDict(v)
default:
panic("invalid type when encode")
}
} | go | func Encode(data interface{}) string {
switch v := data.(type) {
case string:
return EncodeString(v)
case int:
return EncodeInt(v)
case []interface{}:
return EncodeList(v)
case map[string]interface{}:
return EncodeDict(v)
default:
panic("invalid type when encode")
}
} | [
"func",
"Encode",
"(",
"data",
"interface",
"{",
"}",
")",
"string",
"{",
"switch",
"v",
":=",
"data",
".",
"(",
"type",
")",
"{",
"case",
"string",
":",
"return",
"EncodeString",
"(",
"v",
")",
"\n",
"case",
"int",
":",
"return",
"EncodeInt",
"(",
... | // Encode encodes a string, int, dict or list value to a bencoded string. | [
"Encode",
"encodes",
"a",
"string",
"int",
"dict",
"or",
"list",
"value",
"to",
"a",
"bencoded",
"string",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/bencode.go#L250-L263 | train |
shiyanhui/dht | container.go | Get | func (smap *syncedMap) Get(key interface{}) (val interface{}, ok bool) {
smap.RLock()
defer smap.RUnlock()
val, ok = smap.data[key]
return
} | go | func (smap *syncedMap) Get(key interface{}) (val interface{}, ok bool) {
smap.RLock()
defer smap.RUnlock()
val, ok = smap.data[key]
return
} | [
"func",
"(",
"smap",
"*",
"syncedMap",
")",
"Get",
"(",
"key",
"interface",
"{",
"}",
")",
"(",
"val",
"interface",
"{",
"}",
",",
"ok",
"bool",
")",
"{",
"smap",
".",
"RLock",
"(",
")",
"\n",
"defer",
"smap",
".",
"RUnlock",
"(",
")",
"\n\n",
... | // Get returns the value mapped to key. | [
"Get",
"returns",
"the",
"value",
"mapped",
"to",
"key",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L28-L34 | train |
shiyanhui/dht | container.go | Has | func (smap *syncedMap) Has(key interface{}) bool {
_, ok := smap.Get(key)
return ok
} | go | func (smap *syncedMap) Has(key interface{}) bool {
_, ok := smap.Get(key)
return ok
} | [
"func",
"(",
"smap",
"*",
"syncedMap",
")",
"Has",
"(",
"key",
"interface",
"{",
"}",
")",
"bool",
"{",
"_",
",",
"ok",
":=",
"smap",
".",
"Get",
"(",
"key",
")",
"\n",
"return",
"ok",
"\n",
"}"
] | // Has returns whether the syncedMap contains the key. | [
"Has",
"returns",
"whether",
"the",
"syncedMap",
"contains",
"the",
"key",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L37-L40 | train |
shiyanhui/dht | container.go | Delete | func (smap *syncedMap) Delete(key interface{}) {
smap.Lock()
defer smap.Unlock()
delete(smap.data, key)
} | go | func (smap *syncedMap) Delete(key interface{}) {
smap.Lock()
defer smap.Unlock()
delete(smap.data, key)
} | [
"func",
"(",
"smap",
"*",
"syncedMap",
")",
"Delete",
"(",
"key",
"interface",
"{",
"}",
")",
"{",
"smap",
".",
"Lock",
"(",
")",
"\n",
"defer",
"smap",
".",
"Unlock",
"(",
")",
"\n\n",
"delete",
"(",
"smap",
".",
"data",
",",
"key",
")",
"\n",
... | // Delete deletes the key in the map. | [
"Delete",
"deletes",
"the",
"key",
"in",
"the",
"map",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L51-L56 | train |
shiyanhui/dht | container.go | DeleteMulti | func (smap *syncedMap) DeleteMulti(keys []interface{}) {
smap.Lock()
defer smap.Unlock()
for _, key := range keys {
delete(smap.data, key)
}
} | go | func (smap *syncedMap) DeleteMulti(keys []interface{}) {
smap.Lock()
defer smap.Unlock()
for _, key := range keys {
delete(smap.data, key)
}
} | [
"func",
"(",
"smap",
"*",
"syncedMap",
")",
"DeleteMulti",
"(",
"keys",
"[",
"]",
"interface",
"{",
"}",
")",
"{",
"smap",
".",
"Lock",
"(",
")",
"\n",
"defer",
"smap",
".",
"Unlock",
"(",
")",
"\n\n",
"for",
"_",
",",
"key",
":=",
"range",
"keys... | // DeleteMulti deletes keys in batch. | [
"DeleteMulti",
"deletes",
"keys",
"in",
"batch",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L59-L66 | train |
shiyanhui/dht | container.go | Clear | func (smap *syncedMap) Clear() {
smap.Lock()
defer smap.Unlock()
smap.data = make(map[interface{}]interface{})
} | go | func (smap *syncedMap) Clear() {
smap.Lock()
defer smap.Unlock()
smap.data = make(map[interface{}]interface{})
} | [
"func",
"(",
"smap",
"*",
"syncedMap",
")",
"Clear",
"(",
")",
"{",
"smap",
".",
"Lock",
"(",
")",
"\n",
"defer",
"smap",
".",
"Unlock",
"(",
")",
"\n\n",
"smap",
".",
"data",
"=",
"make",
"(",
"map",
"[",
"interface",
"{",
"}",
"]",
"interface",... | // Clear resets the data. | [
"Clear",
"resets",
"the",
"data",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L69-L74 | train |
shiyanhui/dht | container.go | Iter | func (smap *syncedMap) Iter() <-chan mapItem {
ch := make(chan mapItem)
go func() {
smap.RLock()
for key, val := range smap.data {
ch <- mapItem{
key: key,
val: val,
}
}
smap.RUnlock()
close(ch)
}()
return ch
} | go | func (smap *syncedMap) Iter() <-chan mapItem {
ch := make(chan mapItem)
go func() {
smap.RLock()
for key, val := range smap.data {
ch <- mapItem{
key: key,
val: val,
}
}
smap.RUnlock()
close(ch)
}()
return ch
} | [
"func",
"(",
"smap",
"*",
"syncedMap",
")",
"Iter",
"(",
")",
"<-",
"chan",
"mapItem",
"{",
"ch",
":=",
"make",
"(",
"chan",
"mapItem",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"smap",
".",
"RLock",
"(",
")",
"\n",
"for",
"key",
",",
"val",
":="... | // Iter returns a chan which output all items. | [
"Iter",
"returns",
"a",
"chan",
"which",
"output",
"all",
"items",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L77-L91 | train |
shiyanhui/dht | container.go | Len | func (smap *syncedMap) Len() int {
smap.RLock()
defer smap.RUnlock()
return len(smap.data)
} | go | func (smap *syncedMap) Len() int {
smap.RLock()
defer smap.RUnlock()
return len(smap.data)
} | [
"func",
"(",
"smap",
"*",
"syncedMap",
")",
"Len",
"(",
")",
"int",
"{",
"smap",
".",
"RLock",
"(",
")",
"\n",
"defer",
"smap",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"len",
"(",
"smap",
".",
"data",
")",
"\n",
"}"
] | // Len returns the length of syncedMap. | [
"Len",
"returns",
"the",
"length",
"of",
"syncedMap",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L94-L99 | train |
shiyanhui/dht | container.go | Front | func (slist *syncedList) Front() *list.Element {
slist.RLock()
defer slist.RUnlock()
return slist.queue.Front()
} | go | func (slist *syncedList) Front() *list.Element {
slist.RLock()
defer slist.RUnlock()
return slist.queue.Front()
} | [
"func",
"(",
"slist",
"*",
"syncedList",
")",
"Front",
"(",
")",
"*",
"list",
".",
"Element",
"{",
"slist",
".",
"RLock",
"(",
")",
"\n",
"defer",
"slist",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"slist",
".",
"queue",
".",
"Front",
"(",
")",
... | // Front returns the first element of slist. | [
"Front",
"returns",
"the",
"first",
"element",
"of",
"slist",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L116-L121 | train |
shiyanhui/dht | container.go | Back | func (slist *syncedList) Back() *list.Element {
slist.RLock()
defer slist.RUnlock()
return slist.queue.Back()
} | go | func (slist *syncedList) Back() *list.Element {
slist.RLock()
defer slist.RUnlock()
return slist.queue.Back()
} | [
"func",
"(",
"slist",
"*",
"syncedList",
")",
"Back",
"(",
")",
"*",
"list",
".",
"Element",
"{",
"slist",
".",
"RLock",
"(",
")",
"\n",
"defer",
"slist",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"slist",
".",
"queue",
".",
"Back",
"(",
")",
"... | // Back returns the last element of slist. | [
"Back",
"returns",
"the",
"last",
"element",
"of",
"slist",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L124-L129 | train |
shiyanhui/dht | container.go | PushFront | func (slist *syncedList) PushFront(v interface{}) *list.Element {
slist.Lock()
defer slist.Unlock()
return slist.queue.PushFront(v)
} | go | func (slist *syncedList) PushFront(v interface{}) *list.Element {
slist.Lock()
defer slist.Unlock()
return slist.queue.PushFront(v)
} | [
"func",
"(",
"slist",
"*",
"syncedList",
")",
"PushFront",
"(",
"v",
"interface",
"{",
"}",
")",
"*",
"list",
".",
"Element",
"{",
"slist",
".",
"Lock",
"(",
")",
"\n",
"defer",
"slist",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"slist",
".",
"que... | // PushFront pushs an element to the head of slist. | [
"PushFront",
"pushs",
"an",
"element",
"to",
"the",
"head",
"of",
"slist",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L132-L137 | train |
shiyanhui/dht | container.go | InsertBefore | func (slist *syncedList) InsertBefore(
v interface{}, mark *list.Element) *list.Element {
slist.Lock()
defer slist.Unlock()
return slist.queue.InsertBefore(v, mark)
} | go | func (slist *syncedList) InsertBefore(
v interface{}, mark *list.Element) *list.Element {
slist.Lock()
defer slist.Unlock()
return slist.queue.InsertBefore(v, mark)
} | [
"func",
"(",
"slist",
"*",
"syncedList",
")",
"InsertBefore",
"(",
"v",
"interface",
"{",
"}",
",",
"mark",
"*",
"list",
".",
"Element",
")",
"*",
"list",
".",
"Element",
"{",
"slist",
".",
"Lock",
"(",
")",
"\n",
"defer",
"slist",
".",
"Unlock",
"... | // InsertBefore inserts v before mark. | [
"InsertBefore",
"inserts",
"v",
"before",
"mark",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L148-L155 | train |
shiyanhui/dht | container.go | Remove | func (slist *syncedList) Remove(e *list.Element) interface{} {
slist.Lock()
defer slist.Unlock()
return slist.queue.Remove(e)
} | go | func (slist *syncedList) Remove(e *list.Element) interface{} {
slist.Lock()
defer slist.Unlock()
return slist.queue.Remove(e)
} | [
"func",
"(",
"slist",
"*",
"syncedList",
")",
"Remove",
"(",
"e",
"*",
"list",
".",
"Element",
")",
"interface",
"{",
"}",
"{",
"slist",
".",
"Lock",
"(",
")",
"\n",
"defer",
"slist",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"slist",
".",
"queue"... | // Remove removes e from the slist. | [
"Remove",
"removes",
"e",
"from",
"the",
"slist",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L168-L173 | train |
shiyanhui/dht | container.go | Clear | func (slist *syncedList) Clear() {
slist.Lock()
defer slist.Unlock()
slist.queue.Init()
} | go | func (slist *syncedList) Clear() {
slist.Lock()
defer slist.Unlock()
slist.queue.Init()
} | [
"func",
"(",
"slist",
"*",
"syncedList",
")",
"Clear",
"(",
")",
"{",
"slist",
".",
"Lock",
"(",
")",
"\n",
"defer",
"slist",
".",
"Unlock",
"(",
")",
"\n\n",
"slist",
".",
"queue",
".",
"Init",
"(",
")",
"\n",
"}"
] | // Clear resets the list queue. | [
"Clear",
"resets",
"the",
"list",
"queue",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L176-L181 | train |
shiyanhui/dht | container.go | Len | func (slist *syncedList) Len() int {
slist.RLock()
defer slist.RUnlock()
return slist.queue.Len()
} | go | func (slist *syncedList) Len() int {
slist.RLock()
defer slist.RUnlock()
return slist.queue.Len()
} | [
"func",
"(",
"slist",
"*",
"syncedList",
")",
"Len",
"(",
")",
"int",
"{",
"slist",
".",
"RLock",
"(",
")",
"\n",
"defer",
"slist",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"slist",
".",
"queue",
".",
"Len",
"(",
")",
"\n",
"}"
] | // Len returns length of the slist. | [
"Len",
"returns",
"length",
"of",
"the",
"slist",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L184-L189 | train |
shiyanhui/dht | container.go | Iter | func (slist *syncedList) Iter() <-chan *list.Element {
ch := make(chan *list.Element)
go func() {
slist.RLock()
for e := slist.queue.Front(); e != nil; e = e.Next() {
ch <- e
}
slist.RUnlock()
close(ch)
}()
return ch
} | go | func (slist *syncedList) Iter() <-chan *list.Element {
ch := make(chan *list.Element)
go func() {
slist.RLock()
for e := slist.queue.Front(); e != nil; e = e.Next() {
ch <- e
}
slist.RUnlock()
close(ch)
}()
return ch
} | [
"func",
"(",
"slist",
"*",
"syncedList",
")",
"Iter",
"(",
")",
"<-",
"chan",
"*",
"list",
".",
"Element",
"{",
"ch",
":=",
"make",
"(",
"chan",
"*",
"list",
".",
"Element",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"slist",
".",
"RLock",
"(",
")... | // Iter returns a chan which output all elements. | [
"Iter",
"returns",
"a",
"chan",
"which",
"output",
"all",
"elements",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L192-L203 | train |
shiyanhui/dht | container.go | newKeyedDeque | func newKeyedDeque() *keyedDeque {
return &keyedDeque{
RWMutex: &sync.RWMutex{},
syncedList: newSyncedList(),
index: make(map[interface{}]*list.Element),
invertedIndex: make(map[*list.Element]interface{}),
}
} | go | func newKeyedDeque() *keyedDeque {
return &keyedDeque{
RWMutex: &sync.RWMutex{},
syncedList: newSyncedList(),
index: make(map[interface{}]*list.Element),
invertedIndex: make(map[*list.Element]interface{}),
}
} | [
"func",
"newKeyedDeque",
"(",
")",
"*",
"keyedDeque",
"{",
"return",
"&",
"keyedDeque",
"{",
"RWMutex",
":",
"&",
"sync",
".",
"RWMutex",
"{",
"}",
",",
"syncedList",
":",
"newSyncedList",
"(",
")",
",",
"index",
":",
"make",
"(",
"map",
"[",
"interfac... | // newKeyedDeque returns a newKeyedDeque pointer. | [
"newKeyedDeque",
"returns",
"a",
"newKeyedDeque",
"pointer",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L214-L221 | train |
shiyanhui/dht | container.go | Push | func (deque *keyedDeque) Push(key interface{}, val interface{}) {
deque.Lock()
defer deque.Unlock()
if e, ok := deque.index[key]; ok {
deque.syncedList.Remove(e)
}
deque.index[key] = deque.syncedList.PushBack(val)
deque.invertedIndex[deque.index[key]] = key
} | go | func (deque *keyedDeque) Push(key interface{}, val interface{}) {
deque.Lock()
defer deque.Unlock()
if e, ok := deque.index[key]; ok {
deque.syncedList.Remove(e)
}
deque.index[key] = deque.syncedList.PushBack(val)
deque.invertedIndex[deque.index[key]] = key
} | [
"func",
"(",
"deque",
"*",
"keyedDeque",
")",
"Push",
"(",
"key",
"interface",
"{",
"}",
",",
"val",
"interface",
"{",
"}",
")",
"{",
"deque",
".",
"Lock",
"(",
")",
"\n",
"defer",
"deque",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"e",
",",
"ok",
... | // Push pushs a keyed-value to the end of deque. | [
"Push",
"pushs",
"a",
"keyed",
"-",
"value",
"to",
"the",
"end",
"of",
"deque",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L224-L233 | train |
shiyanhui/dht | container.go | Get | func (deque *keyedDeque) Get(key interface{}) (*list.Element, bool) {
deque.RLock()
defer deque.RUnlock()
v, ok := deque.index[key]
return v, ok
} | go | func (deque *keyedDeque) Get(key interface{}) (*list.Element, bool) {
deque.RLock()
defer deque.RUnlock()
v, ok := deque.index[key]
return v, ok
} | [
"func",
"(",
"deque",
"*",
"keyedDeque",
")",
"Get",
"(",
"key",
"interface",
"{",
"}",
")",
"(",
"*",
"list",
".",
"Element",
",",
"bool",
")",
"{",
"deque",
".",
"RLock",
"(",
")",
"\n",
"defer",
"deque",
".",
"RUnlock",
"(",
")",
"\n\n",
"v",
... | // Get returns the keyed value. | [
"Get",
"returns",
"the",
"keyed",
"value",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L236-L242 | train |
shiyanhui/dht | container.go | HasKey | func (deque *keyedDeque) HasKey(key interface{}) bool {
_, ok := deque.Get(key)
return ok
} | go | func (deque *keyedDeque) HasKey(key interface{}) bool {
_, ok := deque.Get(key)
return ok
} | [
"func",
"(",
"deque",
"*",
"keyedDeque",
")",
"HasKey",
"(",
"key",
"interface",
"{",
"}",
")",
"bool",
"{",
"_",
",",
"ok",
":=",
"deque",
".",
"Get",
"(",
"key",
")",
"\n",
"return",
"ok",
"\n",
"}"
] | // Has returns whether key already exists. | [
"Has",
"returns",
"whether",
"key",
"already",
"exists",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L245-L248 | train |
shiyanhui/dht | container.go | Delete | func (deque *keyedDeque) Delete(key interface{}) (v interface{}) {
deque.RLock()
e, ok := deque.index[key]
deque.RUnlock()
deque.Lock()
defer deque.Unlock()
if ok {
v = deque.syncedList.Remove(e)
delete(deque.index, key)
delete(deque.invertedIndex, e)
}
return
} | go | func (deque *keyedDeque) Delete(key interface{}) (v interface{}) {
deque.RLock()
e, ok := deque.index[key]
deque.RUnlock()
deque.Lock()
defer deque.Unlock()
if ok {
v = deque.syncedList.Remove(e)
delete(deque.index, key)
delete(deque.invertedIndex, e)
}
return
} | [
"func",
"(",
"deque",
"*",
"keyedDeque",
")",
"Delete",
"(",
"key",
"interface",
"{",
"}",
")",
"(",
"v",
"interface",
"{",
"}",
")",
"{",
"deque",
".",
"RLock",
"(",
")",
"\n",
"e",
",",
"ok",
":=",
"deque",
".",
"index",
"[",
"key",
"]",
"\n"... | // Delete deletes a value named key. | [
"Delete",
"deletes",
"a",
"value",
"named",
"key",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L251-L266 | train |
shiyanhui/dht | container.go | Remove | func (deque *keyedDeque) Remove(e *list.Element) (v interface{}) {
deque.RLock()
key, ok := deque.invertedIndex[e]
deque.RUnlock()
if ok {
v = deque.Delete(key)
}
return
} | go | func (deque *keyedDeque) Remove(e *list.Element) (v interface{}) {
deque.RLock()
key, ok := deque.invertedIndex[e]
deque.RUnlock()
if ok {
v = deque.Delete(key)
}
return
} | [
"func",
"(",
"deque",
"*",
"keyedDeque",
")",
"Remove",
"(",
"e",
"*",
"list",
".",
"Element",
")",
"(",
"v",
"interface",
"{",
"}",
")",
"{",
"deque",
".",
"RLock",
"(",
")",
"\n",
"key",
",",
"ok",
":=",
"deque",
".",
"invertedIndex",
"[",
"e",... | // Removes overwrites list.List.Remove. | [
"Removes",
"overwrites",
"list",
".",
"List",
".",
"Remove",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L269-L279 | train |
shiyanhui/dht | container.go | Clear | func (deque *keyedDeque) Clear() {
deque.Lock()
defer deque.Unlock()
deque.syncedList.Clear()
deque.index = make(map[interface{}]*list.Element)
deque.invertedIndex = make(map[*list.Element]interface{})
} | go | func (deque *keyedDeque) Clear() {
deque.Lock()
defer deque.Unlock()
deque.syncedList.Clear()
deque.index = make(map[interface{}]*list.Element)
deque.invertedIndex = make(map[*list.Element]interface{})
} | [
"func",
"(",
"deque",
"*",
"keyedDeque",
")",
"Clear",
"(",
")",
"{",
"deque",
".",
"Lock",
"(",
")",
"\n",
"defer",
"deque",
".",
"Unlock",
"(",
")",
"\n\n",
"deque",
".",
"syncedList",
".",
"Clear",
"(",
")",
"\n",
"deque",
".",
"index",
"=",
"... | // Clear resets the deque. | [
"Clear",
"resets",
"the",
"deque",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/container.go#L282-L289 | train |
shiyanhui/dht | dht.go | NewStandardConfig | func NewStandardConfig() *Config {
return &Config{
K: 8,
KBucketSize: 8,
Network: "udp4",
Address: ":6881",
PrimeNodes: []string{
"router.bittorrent.com:6881",
"router.utorrent.com:6881",
"dht.transmissionbt.com:6881",
},
NodeExpriedAfter: time.Duration(time.Minute * 15),
... | go | func NewStandardConfig() *Config {
return &Config{
K: 8,
KBucketSize: 8,
Network: "udp4",
Address: ":6881",
PrimeNodes: []string{
"router.bittorrent.com:6881",
"router.utorrent.com:6881",
"dht.transmissionbt.com:6881",
},
NodeExpriedAfter: time.Duration(time.Minute * 15),
... | [
"func",
"NewStandardConfig",
"(",
")",
"*",
"Config",
"{",
"return",
"&",
"Config",
"{",
"K",
":",
"8",
",",
"KBucketSize",
":",
"8",
",",
"Network",
":",
"\"",
"\"",
",",
"Address",
":",
"\"",
"\"",
",",
"PrimeNodes",
":",
"[",
"]",
"string",
"{",... | // NewStandardConfig returns a Config pointer with default values. | [
"NewStandardConfig",
"returns",
"a",
"Config",
"pointer",
"with",
"default",
"values",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/dht.go#L76-L101 | train |
shiyanhui/dht | dht.go | NewCrawlConfig | func NewCrawlConfig() *Config {
config := NewStandardConfig()
config.NodeExpriedAfter = 0
config.KBucketExpiredAfter = 0
config.CheckKBucketPeriod = time.Second * 5
config.KBucketSize = math.MaxInt32
config.Mode = CrawlMode
config.RefreshNodeNum = 256
return config
} | go | func NewCrawlConfig() *Config {
config := NewStandardConfig()
config.NodeExpriedAfter = 0
config.KBucketExpiredAfter = 0
config.CheckKBucketPeriod = time.Second * 5
config.KBucketSize = math.MaxInt32
config.Mode = CrawlMode
config.RefreshNodeNum = 256
return config
} | [
"func",
"NewCrawlConfig",
"(",
")",
"*",
"Config",
"{",
"config",
":=",
"NewStandardConfig",
"(",
")",
"\n",
"config",
".",
"NodeExpriedAfter",
"=",
"0",
"\n",
"config",
".",
"KBucketExpiredAfter",
"=",
"0",
"\n",
"config",
".",
"CheckKBucketPeriod",
"=",
"t... | // NewCrawlConfig returns a config in crawling mode. | [
"NewCrawlConfig",
"returns",
"a",
"config",
"in",
"crawling",
"mode",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/dht.go#L104-L114 | train |
shiyanhui/dht | dht.go | New | func New(config *Config) *DHT {
if config == nil {
config = NewStandardConfig()
}
node, err := newNode(randomString(20), config.Network, config.Address)
if err != nil {
panic(err)
}
d := &DHT{
Config: config,
node: node,
blackList: newBlackList(config.BlackListMaxSize),
packets: ... | go | func New(config *Config) *DHT {
if config == nil {
config = NewStandardConfig()
}
node, err := newNode(randomString(20), config.Network, config.Address)
if err != nil {
panic(err)
}
d := &DHT{
Config: config,
node: node,
blackList: newBlackList(config.BlackListMaxSize),
packets: ... | [
"func",
"New",
"(",
"config",
"*",
"Config",
")",
"*",
"DHT",
"{",
"if",
"config",
"==",
"nil",
"{",
"config",
"=",
"NewStandardConfig",
"(",
")",
"\n",
"}",
"\n\n",
"node",
",",
"err",
":=",
"newNode",
"(",
"randomString",
"(",
"20",
")",
",",
"co... | // New returns a DHT pointer. If config is nil, then config will be set to
// the default config. | [
"New",
"returns",
"a",
"DHT",
"pointer",
".",
"If",
"config",
"is",
"nil",
"then",
"config",
"will",
"be",
"set",
"to",
"the",
"default",
"config",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/dht.go#L133-L167 | train |
shiyanhui/dht | dht.go | init | func (dht *DHT) init() {
listener, err := net.ListenPacket(dht.Network, dht.Address)
if err != nil {
panic(err)
}
dht.conn = listener.(*net.UDPConn)
dht.routingTable = newRoutingTable(dht.KBucketSize, dht)
dht.peersManager = newPeersManager(dht)
dht.tokenManager = newTokenManager(dht.TokenExpiredAfter, dht)
... | go | func (dht *DHT) init() {
listener, err := net.ListenPacket(dht.Network, dht.Address)
if err != nil {
panic(err)
}
dht.conn = listener.(*net.UDPConn)
dht.routingTable = newRoutingTable(dht.KBucketSize, dht)
dht.peersManager = newPeersManager(dht)
dht.tokenManager = newTokenManager(dht.TokenExpiredAfter, dht)
... | [
"func",
"(",
"dht",
"*",
"DHT",
")",
"init",
"(",
")",
"{",
"listener",
",",
"err",
":=",
"net",
".",
"ListenPacket",
"(",
"dht",
".",
"Network",
",",
"dht",
".",
"Address",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\... | // init initializes global varables. | [
"init",
"initializes",
"global",
"varables",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/dht.go#L180-L196 | train |
shiyanhui/dht | dht.go | join | func (dht *DHT) join() {
for _, addr := range dht.PrimeNodes {
raddr, err := net.ResolveUDPAddr(dht.Network, addr)
if err != nil {
continue
}
// NOTE: Temporary node has NOT node id.
dht.transactionManager.findNode(
&node{addr: raddr},
dht.node.id.RawString(),
)
}
} | go | func (dht *DHT) join() {
for _, addr := range dht.PrimeNodes {
raddr, err := net.ResolveUDPAddr(dht.Network, addr)
if err != nil {
continue
}
// NOTE: Temporary node has NOT node id.
dht.transactionManager.findNode(
&node{addr: raddr},
dht.node.id.RawString(),
)
}
} | [
"func",
"(",
"dht",
"*",
"DHT",
")",
"join",
"(",
")",
"{",
"for",
"_",
",",
"addr",
":=",
"range",
"dht",
".",
"PrimeNodes",
"{",
"raddr",
",",
"err",
":=",
"net",
".",
"ResolveUDPAddr",
"(",
"dht",
".",
"Network",
",",
"addr",
")",
"\n",
"if",
... | // join makes current node join the dht network. | [
"join",
"makes",
"current",
"node",
"join",
"the",
"dht",
"network",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/dht.go#L199-L212 | train |
shiyanhui/dht | dht.go | listen | func (dht *DHT) listen() {
go func() {
buff := make([]byte, 8192)
for {
n, raddr, err := dht.conn.ReadFromUDP(buff)
if err != nil {
continue
}
dht.packets <- packet{buff[:n], raddr}
}
}()
} | go | func (dht *DHT) listen() {
go func() {
buff := make([]byte, 8192)
for {
n, raddr, err := dht.conn.ReadFromUDP(buff)
if err != nil {
continue
}
dht.packets <- packet{buff[:n], raddr}
}
}()
} | [
"func",
"(",
"dht",
"*",
"DHT",
")",
"listen",
"(",
")",
"{",
"go",
"func",
"(",
")",
"{",
"buff",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"8192",
")",
"\n",
"for",
"{",
"n",
",",
"raddr",
",",
"err",
":=",
"dht",
".",
"conn",
".",
"ReadF... | // listen receives message from udp. | [
"listen",
"receives",
"message",
"from",
"udp",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/dht.go#L215-L227 | train |
shiyanhui/dht | dht.go | id | func (dht *DHT) id(target string) string {
if dht.IsStandardMode() || target == "" {
return dht.node.id.RawString()
}
return target[:15] + dht.node.id.RawString()[15:]
} | go | func (dht *DHT) id(target string) string {
if dht.IsStandardMode() || target == "" {
return dht.node.id.RawString()
}
return target[:15] + dht.node.id.RawString()[15:]
} | [
"func",
"(",
"dht",
"*",
"DHT",
")",
"id",
"(",
"target",
"string",
")",
"string",
"{",
"if",
"dht",
".",
"IsStandardMode",
"(",
")",
"||",
"target",
"==",
"\"",
"\"",
"{",
"return",
"dht",
".",
"node",
".",
"id",
".",
"RawString",
"(",
")",
"\n"... | // id returns a id near to target if target is not null, otherwise it returns
// the dht's node id. | [
"id",
"returns",
"a",
"id",
"near",
"to",
"target",
"if",
"target",
"is",
"not",
"null",
"otherwise",
"it",
"returns",
"the",
"dht",
"s",
"node",
"id",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/dht.go#L231-L236 | train |
shiyanhui/dht | dht.go | GetPeers | func (dht *DHT) GetPeers(infoHash string) error {
if !dht.Ready {
return ErrNotReady
}
if dht.OnGetPeersResponse == nil {
return ErrOnGetPeersResponseNotSet
}
if len(infoHash) == 40 {
data, err := hex.DecodeString(infoHash)
if err != nil {
return err
}
infoHash = string(data)
}
neighbors := dht... | go | func (dht *DHT) GetPeers(infoHash string) error {
if !dht.Ready {
return ErrNotReady
}
if dht.OnGetPeersResponse == nil {
return ErrOnGetPeersResponseNotSet
}
if len(infoHash) == 40 {
data, err := hex.DecodeString(infoHash)
if err != nil {
return err
}
infoHash = string(data)
}
neighbors := dht... | [
"func",
"(",
"dht",
"*",
"DHT",
")",
"GetPeers",
"(",
"infoHash",
"string",
")",
"error",
"{",
"if",
"!",
"dht",
".",
"Ready",
"{",
"return",
"ErrNotReady",
"\n",
"}",
"\n\n",
"if",
"dht",
".",
"OnGetPeersResponse",
"==",
"nil",
"{",
"return",
"ErrOnGe... | // GetPeers returns peers who have announced having infoHash. | [
"GetPeers",
"returns",
"peers",
"who",
"have",
"announced",
"having",
"infoHash",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/dht.go#L239-L264 | train |
shiyanhui/dht | dht.go | Run | func (dht *DHT) Run() {
dht.init()
dht.listen()
dht.join()
dht.Ready = true
var pkt packet
tick := time.Tick(dht.CheckKBucketPeriod)
for {
select {
case pkt = <-dht.packets:
handle(dht, pkt)
case <-tick:
if dht.routingTable.Len() == 0 {
dht.join()
} else if dht.transactionManager.len() == 0... | go | func (dht *DHT) Run() {
dht.init()
dht.listen()
dht.join()
dht.Ready = true
var pkt packet
tick := time.Tick(dht.CheckKBucketPeriod)
for {
select {
case pkt = <-dht.packets:
handle(dht, pkt)
case <-tick:
if dht.routingTable.Len() == 0 {
dht.join()
} else if dht.transactionManager.len() == 0... | [
"func",
"(",
"dht",
"*",
"DHT",
")",
"Run",
"(",
")",
"{",
"dht",
".",
"init",
"(",
")",
"\n",
"dht",
".",
"listen",
"(",
")",
"\n",
"dht",
".",
"join",
"(",
")",
"\n\n",
"dht",
".",
"Ready",
"=",
"true",
"\n\n",
"var",
"pkt",
"packet",
"\n",... | // Run starts the dht. | [
"Run",
"starts",
"the",
"dht",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/dht.go#L267-L289 | train |
shiyanhui/dht | blacklist.go | newBlackList | func newBlackList(size int) *blackList {
return &blackList{
list: newSyncedMap(),
maxSize: size,
expiredAfter: time.Hour * 1,
}
} | go | func newBlackList(size int) *blackList {
return &blackList{
list: newSyncedMap(),
maxSize: size,
expiredAfter: time.Hour * 1,
}
} | [
"func",
"newBlackList",
"(",
"size",
"int",
")",
"*",
"blackList",
"{",
"return",
"&",
"blackList",
"{",
"list",
":",
"newSyncedMap",
"(",
")",
",",
"maxSize",
":",
"size",
",",
"expiredAfter",
":",
"time",
".",
"Hour",
"*",
"1",
",",
"}",
"\n",
"}"
... | // newBlackList returns a blackList pointer. | [
"newBlackList",
"returns",
"a",
"blackList",
"pointer",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/blacklist.go#L23-L29 | train |
shiyanhui/dht | blacklist.go | insert | func (bl *blackList) insert(ip string, port int) {
if bl.list.Len() >= bl.maxSize {
return
}
bl.list.Set(bl.genKey(ip, port), &blockedItem{
ip: ip,
port: port,
createTime: time.Now(),
})
} | go | func (bl *blackList) insert(ip string, port int) {
if bl.list.Len() >= bl.maxSize {
return
}
bl.list.Set(bl.genKey(ip, port), &blockedItem{
ip: ip,
port: port,
createTime: time.Now(),
})
} | [
"func",
"(",
"bl",
"*",
"blackList",
")",
"insert",
"(",
"ip",
"string",
",",
"port",
"int",
")",
"{",
"if",
"bl",
".",
"list",
".",
"Len",
"(",
")",
">=",
"bl",
".",
"maxSize",
"{",
"return",
"\n",
"}",
"\n\n",
"bl",
".",
"list",
".",
"Set",
... | // insert adds a blocked item to the blacklist. | [
"insert",
"adds",
"a",
"blocked",
"item",
"to",
"the",
"blacklist",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/blacklist.go#L42-L52 | train |
shiyanhui/dht | blacklist.go | delete | func (bl *blackList) delete(ip string, port int) {
bl.list.Delete(bl.genKey(ip, port))
} | go | func (bl *blackList) delete(ip string, port int) {
bl.list.Delete(bl.genKey(ip, port))
} | [
"func",
"(",
"bl",
"*",
"blackList",
")",
"delete",
"(",
"ip",
"string",
",",
"port",
"int",
")",
"{",
"bl",
".",
"list",
".",
"Delete",
"(",
"bl",
".",
"genKey",
"(",
"ip",
",",
"port",
")",
")",
"\n",
"}"
] | // delete removes blocked item form the blackList. | [
"delete",
"removes",
"blocked",
"item",
"form",
"the",
"blackList",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/blacklist.go#L55-L57 | train |
shiyanhui/dht | blacklist.go | in | func (bl *blackList) in(ip string, port int) bool {
if _, ok := bl.list.Get(ip); ok {
return true
}
key := bl.genKey(ip, port)
v, ok := bl.list.Get(key)
if ok {
if time.Now().Sub(v.(*blockedItem).createTime) < bl.expiredAfter {
return true
}
bl.list.Delete(key)
}
return false
} | go | func (bl *blackList) in(ip string, port int) bool {
if _, ok := bl.list.Get(ip); ok {
return true
}
key := bl.genKey(ip, port)
v, ok := bl.list.Get(key)
if ok {
if time.Now().Sub(v.(*blockedItem).createTime) < bl.expiredAfter {
return true
}
bl.list.Delete(key)
}
return false
} | [
"func",
"(",
"bl",
"*",
"blackList",
")",
"in",
"(",
"ip",
"string",
",",
"port",
"int",
")",
"bool",
"{",
"if",
"_",
",",
"ok",
":=",
"bl",
".",
"list",
".",
"Get",
"(",
"ip",
")",
";",
"ok",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"key",
... | // validate checks whether ip-port pair is in the block nodes list. | [
"validate",
"checks",
"whether",
"ip",
"-",
"port",
"pair",
"is",
"in",
"the",
"block",
"nodes",
"list",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/blacklist.go#L60-L75 | train |
shiyanhui/dht | blacklist.go | clear | func (bl *blackList) clear() {
for _ = range time.Tick(time.Minute * 10) {
keys := make([]interface{}, 0, 100)
for item := range bl.list.Iter() {
if time.Now().Sub(
item.val.(*blockedItem).createTime) > bl.expiredAfter {
keys = append(keys, item.key)
}
}
bl.list.DeleteMulti(keys)
}
} | go | func (bl *blackList) clear() {
for _ = range time.Tick(time.Minute * 10) {
keys := make([]interface{}, 0, 100)
for item := range bl.list.Iter() {
if time.Now().Sub(
item.val.(*blockedItem).createTime) > bl.expiredAfter {
keys = append(keys, item.key)
}
}
bl.list.DeleteMulti(keys)
}
} | [
"func",
"(",
"bl",
"*",
"blackList",
")",
"clear",
"(",
")",
"{",
"for",
"_",
"=",
"range",
"time",
".",
"Tick",
"(",
"time",
".",
"Minute",
"*",
"10",
")",
"{",
"keys",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"0",
",",
"100"... | // clear cleans the expired items every 10 minutes. | [
"clear",
"cleans",
"the",
"expired",
"items",
"every",
"10",
"minutes",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/blacklist.go#L78-L92 | train |
shiyanhui/dht | peerwire.go | read | func read(conn *net.TCPConn, size int, data *bytes.Buffer) error {
conn.SetReadDeadline(time.Now().Add(time.Second * 15))
n, err := io.CopyN(data, conn, int64(size))
if err != nil || n != int64(size) {
return errors.New("read error")
}
return nil
} | go | func read(conn *net.TCPConn, size int, data *bytes.Buffer) error {
conn.SetReadDeadline(time.Now().Add(time.Second * 15))
n, err := io.CopyN(data, conn, int64(size))
if err != nil || n != int64(size) {
return errors.New("read error")
}
return nil
} | [
"func",
"read",
"(",
"conn",
"*",
"net",
".",
"TCPConn",
",",
"size",
"int",
",",
"data",
"*",
"bytes",
".",
"Buffer",
")",
"error",
"{",
"conn",
".",
"SetReadDeadline",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"time",
".",
"Second",
"... | // read reads size-length bytes from conn to data. | [
"read",
"reads",
"size",
"-",
"length",
"bytes",
"from",
"conn",
"to",
"data",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/peerwire.go#L41-L49 | train |
shiyanhui/dht | peerwire.go | readMessage | func readMessage(conn *net.TCPConn, data *bytes.Buffer) (
length int, err error) {
if err = read(conn, 4, data); err != nil {
return
}
length = int(bytes2int(data.Next(4)))
if length == 0 {
return
}
if err = read(conn, length, data); err != nil {
return
}
return
} | go | func readMessage(conn *net.TCPConn, data *bytes.Buffer) (
length int, err error) {
if err = read(conn, 4, data); err != nil {
return
}
length = int(bytes2int(data.Next(4)))
if length == 0 {
return
}
if err = read(conn, length, data); err != nil {
return
}
return
} | [
"func",
"readMessage",
"(",
"conn",
"*",
"net",
".",
"TCPConn",
",",
"data",
"*",
"bytes",
".",
"Buffer",
")",
"(",
"length",
"int",
",",
"err",
"error",
")",
"{",
"if",
"err",
"=",
"read",
"(",
"conn",
",",
"4",
",",
"data",
")",
";",
"err",
"... | // readMessage gets a message from the tcp connection. | [
"readMessage",
"gets",
"a",
"message",
"from",
"the",
"tcp",
"connection",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/peerwire.go#L52-L68 | train |
shiyanhui/dht | peerwire.go | sendMessage | func sendMessage(conn *net.TCPConn, data []byte) error {
length := int32(len(data))
buffer := bytes.NewBuffer(nil)
binary.Write(buffer, binary.BigEndian, length)
conn.SetWriteDeadline(time.Now().Add(time.Second * 10))
_, err := conn.Write(append(buffer.Bytes(), data...))
return err
} | go | func sendMessage(conn *net.TCPConn, data []byte) error {
length := int32(len(data))
buffer := bytes.NewBuffer(nil)
binary.Write(buffer, binary.BigEndian, length)
conn.SetWriteDeadline(time.Now().Add(time.Second * 10))
_, err := conn.Write(append(buffer.Bytes(), data...))
return err
} | [
"func",
"sendMessage",
"(",
"conn",
"*",
"net",
".",
"TCPConn",
",",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"length",
":=",
"int32",
"(",
"len",
"(",
"data",
")",
")",
"\n\n",
"buffer",
":=",
"bytes",
".",
"NewBuffer",
"(",
"nil",
")",
"\n",
... | // sendMessage sends data to the connection. | [
"sendMessage",
"sends",
"data",
"to",
"the",
"connection",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/peerwire.go#L71-L80 | train |
shiyanhui/dht | peerwire.go | sendHandshake | func sendHandshake(conn *net.TCPConn, infoHash, peerID []byte) error {
data := make([]byte, 68)
copy(data[:28], handshakePrefix)
copy(data[28:48], infoHash)
copy(data[48:], peerID)
conn.SetWriteDeadline(time.Now().Add(time.Second * 10))
_, err := conn.Write(data)
return err
} | go | func sendHandshake(conn *net.TCPConn, infoHash, peerID []byte) error {
data := make([]byte, 68)
copy(data[:28], handshakePrefix)
copy(data[28:48], infoHash)
copy(data[48:], peerID)
conn.SetWriteDeadline(time.Now().Add(time.Second * 10))
_, err := conn.Write(data)
return err
} | [
"func",
"sendHandshake",
"(",
"conn",
"*",
"net",
".",
"TCPConn",
",",
"infoHash",
",",
"peerID",
"[",
"]",
"byte",
")",
"error",
"{",
"data",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"68",
")",
"\n",
"copy",
"(",
"data",
"[",
":",
"28",
"]",
... | // sendHandshake sends handshake message to conn. | [
"sendHandshake",
"sends",
"handshake",
"message",
"to",
"conn",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/peerwire.go#L83-L92 | train |
shiyanhui/dht | peerwire.go | onHandshake | func onHandshake(data []byte) (err error) {
if !(bytes.Equal(handshakePrefix[:20], data[:20]) && data[25]&0x10 != 0) {
err = errors.New("invalid handshake response")
}
return
} | go | func onHandshake(data []byte) (err error) {
if !(bytes.Equal(handshakePrefix[:20], data[:20]) && data[25]&0x10 != 0) {
err = errors.New("invalid handshake response")
}
return
} | [
"func",
"onHandshake",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"err",
"error",
")",
"{",
"if",
"!",
"(",
"bytes",
".",
"Equal",
"(",
"handshakePrefix",
"[",
":",
"20",
"]",
",",
"data",
"[",
":",
"20",
"]",
")",
"&&",
"data",
"[",
"25",
"]",
... | // onHandshake handles the handshake response. | [
"onHandshake",
"handles",
"the",
"handshake",
"response",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/peerwire.go#L95-L100 | train |
shiyanhui/dht | peerwire.go | sendExtHandshake | func sendExtHandshake(conn *net.TCPConn) error {
data := append(
[]byte{EXTENDED, HANDSHAKE},
Encode(map[string]interface{}{
"m": map[string]interface{}{"ut_metadata": 1},
})...,
)
return sendMessage(conn, data)
} | go | func sendExtHandshake(conn *net.TCPConn) error {
data := append(
[]byte{EXTENDED, HANDSHAKE},
Encode(map[string]interface{}{
"m": map[string]interface{}{"ut_metadata": 1},
})...,
)
return sendMessage(conn, data)
} | [
"func",
"sendExtHandshake",
"(",
"conn",
"*",
"net",
".",
"TCPConn",
")",
"error",
"{",
"data",
":=",
"append",
"(",
"[",
"]",
"byte",
"{",
"EXTENDED",
",",
"HANDSHAKE",
"}",
",",
"Encode",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
... | // sendExtHandshake requests for the ut_metadata and metadata_size. | [
"sendExtHandshake",
"requests",
"for",
"the",
"ut_metadata",
"and",
"metadata_size",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/peerwire.go#L103-L112 | train |
shiyanhui/dht | peerwire.go | getUTMetaSize | func getUTMetaSize(data []byte) (
utMetadata int, metadataSize int, err error) {
v, err := Decode(data)
if err != nil {
return
}
dict, ok := v.(map[string]interface{})
if !ok {
err = errors.New("invalid dict")
return
}
if err = ParseKeys(
dict, [][]string{{"metadata_size", "int"}, {"m", "map"}}); err... | go | func getUTMetaSize(data []byte) (
utMetadata int, metadataSize int, err error) {
v, err := Decode(data)
if err != nil {
return
}
dict, ok := v.(map[string]interface{})
if !ok {
err = errors.New("invalid dict")
return
}
if err = ParseKeys(
dict, [][]string{{"metadata_size", "int"}, {"m", "map"}}); err... | [
"func",
"getUTMetaSize",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"utMetadata",
"int",
",",
"metadataSize",
"int",
",",
"err",
"error",
")",
"{",
"v",
",",
"err",
":=",
"Decode",
"(",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n"... | // getUTMetaSize returns the ut_metadata and metadata_size. | [
"getUTMetaSize",
"returns",
"the",
"ut_metadata",
"and",
"metadata_size",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/peerwire.go#L115-L146 | train |
shiyanhui/dht | peerwire.go | Request | func (wire *Wire) Request(infoHash []byte, ip string, port int) {
wire.requests <- Request{InfoHash: infoHash, IP: ip, Port: port}
} | go | func (wire *Wire) Request(infoHash []byte, ip string, port int) {
wire.requests <- Request{InfoHash: infoHash, IP: ip, Port: port}
} | [
"func",
"(",
"wire",
"*",
"Wire",
")",
"Request",
"(",
"infoHash",
"[",
"]",
"byte",
",",
"ip",
"string",
",",
"port",
"int",
")",
"{",
"wire",
".",
"requests",
"<-",
"Request",
"{",
"InfoHash",
":",
"infoHash",
",",
"IP",
":",
"ip",
",",
"Port",
... | // Request pushes the request to the queue. | [
"Request",
"pushes",
"the",
"request",
"to",
"the",
"queue",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/peerwire.go#L185-L187 | train |
shiyanhui/dht | peerwire.go | isDone | func (wire *Wire) isDone(pieces [][]byte) bool {
for _, piece := range pieces {
if len(piece) == 0 {
return false
}
}
return true
} | go | func (wire *Wire) isDone(pieces [][]byte) bool {
for _, piece := range pieces {
if len(piece) == 0 {
return false
}
}
return true
} | [
"func",
"(",
"wire",
"*",
"Wire",
")",
"isDone",
"(",
"pieces",
"[",
"]",
"[",
"]",
"byte",
")",
"bool",
"{",
"for",
"_",
",",
"piece",
":=",
"range",
"pieces",
"{",
"if",
"len",
"(",
"piece",
")",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
... | // isDone returns whether the wire get all pieces of the metadata info. | [
"isDone",
"returns",
"whether",
"the",
"wire",
"get",
"all",
"pieces",
"of",
"the",
"metadata",
"info",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/peerwire.go#L195-L202 | train |
shiyanhui/dht | peerwire.go | Run | func (wire *Wire) Run() {
go wire.blackList.clear()
for r := range wire.requests {
wire.workerTokens <- struct{}{}
go func(r Request) {
defer func() {
<-wire.workerTokens
}()
key := strings.Join([]string{
string(r.InfoHash), genAddress(r.IP, r.Port),
}, ":")
if len(r.InfoHash) != 20 || ... | go | func (wire *Wire) Run() {
go wire.blackList.clear()
for r := range wire.requests {
wire.workerTokens <- struct{}{}
go func(r Request) {
defer func() {
<-wire.workerTokens
}()
key := strings.Join([]string{
string(r.InfoHash), genAddress(r.IP, r.Port),
}, ":")
if len(r.InfoHash) != 20 || ... | [
"func",
"(",
"wire",
"*",
"Wire",
")",
"Run",
"(",
")",
"{",
"go",
"wire",
".",
"blackList",
".",
"clear",
"(",
")",
"\n\n",
"for",
"r",
":=",
"range",
"wire",
".",
"requests",
"{",
"wire",
".",
"workerTokens",
"<-",
"struct",
"{",
"}",
"{",
"}",... | // Run starts the peer wire protocol. | [
"Run",
"starts",
"the",
"peer",
"wire",
"protocol",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/peerwire.go#L362-L385 | train |
shiyanhui/dht | bitmap.go | newBitmap | func newBitmap(size int) *bitmap {
div, mod := size>>3, size&0x07
if mod > 0 {
div++
}
return &bitmap{size, make([]byte, div)}
} | go | func newBitmap(size int) *bitmap {
div, mod := size>>3, size&0x07
if mod > 0 {
div++
}
return &bitmap{size, make([]byte, div)}
} | [
"func",
"newBitmap",
"(",
"size",
"int",
")",
"*",
"bitmap",
"{",
"div",
",",
"mod",
":=",
"size",
">>",
"3",
",",
"size",
"&",
"0x07",
"\n",
"if",
"mod",
">",
"0",
"{",
"div",
"++",
"\n",
"}",
"\n",
"return",
"&",
"bitmap",
"{",
"size",
",",
... | // newBitmap returns a size-length bitmap pointer. | [
"newBitmap",
"returns",
"a",
"size",
"-",
"length",
"bitmap",
"pointer",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/bitmap.go#L16-L22 | train |
shiyanhui/dht | bitmap.go | newBitmapFromBytes | func newBitmapFromBytes(data []byte) *bitmap {
bitmap := newBitmap(len(data) << 3)
copy(bitmap.data, data)
return bitmap
} | go | func newBitmapFromBytes(data []byte) *bitmap {
bitmap := newBitmap(len(data) << 3)
copy(bitmap.data, data)
return bitmap
} | [
"func",
"newBitmapFromBytes",
"(",
"data",
"[",
"]",
"byte",
")",
"*",
"bitmap",
"{",
"bitmap",
":=",
"newBitmap",
"(",
"len",
"(",
"data",
")",
"<<",
"3",
")",
"\n",
"copy",
"(",
"bitmap",
".",
"data",
",",
"data",
")",
"\n",
"return",
"bitmap",
"... | // newBitmapFromBytes returns a bitmap pointer created from a byte array. | [
"newBitmapFromBytes",
"returns",
"a",
"bitmap",
"pointer",
"created",
"from",
"a",
"byte",
"array",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/bitmap.go#L49-L53 | train |
shiyanhui/dht | bitmap.go | Bit | func (bitmap *bitmap) Bit(index int) int {
if index >= bitmap.Size {
panic("index out of range")
}
div, mod := index>>3, index&0x07
return int((uint(bitmap.data[div]) & (1 << uint(7-mod))) >> uint(7-mod))
} | go | func (bitmap *bitmap) Bit(index int) int {
if index >= bitmap.Size {
panic("index out of range")
}
div, mod := index>>3, index&0x07
return int((uint(bitmap.data[div]) & (1 << uint(7-mod))) >> uint(7-mod))
} | [
"func",
"(",
"bitmap",
"*",
"bitmap",
")",
"Bit",
"(",
"index",
"int",
")",
"int",
"{",
"if",
"index",
">=",
"bitmap",
".",
"Size",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"div",
",",
"mod",
":=",
"index",
">>",
"3",
",",
"index"... | // Bit returns the bit at index. | [
"Bit",
"returns",
"the",
"bit",
"at",
"index",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/bitmap.go#L61-L68 | train |
shiyanhui/dht | bitmap.go | set | func (bitmap *bitmap) set(index int, bit int) {
if index >= bitmap.Size {
panic("index out of range")
}
div, mod := index>>3, index&0x07
shift := byte(1 << uint(7-mod))
bitmap.data[div] &= ^shift
if bit > 0 {
bitmap.data[div] |= shift
}
} | go | func (bitmap *bitmap) set(index int, bit int) {
if index >= bitmap.Size {
panic("index out of range")
}
div, mod := index>>3, index&0x07
shift := byte(1 << uint(7-mod))
bitmap.data[div] &= ^shift
if bit > 0 {
bitmap.data[div] |= shift
}
} | [
"func",
"(",
"bitmap",
"*",
"bitmap",
")",
"set",
"(",
"index",
"int",
",",
"bit",
"int",
")",
"{",
"if",
"index",
">=",
"bitmap",
".",
"Size",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"div",
",",
"mod",
":=",
"index",
">>",
"3",
... | // set sets the bit at index `index`. If bit is true, set 1, otherwise set 0. | [
"set",
"sets",
"the",
"bit",
"at",
"index",
"index",
".",
"If",
"bit",
"is",
"true",
"set",
"1",
"otherwise",
"set",
"0",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/bitmap.go#L71-L83 | train |
shiyanhui/dht | bitmap.go | Xor | func (bitmap *bitmap) Xor(other *bitmap) *bitmap {
if bitmap.Size != other.Size {
panic("size not the same")
}
distance := newBitmap(bitmap.Size)
xor(distance.data, bitmap.data, other.data)
return distance
} | go | func (bitmap *bitmap) Xor(other *bitmap) *bitmap {
if bitmap.Size != other.Size {
panic("size not the same")
}
distance := newBitmap(bitmap.Size)
xor(distance.data, bitmap.data, other.data)
return distance
} | [
"func",
"(",
"bitmap",
"*",
"bitmap",
")",
"Xor",
"(",
"other",
"*",
"bitmap",
")",
"*",
"bitmap",
"{",
"if",
"bitmap",
".",
"Size",
"!=",
"other",
".",
"Size",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"distance",
":=",
"newBitmap",
... | // Xor returns the xor value of two bitmap. | [
"Xor",
"returns",
"the",
"xor",
"value",
"of",
"two",
"bitmap",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/bitmap.go#L123-L132 | train |
shiyanhui/dht | bitmap.go | String | func (bitmap *bitmap) String() string {
div, mod := bitmap.Size>>3, bitmap.Size&0x07
buff := make([]string, div+mod)
for i := 0; i < div; i++ {
buff[i] = fmt.Sprintf("%08b", bitmap.data[i])
}
for i := div; i < div+mod; i++ {
buff[i] = fmt.Sprintf("%1b", bitmap.Bit(div*8+(i-div)))
}
return strings.Join(buf... | go | func (bitmap *bitmap) String() string {
div, mod := bitmap.Size>>3, bitmap.Size&0x07
buff := make([]string, div+mod)
for i := 0; i < div; i++ {
buff[i] = fmt.Sprintf("%08b", bitmap.data[i])
}
for i := div; i < div+mod; i++ {
buff[i] = fmt.Sprintf("%1b", bitmap.Bit(div*8+(i-div)))
}
return strings.Join(buf... | [
"func",
"(",
"bitmap",
"*",
"bitmap",
")",
"String",
"(",
")",
"string",
"{",
"div",
",",
"mod",
":=",
"bitmap",
".",
"Size",
">>",
"3",
",",
"bitmap",
".",
"Size",
"&",
"0x07",
"\n",
"buff",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"div",
"... | // String returns the bit sequence string of the bitmap. | [
"String",
"returns",
"the",
"bit",
"sequence",
"string",
"of",
"the",
"bitmap",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/bitmap.go#L135-L148 | train |
shiyanhui/dht | krpc.go | newTokenManager | func newTokenManager(expiredAfter time.Duration, dht *DHT) *tokenManager {
return &tokenManager{
syncedMap: newSyncedMap(),
expiredAfter: expiredAfter,
dht: dht,
}
} | go | func newTokenManager(expiredAfter time.Duration, dht *DHT) *tokenManager {
return &tokenManager{
syncedMap: newSyncedMap(),
expiredAfter: expiredAfter,
dht: dht,
}
} | [
"func",
"newTokenManager",
"(",
"expiredAfter",
"time",
".",
"Duration",
",",
"dht",
"*",
"DHT",
")",
"*",
"tokenManager",
"{",
"return",
"&",
"tokenManager",
"{",
"syncedMap",
":",
"newSyncedMap",
"(",
")",
",",
"expiredAfter",
":",
"expiredAfter",
",",
"dh... | // newTokenManager returns a new tokenManager. | [
"newTokenManager",
"returns",
"a",
"new",
"tokenManager",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L45-L51 | train |
shiyanhui/dht | krpc.go | token | func (tm *tokenManager) token(addr *net.UDPAddr) string {
v, ok := tm.Get(addr.IP.String())
tk, _ := v.(token)
if !ok || time.Now().Sub(tk.createTime) > tm.expiredAfter {
tk = token{
data: randomString(5),
createTime: time.Now(),
}
tm.Set(addr.IP.String(), tk)
}
return tk.data
} | go | func (tm *tokenManager) token(addr *net.UDPAddr) string {
v, ok := tm.Get(addr.IP.String())
tk, _ := v.(token)
if !ok || time.Now().Sub(tk.createTime) > tm.expiredAfter {
tk = token{
data: randomString(5),
createTime: time.Now(),
}
tm.Set(addr.IP.String(), tk)
}
return tk.data
} | [
"func",
"(",
"tm",
"*",
"tokenManager",
")",
"token",
"(",
"addr",
"*",
"net",
".",
"UDPAddr",
")",
"string",
"{",
"v",
",",
"ok",
":=",
"tm",
".",
"Get",
"(",
"addr",
".",
"IP",
".",
"String",
"(",
")",
")",
"\n",
"tk",
",",
"_",
":=",
"v",
... | // token returns a token. If it doesn't exist or is expired, it will add a
// new token. | [
"token",
"returns",
"a",
"token",
".",
"If",
"it",
"doesn",
"t",
"exist",
"or",
"is",
"expired",
"it",
"will",
"add",
"a",
"new",
"token",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L55-L69 | train |
shiyanhui/dht | krpc.go | clear | func (tm *tokenManager) clear() {
for _ = range time.Tick(time.Minute * 3) {
keys := make([]interface{}, 0, 100)
for item := range tm.Iter() {
if time.Now().Sub(item.val.(token).createTime) > tm.expiredAfter {
keys = append(keys, item.key)
}
}
tm.DeleteMulti(keys)
}
} | go | func (tm *tokenManager) clear() {
for _ = range time.Tick(time.Minute * 3) {
keys := make([]interface{}, 0, 100)
for item := range tm.Iter() {
if time.Now().Sub(item.val.(token).createTime) > tm.expiredAfter {
keys = append(keys, item.key)
}
}
tm.DeleteMulti(keys)
}
} | [
"func",
"(",
"tm",
"*",
"tokenManager",
")",
"clear",
"(",
")",
"{",
"for",
"_",
"=",
"range",
"time",
".",
"Tick",
"(",
"time",
".",
"Minute",
"*",
"3",
")",
"{",
"keys",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"0",
",",
"10... | // clear removes expired tokens. | [
"clear",
"removes",
"expired",
"tokens",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L72-L84 | train |
shiyanhui/dht | krpc.go | check | func (tm *tokenManager) check(addr *net.UDPAddr, tokenString string) bool {
key := addr.IP.String()
v, ok := tm.Get(key)
tk, _ := v.(token)
if ok {
tm.Delete(key)
}
return ok && tokenString == tk.data
} | go | func (tm *tokenManager) check(addr *net.UDPAddr, tokenString string) bool {
key := addr.IP.String()
v, ok := tm.Get(key)
tk, _ := v.(token)
if ok {
tm.Delete(key)
}
return ok && tokenString == tk.data
} | [
"func",
"(",
"tm",
"*",
"tokenManager",
")",
"check",
"(",
"addr",
"*",
"net",
".",
"UDPAddr",
",",
"tokenString",
"string",
")",
"bool",
"{",
"key",
":=",
"addr",
".",
"IP",
".",
"String",
"(",
")",
"\n",
"v",
",",
"ok",
":=",
"tm",
".",
"Get",
... | // check returns whether the token is valid. | [
"check",
"returns",
"whether",
"the",
"token",
"is",
"valid",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L87-L97 | train |
shiyanhui/dht | krpc.go | makeQuery | func makeQuery(t, q string, a map[string]interface{}) map[string]interface{} {
return map[string]interface{}{
"t": t,
"y": "q",
"q": q,
"a": a,
}
} | go | func makeQuery(t, q string, a map[string]interface{}) map[string]interface{} {
return map[string]interface{}{
"t": t,
"y": "q",
"q": q,
"a": a,
}
} | [
"func",
"makeQuery",
"(",
"t",
",",
"q",
"string",
",",
"a",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"return",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\""... | // makeQuery returns a query-formed data. | [
"makeQuery",
"returns",
"a",
"query",
"-",
"formed",
"data",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L100-L107 | train |
shiyanhui/dht | krpc.go | makeError | func makeError(t string, errCode int, errMsg string) map[string]interface{} {
return map[string]interface{}{
"t": t,
"y": "e",
"e": []interface{}{errCode, errMsg},
}
} | go | func makeError(t string, errCode int, errMsg string) map[string]interface{} {
return map[string]interface{}{
"t": t,
"y": "e",
"e": []interface{}{errCode, errMsg},
}
} | [
"func",
"makeError",
"(",
"t",
"string",
",",
"errCode",
"int",
",",
"errMsg",
"string",
")",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"return",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"t",
",",
"\"",
... | // makeError returns a err-formed data. | [
"makeError",
"returns",
"a",
"err",
"-",
"formed",
"data",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L119-L125 | train |
shiyanhui/dht | krpc.go | send | func send(dht *DHT, addr *net.UDPAddr, data map[string]interface{}) error {
dht.conn.SetWriteDeadline(time.Now().Add(time.Second * 15))
_, err := dht.conn.WriteToUDP([]byte(Encode(data)), addr)
if err != nil {
dht.blackList.insert(addr.IP.String(), -1)
}
return err
} | go | func send(dht *DHT, addr *net.UDPAddr, data map[string]interface{}) error {
dht.conn.SetWriteDeadline(time.Now().Add(time.Second * 15))
_, err := dht.conn.WriteToUDP([]byte(Encode(data)), addr)
if err != nil {
dht.blackList.insert(addr.IP.String(), -1)
}
return err
} | [
"func",
"send",
"(",
"dht",
"*",
"DHT",
",",
"addr",
"*",
"net",
".",
"UDPAddr",
",",
"data",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"error",
"{",
"dht",
".",
"conn",
".",
"SetWriteDeadline",
"(",
"time",
".",
"Now",
"(",
")",
"."... | // send sends data to the udp. | [
"send",
"sends",
"data",
"to",
"the",
"udp",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L128-L136 | train |
shiyanhui/dht | krpc.go | newTransactionManager | func newTransactionManager(maxCursor uint64, dht *DHT) *transactionManager {
return &transactionManager{
RWMutex: &sync.RWMutex{},
transactions: newSyncedMap(),
index: newSyncedMap(),
maxCursor: maxCursor,
queryChan: make(chan *query, 1024),
dht: dht,
}
} | go | func newTransactionManager(maxCursor uint64, dht *DHT) *transactionManager {
return &transactionManager{
RWMutex: &sync.RWMutex{},
transactions: newSyncedMap(),
index: newSyncedMap(),
maxCursor: maxCursor,
queryChan: make(chan *query, 1024),
dht: dht,
}
} | [
"func",
"newTransactionManager",
"(",
"maxCursor",
"uint64",
",",
"dht",
"*",
"DHT",
")",
"*",
"transactionManager",
"{",
"return",
"&",
"transactionManager",
"{",
"RWMutex",
":",
"&",
"sync",
".",
"RWMutex",
"{",
"}",
",",
"transactions",
":",
"newSyncedMap",... | // newTransactionManager returns new transactionManager pointer. | [
"newTransactionManager",
"returns",
"new",
"transactionManager",
"pointer",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L163-L172 | train |
shiyanhui/dht | krpc.go | genTransID | func (tm *transactionManager) genTransID() string {
tm.Lock()
defer tm.Unlock()
tm.cursor = (tm.cursor + 1) % tm.maxCursor
return string(int2bytes(tm.cursor))
} | go | func (tm *transactionManager) genTransID() string {
tm.Lock()
defer tm.Unlock()
tm.cursor = (tm.cursor + 1) % tm.maxCursor
return string(int2bytes(tm.cursor))
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"genTransID",
"(",
")",
"string",
"{",
"tm",
".",
"Lock",
"(",
")",
"\n",
"defer",
"tm",
".",
"Unlock",
"(",
")",
"\n\n",
"tm",
".",
"cursor",
"=",
"(",
"tm",
".",
"cursor",
"+",
"1",
")",
"%",
... | // genTransID generates a transaction id and returns it. | [
"genTransID",
"generates",
"a",
"transaction",
"id",
"and",
"returns",
"it",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L175-L181 | train |
shiyanhui/dht | krpc.go | newTransaction | func (tm *transactionManager) newTransaction(id string, q *query) *transaction {
return &transaction{
id: id,
query: q,
response: make(chan struct{}, tm.dht.Try+1),
}
} | go | func (tm *transactionManager) newTransaction(id string, q *query) *transaction {
return &transaction{
id: id,
query: q,
response: make(chan struct{}, tm.dht.Try+1),
}
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"newTransaction",
"(",
"id",
"string",
",",
"q",
"*",
"query",
")",
"*",
"transaction",
"{",
"return",
"&",
"transaction",
"{",
"id",
":",
"id",
",",
"query",
":",
"q",
",",
"response",
":",
"make",
... | // newTransaction creates a new transaction. | [
"newTransaction",
"creates",
"a",
"new",
"transaction",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L184-L190 | train |
shiyanhui/dht | krpc.go | genIndexKey | func (tm *transactionManager) genIndexKey(queryType, address string) string {
return strings.Join([]string{queryType, address}, ":")
} | go | func (tm *transactionManager) genIndexKey(queryType, address string) string {
return strings.Join([]string{queryType, address}, ":")
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"genIndexKey",
"(",
"queryType",
",",
"address",
"string",
")",
"string",
"{",
"return",
"strings",
".",
"Join",
"(",
"[",
"]",
"string",
"{",
"queryType",
",",
"address",
"}",
",",
"\"",
"\"",
")",
"\... | // genIndexKey generates an indexed key which consists of queryType and
// address. | [
"genIndexKey",
"generates",
"an",
"indexed",
"key",
"which",
"consists",
"of",
"queryType",
"and",
"address",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L194-L196 | train |
shiyanhui/dht | krpc.go | genIndexKeyByTrans | func (tm *transactionManager) genIndexKeyByTrans(trans *transaction) string {
return tm.genIndexKey(trans.data["q"].(string), trans.node.addr.String())
} | go | func (tm *transactionManager) genIndexKeyByTrans(trans *transaction) string {
return tm.genIndexKey(trans.data["q"].(string), trans.node.addr.String())
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"genIndexKeyByTrans",
"(",
"trans",
"*",
"transaction",
")",
"string",
"{",
"return",
"tm",
".",
"genIndexKey",
"(",
"trans",
".",
"data",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
",",
"trans",
"... | // genIndexKeyByTrans generates an indexed key by a transaction. | [
"genIndexKeyByTrans",
"generates",
"an",
"indexed",
"key",
"by",
"a",
"transaction",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L199-L201 | train |
shiyanhui/dht | krpc.go | insert | func (tm *transactionManager) insert(trans *transaction) {
tm.Lock()
defer tm.Unlock()
tm.transactions.Set(trans.id, trans)
tm.index.Set(tm.genIndexKeyByTrans(trans), trans)
} | go | func (tm *transactionManager) insert(trans *transaction) {
tm.Lock()
defer tm.Unlock()
tm.transactions.Set(trans.id, trans)
tm.index.Set(tm.genIndexKeyByTrans(trans), trans)
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"insert",
"(",
"trans",
"*",
"transaction",
")",
"{",
"tm",
".",
"Lock",
"(",
")",
"\n",
"defer",
"tm",
".",
"Unlock",
"(",
")",
"\n\n",
"tm",
".",
"transactions",
".",
"Set",
"(",
"trans",
".",
"i... | // insert adds a transaction to transactionManager. | [
"insert",
"adds",
"a",
"transaction",
"to",
"transactionManager",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L204-L210 | train |
shiyanhui/dht | krpc.go | delete | func (tm *transactionManager) delete(transID string) {
v, ok := tm.transactions.Get(transID)
if !ok {
return
}
tm.Lock()
defer tm.Unlock()
trans := v.(*transaction)
tm.transactions.Delete(trans.id)
tm.index.Delete(tm.genIndexKeyByTrans(trans))
} | go | func (tm *transactionManager) delete(transID string) {
v, ok := tm.transactions.Get(transID)
if !ok {
return
}
tm.Lock()
defer tm.Unlock()
trans := v.(*transaction)
tm.transactions.Delete(trans.id)
tm.index.Delete(tm.genIndexKeyByTrans(trans))
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"delete",
"(",
"transID",
"string",
")",
"{",
"v",
",",
"ok",
":=",
"tm",
".",
"transactions",
".",
"Get",
"(",
"transID",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n\n",
"tm",
".",
... | // delete removes a transaction from transactionManager. | [
"delete",
"removes",
"a",
"transaction",
"from",
"transactionManager",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L213-L225 | train |
shiyanhui/dht | krpc.go | transaction | func (tm *transactionManager) transaction(
key string, keyType int) *transaction {
sm := tm.transactions
if keyType == 1 {
sm = tm.index
}
v, ok := sm.Get(key)
if !ok {
return nil
}
return v.(*transaction)
} | go | func (tm *transactionManager) transaction(
key string, keyType int) *transaction {
sm := tm.transactions
if keyType == 1 {
sm = tm.index
}
v, ok := sm.Get(key)
if !ok {
return nil
}
return v.(*transaction)
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"transaction",
"(",
"key",
"string",
",",
"keyType",
"int",
")",
"*",
"transaction",
"{",
"sm",
":=",
"tm",
".",
"transactions",
"\n",
"if",
"keyType",
"==",
"1",
"{",
"sm",
"=",
"tm",
".",
"index",
... | // transaction returns a transaction. keyType should be one of 0, 1 which
// represents transId and index each. | [
"transaction",
"returns",
"a",
"transaction",
".",
"keyType",
"should",
"be",
"one",
"of",
"0",
"1",
"which",
"represents",
"transId",
"and",
"index",
"each",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L234-L248 | train |
shiyanhui/dht | krpc.go | filterOne | func (tm *transactionManager) filterOne(
transID string, addr *net.UDPAddr) *transaction {
trans := tm.getByTransID(transID)
if trans == nil || trans.node.addr.String() != addr.String() {
return nil
}
return trans
} | go | func (tm *transactionManager) filterOne(
transID string, addr *net.UDPAddr) *transaction {
trans := tm.getByTransID(transID)
if trans == nil || trans.node.addr.String() != addr.String() {
return nil
}
return trans
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"filterOne",
"(",
"transID",
"string",
",",
"addr",
"*",
"net",
".",
"UDPAddr",
")",
"*",
"transaction",
"{",
"trans",
":=",
"tm",
".",
"getByTransID",
"(",
"transID",
")",
"\n",
"if",
"trans",
"==",
"... | // transaction gets the proper transaction with whose id is transId and
// address is addr. | [
"transaction",
"gets",
"the",
"proper",
"transaction",
"with",
"whose",
"id",
"is",
"transId",
"and",
"address",
"is",
"addr",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L262-L271 | train |
shiyanhui/dht | krpc.go | query | func (tm *transactionManager) query(q *query, try int) {
transID := q.data["t"].(string)
trans := tm.newTransaction(transID, q)
tm.insert(trans)
defer tm.delete(trans.id)
success := false
for i := 0; i < try; i++ {
if err := send(tm.dht, q.node.addr, q.data); err != nil {
break
}
select {
case <-tra... | go | func (tm *transactionManager) query(q *query, try int) {
transID := q.data["t"].(string)
trans := tm.newTransaction(transID, q)
tm.insert(trans)
defer tm.delete(trans.id)
success := false
for i := 0; i < try; i++ {
if err := send(tm.dht, q.node.addr, q.data); err != nil {
break
}
select {
case <-tra... | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"query",
"(",
"q",
"*",
"query",
",",
"try",
"int",
")",
"{",
"transID",
":=",
"q",
".",
"data",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
"\n",
"trans",
":=",
"tm",
".",
"newTransaction",
"... | // query sends the query-formed data to udp and wait for the response.
// When timeout, it will retry `try - 1` times, which means it will query
// `try` times totally. | [
"query",
"sends",
"the",
"query",
"-",
"formed",
"data",
"to",
"udp",
"and",
"wait",
"for",
"the",
"response",
".",
"When",
"timeout",
"it",
"will",
"retry",
"try",
"-",
"1",
"times",
"which",
"means",
"it",
"will",
"query",
"try",
"times",
"totally",
... | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L276-L301 | train |
shiyanhui/dht | krpc.go | run | func (tm *transactionManager) run() {
var q *query
for {
select {
case q = <-tm.queryChan:
go tm.query(q, tm.dht.Try)
}
}
} | go | func (tm *transactionManager) run() {
var q *query
for {
select {
case q = <-tm.queryChan:
go tm.query(q, tm.dht.Try)
}
}
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"run",
"(",
")",
"{",
"var",
"q",
"*",
"query",
"\n\n",
"for",
"{",
"select",
"{",
"case",
"q",
"=",
"<-",
"tm",
".",
"queryChan",
":",
"go",
"tm",
".",
"query",
"(",
"q",
",",
"tm",
".",
"dht"... | // run starts to listen and consume the query chan. | [
"run",
"starts",
"to",
"listen",
"and",
"consume",
"the",
"query",
"chan",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L304-L313 | train |
shiyanhui/dht | krpc.go | sendQuery | func (tm *transactionManager) sendQuery(
no *node, queryType string, a map[string]interface{}) {
// If the target is self, then stop.
if no.id != nil && no.id.RawString() == tm.dht.node.id.RawString() ||
tm.getByIndex(tm.genIndexKey(queryType, no.addr.String())) != nil ||
tm.dht.blackList.in(no.addr.IP.String()... | go | func (tm *transactionManager) sendQuery(
no *node, queryType string, a map[string]interface{}) {
// If the target is self, then stop.
if no.id != nil && no.id.RawString() == tm.dht.node.id.RawString() ||
tm.getByIndex(tm.genIndexKey(queryType, no.addr.String())) != nil ||
tm.dht.blackList.in(no.addr.IP.String()... | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"sendQuery",
"(",
"no",
"*",
"node",
",",
"queryType",
"string",
",",
"a",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"{",
"// If the target is self, then stop.",
"if",
"no",
".",
"id",
"!=",
... | // sendQuery send query-formed data to the chan. | [
"sendQuery",
"send",
"query",
"-",
"formed",
"data",
"to",
"the",
"chan",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L316-L331 | train |
shiyanhui/dht | krpc.go | ping | func (tm *transactionManager) ping(no *node) {
tm.sendQuery(no, pingType, map[string]interface{}{
"id": tm.dht.id(no.id.RawString()),
})
} | go | func (tm *transactionManager) ping(no *node) {
tm.sendQuery(no, pingType, map[string]interface{}{
"id": tm.dht.id(no.id.RawString()),
})
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"ping",
"(",
"no",
"*",
"node",
")",
"{",
"tm",
".",
"sendQuery",
"(",
"no",
",",
"pingType",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"tm",
".",
"dht",
".",
... | // ping sends ping query to the chan. | [
"ping",
"sends",
"ping",
"query",
"to",
"the",
"chan",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L334-L338 | train |
shiyanhui/dht | krpc.go | findNode | func (tm *transactionManager) findNode(no *node, target string) {
tm.sendQuery(no, findNodeType, map[string]interface{}{
"id": tm.dht.id(target),
"target": target,
})
} | go | func (tm *transactionManager) findNode(no *node, target string) {
tm.sendQuery(no, findNodeType, map[string]interface{}{
"id": tm.dht.id(target),
"target": target,
})
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"findNode",
"(",
"no",
"*",
"node",
",",
"target",
"string",
")",
"{",
"tm",
".",
"sendQuery",
"(",
"no",
",",
"findNodeType",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
... | // findNode sends find_node query to the chan. | [
"findNode",
"sends",
"find_node",
"query",
"to",
"the",
"chan",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L341-L346 | train |
shiyanhui/dht | krpc.go | getPeers | func (tm *transactionManager) getPeers(no *node, infoHash string) {
tm.sendQuery(no, getPeersType, map[string]interface{}{
"id": tm.dht.id(infoHash),
"info_hash": infoHash,
})
} | go | func (tm *transactionManager) getPeers(no *node, infoHash string) {
tm.sendQuery(no, getPeersType, map[string]interface{}{
"id": tm.dht.id(infoHash),
"info_hash": infoHash,
})
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"getPeers",
"(",
"no",
"*",
"node",
",",
"infoHash",
"string",
")",
"{",
"tm",
".",
"sendQuery",
"(",
"no",
",",
"getPeersType",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\""... | // getPeers sends get_peers query to the chan. | [
"getPeers",
"sends",
"get_peers",
"query",
"to",
"the",
"chan",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L349-L354 | train |
shiyanhui/dht | krpc.go | announcePeer | func (tm *transactionManager) announcePeer(
no *node, infoHash string, impliedPort, port int, token string) {
tm.sendQuery(no, announcePeerType, map[string]interface{}{
"id": tm.dht.id(no.id.RawString()),
"info_hash": infoHash,
"implied_port": impliedPort,
"port": port,
"token": ... | go | func (tm *transactionManager) announcePeer(
no *node, infoHash string, impliedPort, port int, token string) {
tm.sendQuery(no, announcePeerType, map[string]interface{}{
"id": tm.dht.id(no.id.RawString()),
"info_hash": infoHash,
"implied_port": impliedPort,
"port": port,
"token": ... | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"announcePeer",
"(",
"no",
"*",
"node",
",",
"infoHash",
"string",
",",
"impliedPort",
",",
"port",
"int",
",",
"token",
"string",
")",
"{",
"tm",
".",
"sendQuery",
"(",
"no",
",",
"announcePeerType",
",... | // announcePeer sends announce_peer query to the chan. | [
"announcePeer",
"sends",
"announce_peer",
"query",
"to",
"the",
"chan",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L357-L367 | train |
shiyanhui/dht | krpc.go | ParseKey | func ParseKey(data map[string]interface{}, key string, t string) error {
val, ok := data[key]
if !ok {
return errors.New("lack of key")
}
switch t {
case "string":
_, ok = val.(string)
case "int":
_, ok = val.(int)
case "map":
_, ok = val.(map[string]interface{})
case "list":
_, ok = val.([]interface... | go | func ParseKey(data map[string]interface{}, key string, t string) error {
val, ok := data[key]
if !ok {
return errors.New("lack of key")
}
switch t {
case "string":
_, ok = val.(string)
case "int":
_, ok = val.(int)
case "map":
_, ok = val.(map[string]interface{})
case "list":
_, ok = val.([]interface... | [
"func",
"ParseKey",
"(",
"data",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"key",
"string",
",",
"t",
"string",
")",
"error",
"{",
"val",
",",
"ok",
":=",
"data",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
... | // ParseKey parses the key in dict data. `t` is type of the keyed value.
// It's one of "int", "string", "map", "list". | [
"ParseKey",
"parses",
"the",
"key",
"in",
"dict",
"data",
".",
"t",
"is",
"type",
"of",
"the",
"keyed",
"value",
".",
"It",
"s",
"one",
"of",
"int",
"string",
"map",
"list",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L371-L395 | train |
shiyanhui/dht | krpc.go | ParseKeys | func ParseKeys(data map[string]interface{}, pairs [][]string) error {
for _, args := range pairs {
key, t := args[0], args[1]
if err := ParseKey(data, key, t); err != nil {
return err
}
}
return nil
} | go | func ParseKeys(data map[string]interface{}, pairs [][]string) error {
for _, args := range pairs {
key, t := args[0], args[1]
if err := ParseKey(data, key, t); err != nil {
return err
}
}
return nil
} | [
"func",
"ParseKeys",
"(",
"data",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"pairs",
"[",
"]",
"[",
"]",
"string",
")",
"error",
"{",
"for",
"_",
",",
"args",
":=",
"range",
"pairs",
"{",
"key",
",",
"t",
":=",
"args",
"[",
"0",
"]... | // ParseKeys parses keys. It just wraps ParseKey. | [
"ParseKeys",
"parses",
"keys",
".",
"It",
"just",
"wraps",
"ParseKey",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L398-L406 | train |
shiyanhui/dht | krpc.go | parseMessage | func parseMessage(data interface{}) (map[string]interface{}, error) {
response, ok := data.(map[string]interface{})
if !ok {
return nil, errors.New("response is not dict")
}
if err := ParseKeys(
response, [][]string{{"t", "string"}, {"y", "string"}}); err != nil {
return nil, err
}
return response, nil
} | go | func parseMessage(data interface{}) (map[string]interface{}, error) {
response, ok := data.(map[string]interface{})
if !ok {
return nil, errors.New("response is not dict")
}
if err := ParseKeys(
response, [][]string{{"t", "string"}, {"y", "string"}}); err != nil {
return nil, err
}
return response, nil
} | [
"func",
"parseMessage",
"(",
"data",
"interface",
"{",
"}",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"response",
",",
"ok",
":=",
"data",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
... | // parseMessage parses the basic data received from udp.
// It returns a map value. | [
"parseMessage",
"parses",
"the",
"basic",
"data",
"received",
"from",
"udp",
".",
"It",
"returns",
"a",
"map",
"value",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L410-L422 | train |
shiyanhui/dht | krpc.go | findOn | func findOn(dht *DHT, r map[string]interface{}, target *bitmap,
queryType string) error {
if err := ParseKey(r, "nodes", "string"); err != nil {
return err
}
nodes := r["nodes"].(string)
if len(nodes)%26 != 0 {
return errors.New("the length of nodes should can be divided by 26")
}
hasNew, found := false, ... | go | func findOn(dht *DHT, r map[string]interface{}, target *bitmap,
queryType string) error {
if err := ParseKey(r, "nodes", "string"); err != nil {
return err
}
nodes := r["nodes"].(string)
if len(nodes)%26 != 0 {
return errors.New("the length of nodes should can be divided by 26")
}
hasNew, found := false, ... | [
"func",
"findOn",
"(",
"dht",
"*",
"DHT",
",",
"r",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"target",
"*",
"bitmap",
",",
"queryType",
"string",
")",
"error",
"{",
"if",
"err",
":=",
"ParseKey",
"(",
"r",
",",
"\"",
"\"",
",",
"\""... | // findOn puts nodes in the response to the routingTable, then if target is in
// the nodes or all nodes are in the routingTable, it stops. Otherwise it
// continues to findNode or getPeers. | [
"findOn",
"puts",
"nodes",
"in",
"the",
"response",
"to",
"the",
"routingTable",
"then",
"if",
"target",
"is",
"in",
"the",
"nodes",
"or",
"all",
"nodes",
"are",
"in",
"the",
"routingTable",
"it",
"stops",
".",
"Otherwise",
"it",
"continues",
"to",
"findNo... | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L595-L637 | train |
shiyanhui/dht | krpc.go | handleError | func handleError(dht *DHT, addr *net.UDPAddr,
response map[string]interface{}) (success bool) {
if err := ParseKey(response, "e", "list"); err != nil {
return
}
if e := response["e"].([]interface{}); len(e) != 2 {
return
}
if trans := dht.transactionManager.filterOne(
response["t"].(string), addr); trans... | go | func handleError(dht *DHT, addr *net.UDPAddr,
response map[string]interface{}) (success bool) {
if err := ParseKey(response, "e", "list"); err != nil {
return
}
if e := response["e"].([]interface{}); len(e) != 2 {
return
}
if trans := dht.transactionManager.filterOne(
response["t"].(string), addr); trans... | [
"func",
"handleError",
"(",
"dht",
"*",
"DHT",
",",
"addr",
"*",
"net",
".",
"UDPAddr",
",",
"response",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"success",
"bool",
")",
"{",
"if",
"err",
":=",
"ParseKey",
"(",
"response",
",",
"... | // handleError handles errors received from udp. | [
"handleError",
"handles",
"errors",
"received",
"from",
"udp",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L728-L746 | train |
shiyanhui/dht | krpc.go | handle | func handle(dht *DHT, pkt packet) {
if len(dht.workerTokens) == dht.PacketWorkerLimit {
return
}
dht.workerTokens <- struct{}{}
go func() {
defer func() {
<-dht.workerTokens
}()
if dht.blackList.in(pkt.raddr.IP.String(), pkt.raddr.Port) {
return
}
data, err := Decode(pkt.data)
if err != nil ... | go | func handle(dht *DHT, pkt packet) {
if len(dht.workerTokens) == dht.PacketWorkerLimit {
return
}
dht.workerTokens <- struct{}{}
go func() {
defer func() {
<-dht.workerTokens
}()
if dht.blackList.in(pkt.raddr.IP.String(), pkt.raddr.Port) {
return
}
data, err := Decode(pkt.data)
if err != nil ... | [
"func",
"handle",
"(",
"dht",
"*",
"DHT",
",",
"pkt",
"packet",
")",
"{",
"if",
"len",
"(",
"dht",
".",
"workerTokens",
")",
"==",
"dht",
".",
"PacketWorkerLimit",
"{",
"return",
"\n",
"}",
"\n\n",
"dht",
".",
"workerTokens",
"<-",
"struct",
"{",
"}"... | // handle handles packets received from udp. | [
"handle",
"handles",
"packets",
"received",
"from",
"udp",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L755-L785 | train |
shiyanhui/dht | util.go | randomString | func randomString(size int) string {
buff := make([]byte, size)
rand.Read(buff)
return string(buff)
} | go | func randomString(size int) string {
buff := make([]byte, size)
rand.Read(buff)
return string(buff)
} | [
"func",
"randomString",
"(",
"size",
"int",
")",
"string",
"{",
"buff",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"size",
")",
"\n",
"rand",
".",
"Read",
"(",
"buff",
")",
"\n",
"return",
"string",
"(",
"buff",
")",
"\n",
"}"
] | // randomString generates a size-length string randomly. | [
"randomString",
"generates",
"a",
"size",
"-",
"length",
"string",
"randomly",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/util.go#L15-L19 | train |
shiyanhui/dht | util.go | bytes2int | func bytes2int(data []byte) uint64 {
n, val := len(data), uint64(0)
if n > 8 {
panic("data too long")
}
for i, b := range data {
val += uint64(b) << uint64((n-i-1)*8)
}
return val
} | go | func bytes2int(data []byte) uint64 {
n, val := len(data), uint64(0)
if n > 8 {
panic("data too long")
}
for i, b := range data {
val += uint64(b) << uint64((n-i-1)*8)
}
return val
} | [
"func",
"bytes2int",
"(",
"data",
"[",
"]",
"byte",
")",
"uint64",
"{",
"n",
",",
"val",
":=",
"len",
"(",
"data",
")",
",",
"uint64",
"(",
"0",
")",
"\n",
"if",
"n",
">",
"8",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"for",
"... | // bytes2int returns the int value it represents. | [
"bytes2int",
"returns",
"the",
"int",
"value",
"it",
"represents",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/util.go#L22-L32 | train |
shiyanhui/dht | util.go | int2bytes | func int2bytes(val uint64) []byte {
data, j := make([]byte, 8), -1
for i := 0; i < 8; i++ {
shift := uint64((7 - i) * 8)
data[i] = byte((val & (0xff << shift)) >> shift)
if j == -1 && data[i] != 0 {
j = i
}
}
if j != -1 {
return data[j:]
}
return data[:1]
} | go | func int2bytes(val uint64) []byte {
data, j := make([]byte, 8), -1
for i := 0; i < 8; i++ {
shift := uint64((7 - i) * 8)
data[i] = byte((val & (0xff << shift)) >> shift)
if j == -1 && data[i] != 0 {
j = i
}
}
if j != -1 {
return data[j:]
}
return data[:1]
} | [
"func",
"int2bytes",
"(",
"val",
"uint64",
")",
"[",
"]",
"byte",
"{",
"data",
",",
"j",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"8",
")",
",",
"-",
"1",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"8",
";",
"i",
"++",
"{",
"shift",
":=... | // int2bytes returns the byte array it represents. | [
"int2bytes",
"returns",
"the",
"byte",
"array",
"it",
"represents",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/util.go#L35-L50 | train |
shiyanhui/dht | util.go | getLocalIPs | func getLocalIPs() (ips []string) {
ips = make([]string, 0, 6)
addrs, err := net.InterfaceAddrs()
if err != nil {
return
}
for _, addr := range addrs {
ip, _, err := net.ParseCIDR(addr.String())
if err != nil {
continue
}
ips = append(ips, ip.String())
}
return
} | go | func getLocalIPs() (ips []string) {
ips = make([]string, 0, 6)
addrs, err := net.InterfaceAddrs()
if err != nil {
return
}
for _, addr := range addrs {
ip, _, err := net.ParseCIDR(addr.String())
if err != nil {
continue
}
ips = append(ips, ip.String())
}
return
} | [
"func",
"getLocalIPs",
"(",
")",
"(",
"ips",
"[",
"]",
"string",
")",
"{",
"ips",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"6",
")",
"\n\n",
"addrs",
",",
"err",
":=",
"net",
".",
"InterfaceAddrs",
"(",
")",
"\n",
"if",
"err",
"!=",... | // getLocalIPs returns local ips. | [
"getLocalIPs",
"returns",
"local",
"ips",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/util.go#L85-L101 | train |
shiyanhui/dht | util.go | getRemoteIP | func getRemoteIP() (ip string, err error) {
client := &http.Client{
Timeout: time.Second * 30,
}
req, err := http.NewRequest("GET", "http://ifconfig.me", nil)
if err != nil {
return
}
req.Header.Set("User-Agent", "curl")
res, err := client.Do(req)
if err != nil {
return
}
defer res.Body.Close()
dat... | go | func getRemoteIP() (ip string, err error) {
client := &http.Client{
Timeout: time.Second * 30,
}
req, err := http.NewRequest("GET", "http://ifconfig.me", nil)
if err != nil {
return
}
req.Header.Set("User-Agent", "curl")
res, err := client.Do(req)
if err != nil {
return
}
defer res.Body.Close()
dat... | [
"func",
"getRemoteIP",
"(",
")",
"(",
"ip",
"string",
",",
"err",
"error",
")",
"{",
"client",
":=",
"&",
"http",
".",
"Client",
"{",
"Timeout",
":",
"time",
".",
"Second",
"*",
"30",
",",
"}",
"\n\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRe... | // getRemoteIP returns the wlan ip. | [
"getRemoteIP",
"returns",
"the",
"wlan",
"ip",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/util.go#L104-L129 | train |
oklog/ulid | ulid.go | New | func New(ms uint64, entropy io.Reader) (id ULID, err error) {
if err = id.SetTime(ms); err != nil {
return id, err
}
switch e := entropy.(type) {
case nil:
return id, err
case MonotonicReader:
err = e.MonotonicRead(ms, id[6:])
default:
_, err = io.ReadFull(e, id[6:])
}
return id, err
} | go | func New(ms uint64, entropy io.Reader) (id ULID, err error) {
if err = id.SetTime(ms); err != nil {
return id, err
}
switch e := entropy.(type) {
case nil:
return id, err
case MonotonicReader:
err = e.MonotonicRead(ms, id[6:])
default:
_, err = io.ReadFull(e, id[6:])
}
return id, err
} | [
"func",
"New",
"(",
"ms",
"uint64",
",",
"entropy",
"io",
".",
"Reader",
")",
"(",
"id",
"ULID",
",",
"err",
"error",
")",
"{",
"if",
"err",
"=",
"id",
".",
"SetTime",
"(",
"ms",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"id",
",",
"err",
... | // New returns an ULID with the given Unix milliseconds timestamp and an
// optional entropy source. Use the Timestamp function to convert
// a time.Time to Unix milliseconds.
//
// ErrBigTime is returned when passing a timestamp bigger than MaxTime.
// Reading from the entropy source may also return an error.
//
// Sa... | [
"New",
"returns",
"an",
"ULID",
"with",
"the",
"given",
"Unix",
"milliseconds",
"timestamp",
"and",
"an",
"optional",
"entropy",
"source",
".",
"Use",
"the",
"Timestamp",
"function",
"to",
"convert",
"a",
"time",
".",
"Time",
"to",
"Unix",
"milliseconds",
".... | bacfb41fdd06edf5294635d18ec387dee671a964 | https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L97-L112 | train |
oklog/ulid | ulid.go | MustNew | func MustNew(ms uint64, entropy io.Reader) ULID {
id, err := New(ms, entropy)
if err != nil {
panic(err)
}
return id
} | go | func MustNew(ms uint64, entropy io.Reader) ULID {
id, err := New(ms, entropy)
if err != nil {
panic(err)
}
return id
} | [
"func",
"MustNew",
"(",
"ms",
"uint64",
",",
"entropy",
"io",
".",
"Reader",
")",
"ULID",
"{",
"id",
",",
"err",
":=",
"New",
"(",
"ms",
",",
"entropy",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"retur... | // MustNew is a convenience function equivalent to New that panics on failure
// instead of returning an error. | [
"MustNew",
"is",
"a",
"convenience",
"function",
"equivalent",
"to",
"New",
"that",
"panics",
"on",
"failure",
"instead",
"of",
"returning",
"an",
"error",
"."
] | bacfb41fdd06edf5294635d18ec387dee671a964 | https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L116-L122 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.