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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
brocaar/lorawan | fhdr.go | SetAddrPrefix | func (a *DevAddr) SetAddrPrefix(netID NetID) {
switch netID.Type() {
case 0:
a.setAddrPrefix(1, 6, netID)
case 1:
a.setAddrPrefix(2, 6, netID)
case 2:
a.setAddrPrefix(3, 9, netID)
case 3:
a.setAddrPrefix(4, 10, netID)
case 4:
a.setAddrPrefix(5, 11, netID)
case 5:
a.setAddrPrefix(6, 13, netID)
case 6:
a.setAddrPrefix(7, 15, netID)
case 7:
a.setAddrPrefix(8, 17, netID)
}
} | go | func (a *DevAddr) SetAddrPrefix(netID NetID) {
switch netID.Type() {
case 0:
a.setAddrPrefix(1, 6, netID)
case 1:
a.setAddrPrefix(2, 6, netID)
case 2:
a.setAddrPrefix(3, 9, netID)
case 3:
a.setAddrPrefix(4, 10, netID)
case 4:
a.setAddrPrefix(5, 11, netID)
case 5:
a.setAddrPrefix(6, 13, netID)
case 6:
a.setAddrPrefix(7, 15, netID)
case 7:
a.setAddrPrefix(8, 17, netID)
}
} | [
"func",
"(",
"a",
"*",
"DevAddr",
")",
"SetAddrPrefix",
"(",
"netID",
"NetID",
")",
"{",
"switch",
"netID",
".",
"Type",
"(",
")",
"{",
"case",
"0",
":",
"a",
".",
"setAddrPrefix",
"(",
"1",
",",
"6",
",",
"netID",
")",
"\n",
"case",
"1",
":",
"a",
".",
"setAddrPrefix",
"(",
"2",
",",
"6",
",",
"netID",
")",
"\n",
"case",
"2",
":",
"a",
".",
"setAddrPrefix",
"(",
"3",
",",
"9",
",",
"netID",
")",
"\n",
"case",
"3",
":",
"a",
".",
"setAddrPrefix",
"(",
"4",
",",
"10",
",",
"netID",
")",
"\n",
"case",
"4",
":",
"a",
".",
"setAddrPrefix",
"(",
"5",
",",
"11",
",",
"netID",
")",
"\n",
"case",
"5",
":",
"a",
".",
"setAddrPrefix",
"(",
"6",
",",
"13",
",",
"netID",
")",
"\n",
"case",
"6",
":",
"a",
".",
"setAddrPrefix",
"(",
"7",
",",
"15",
",",
"netID",
")",
"\n",
"case",
"7",
":",
"a",
".",
"setAddrPrefix",
"(",
"8",
",",
"17",
",",
"netID",
")",
"\n",
"}",
"\n",
"}"
] | // SetAddrPrefix sets the NetID based AddrPrefix. | [
"SetAddrPrefix",
"sets",
"the",
"NetID",
"based",
"AddrPrefix",
"."
] | 5bca41b178e93c384fb6442f55a2d692da890830 | https://github.com/brocaar/lorawan/blob/5bca41b178e93c384fb6442f55a2d692da890830/fhdr.go#L48-L67 | train |
brocaar/lorawan | fhdr.go | IsNetID | func (a DevAddr) IsNetID(netID NetID) bool {
tempDevAddr := a
tempDevAddr.SetAddrPrefix(netID)
if a == tempDevAddr {
return true
}
return false
} | go | func (a DevAddr) IsNetID(netID NetID) bool {
tempDevAddr := a
tempDevAddr.SetAddrPrefix(netID)
if a == tempDevAddr {
return true
}
return false
} | [
"func",
"(",
"a",
"DevAddr",
")",
"IsNetID",
"(",
"netID",
"NetID",
")",
"bool",
"{",
"tempDevAddr",
":=",
"a",
"\n",
"tempDevAddr",
".",
"SetAddrPrefix",
"(",
"netID",
")",
"\n\n",
"if",
"a",
"==",
"tempDevAddr",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
] | // IsNetID returns a bool indicating if the NwkID matches the given NetID. | [
"IsNetID",
"returns",
"a",
"bool",
"indicating",
"if",
"the",
"NwkID",
"matches",
"the",
"given",
"NetID",
"."
] | 5bca41b178e93c384fb6442f55a2d692da890830 | https://github.com/brocaar/lorawan/blob/5bca41b178e93c384fb6442f55a2d692da890830/fhdr.go#L70-L79 | train |
brocaar/lorawan | netid.go | ID | func (n NetID) ID() []byte {
switch n.Type() {
case 0, 1:
return n.getID(6)
case 2:
return n.getID(9)
case 3, 4, 5, 6, 7:
return n.getID(21)
default:
return nil
}
} | go | func (n NetID) ID() []byte {
switch n.Type() {
case 0, 1:
return n.getID(6)
case 2:
return n.getID(9)
case 3, 4, 5, 6, 7:
return n.getID(21)
default:
return nil
}
} | [
"func",
"(",
"n",
"NetID",
")",
"ID",
"(",
")",
"[",
"]",
"byte",
"{",
"switch",
"n",
".",
"Type",
"(",
")",
"{",
"case",
"0",
",",
"1",
":",
"return",
"n",
".",
"getID",
"(",
"6",
")",
"\n",
"case",
"2",
":",
"return",
"n",
".",
"getID",
"(",
"9",
")",
"\n",
"case",
"3",
",",
"4",
",",
"5",
",",
"6",
",",
"7",
":",
"return",
"n",
".",
"getID",
"(",
"21",
")",
"\n",
"default",
":",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // ID returns the NetID ID part. | [
"ID",
"returns",
"the",
"NetID",
"ID",
"part",
"."
] | 5bca41b178e93c384fb6442f55a2d692da890830 | https://github.com/brocaar/lorawan/blob/5bca41b178e93c384fb6442f55a2d692da890830/netid.go#L20-L31 | train |
brocaar/lorawan | airtime/airtime.go | CalculateLoRaAirtime | func CalculateLoRaAirtime(payloadSize, sf, bandwidth, preambleNumber int, codingRate CodingRate, headerEnabled, lowDataRateOptimization bool) (time.Duration, error) {
symbolDuration := CalculateLoRaSymbolDuration(sf, bandwidth)
preambleDuration := CalculateLoRaPreambleDuration(symbolDuration, preambleNumber)
payloadSymbolNumber, err := CalculateLoRaPayloadSymbolNumber(payloadSize, sf, codingRate, headerEnabled, lowDataRateOptimization)
if err != nil {
return 0, err
}
return preambleDuration + (time.Duration(payloadSymbolNumber) * symbolDuration), nil
} | go | func CalculateLoRaAirtime(payloadSize, sf, bandwidth, preambleNumber int, codingRate CodingRate, headerEnabled, lowDataRateOptimization bool) (time.Duration, error) {
symbolDuration := CalculateLoRaSymbolDuration(sf, bandwidth)
preambleDuration := CalculateLoRaPreambleDuration(symbolDuration, preambleNumber)
payloadSymbolNumber, err := CalculateLoRaPayloadSymbolNumber(payloadSize, sf, codingRate, headerEnabled, lowDataRateOptimization)
if err != nil {
return 0, err
}
return preambleDuration + (time.Duration(payloadSymbolNumber) * symbolDuration), nil
} | [
"func",
"CalculateLoRaAirtime",
"(",
"payloadSize",
",",
"sf",
",",
"bandwidth",
",",
"preambleNumber",
"int",
",",
"codingRate",
"CodingRate",
",",
"headerEnabled",
",",
"lowDataRateOptimization",
"bool",
")",
"(",
"time",
".",
"Duration",
",",
"error",
")",
"{",
"symbolDuration",
":=",
"CalculateLoRaSymbolDuration",
"(",
"sf",
",",
"bandwidth",
")",
"\n",
"preambleDuration",
":=",
"CalculateLoRaPreambleDuration",
"(",
"symbolDuration",
",",
"preambleNumber",
")",
"\n\n",
"payloadSymbolNumber",
",",
"err",
":=",
"CalculateLoRaPayloadSymbolNumber",
"(",
"payloadSize",
",",
"sf",
",",
"codingRate",
",",
"headerEnabled",
",",
"lowDataRateOptimization",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"preambleDuration",
"+",
"(",
"time",
".",
"Duration",
"(",
"payloadSymbolNumber",
")",
"*",
"symbolDuration",
")",
",",
"nil",
"\n",
"}"
] | // CalculateLoRaAirtime calculates the airtime for a LoRa modulated frame. | [
"CalculateLoRaAirtime",
"calculates",
"the",
"airtime",
"for",
"a",
"LoRa",
"modulated",
"frame",
"."
] | 5bca41b178e93c384fb6442f55a2d692da890830 | https://github.com/brocaar/lorawan/blob/5bca41b178e93c384fb6442f55a2d692da890830/airtime/airtime.go#L24-L34 | train |
brocaar/lorawan | airtime/airtime.go | CalculateLoRaSymbolDuration | func CalculateLoRaSymbolDuration(sf int, bandwidth int) time.Duration {
return time.Duration((1 << uint(sf)) * 1000000 / bandwidth)
} | go | func CalculateLoRaSymbolDuration(sf int, bandwidth int) time.Duration {
return time.Duration((1 << uint(sf)) * 1000000 / bandwidth)
} | [
"func",
"CalculateLoRaSymbolDuration",
"(",
"sf",
"int",
",",
"bandwidth",
"int",
")",
"time",
".",
"Duration",
"{",
"return",
"time",
".",
"Duration",
"(",
"(",
"1",
"<<",
"uint",
"(",
"sf",
")",
")",
"*",
"1000000",
"/",
"bandwidth",
")",
"\n",
"}"
] | // CalculateLoRaSymbolDuration calculates the LoRa symbol duration. | [
"CalculateLoRaSymbolDuration",
"calculates",
"the",
"LoRa",
"symbol",
"duration",
"."
] | 5bca41b178e93c384fb6442f55a2d692da890830 | https://github.com/brocaar/lorawan/blob/5bca41b178e93c384fb6442f55a2d692da890830/airtime/airtime.go#L37-L39 | train |
brocaar/lorawan | airtime/airtime.go | CalculateLoRaPreambleDuration | func CalculateLoRaPreambleDuration(symbolDuration time.Duration, preambleNumber int) time.Duration {
return time.Duration((100*preambleNumber)+425) * symbolDuration / 100
} | go | func CalculateLoRaPreambleDuration(symbolDuration time.Duration, preambleNumber int) time.Duration {
return time.Duration((100*preambleNumber)+425) * symbolDuration / 100
} | [
"func",
"CalculateLoRaPreambleDuration",
"(",
"symbolDuration",
"time",
".",
"Duration",
",",
"preambleNumber",
"int",
")",
"time",
".",
"Duration",
"{",
"return",
"time",
".",
"Duration",
"(",
"(",
"100",
"*",
"preambleNumber",
")",
"+",
"425",
")",
"*",
"symbolDuration",
"/",
"100",
"\n",
"}"
] | // CalculateLoRaPreambleDuration calculates the LoRa preamble duration. | [
"CalculateLoRaPreambleDuration",
"calculates",
"the",
"LoRa",
"preamble",
"duration",
"."
] | 5bca41b178e93c384fb6442f55a2d692da890830 | https://github.com/brocaar/lorawan/blob/5bca41b178e93c384fb6442f55a2d692da890830/airtime/airtime.go#L42-L44 | train |
brocaar/lorawan | airtime/airtime.go | CalculateLoRaPayloadSymbolNumber | func CalculateLoRaPayloadSymbolNumber(payloadSize, sf int, codingRate CodingRate, headerEnabled, lowDataRateOptimization bool) (int, error) {
var pl, spreadingFactor, h, de, cr float64
if codingRate < 1 || codingRate > 4 {
return 0, errors.New("codingRate must be between 1 - 4")
}
if lowDataRateOptimization {
de = 1
}
if !headerEnabled {
h = 1
}
pl = float64(payloadSize)
spreadingFactor = float64(sf)
cr = float64(codingRate)
a := 8*pl - 4*spreadingFactor + 28 + 16 - 20*h
b := 4 * (spreadingFactor - 2*de)
c := cr + 4
return int(8 + math.Max(math.Ceil(a/b)*c, 0)), nil
} | go | func CalculateLoRaPayloadSymbolNumber(payloadSize, sf int, codingRate CodingRate, headerEnabled, lowDataRateOptimization bool) (int, error) {
var pl, spreadingFactor, h, de, cr float64
if codingRate < 1 || codingRate > 4 {
return 0, errors.New("codingRate must be between 1 - 4")
}
if lowDataRateOptimization {
de = 1
}
if !headerEnabled {
h = 1
}
pl = float64(payloadSize)
spreadingFactor = float64(sf)
cr = float64(codingRate)
a := 8*pl - 4*spreadingFactor + 28 + 16 - 20*h
b := 4 * (spreadingFactor - 2*de)
c := cr + 4
return int(8 + math.Max(math.Ceil(a/b)*c, 0)), nil
} | [
"func",
"CalculateLoRaPayloadSymbolNumber",
"(",
"payloadSize",
",",
"sf",
"int",
",",
"codingRate",
"CodingRate",
",",
"headerEnabled",
",",
"lowDataRateOptimization",
"bool",
")",
"(",
"int",
",",
"error",
")",
"{",
"var",
"pl",
",",
"spreadingFactor",
",",
"h",
",",
"de",
",",
"cr",
"float64",
"\n\n",
"if",
"codingRate",
"<",
"1",
"||",
"codingRate",
">",
"4",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"lowDataRateOptimization",
"{",
"de",
"=",
"1",
"\n",
"}",
"\n\n",
"if",
"!",
"headerEnabled",
"{",
"h",
"=",
"1",
"\n",
"}",
"\n\n",
"pl",
"=",
"float64",
"(",
"payloadSize",
")",
"\n",
"spreadingFactor",
"=",
"float64",
"(",
"sf",
")",
"\n",
"cr",
"=",
"float64",
"(",
"codingRate",
")",
"\n\n",
"a",
":=",
"8",
"*",
"pl",
"-",
"4",
"*",
"spreadingFactor",
"+",
"28",
"+",
"16",
"-",
"20",
"*",
"h",
"\n",
"b",
":=",
"4",
"*",
"(",
"spreadingFactor",
"-",
"2",
"*",
"de",
")",
"\n",
"c",
":=",
"cr",
"+",
"4",
"\n\n",
"return",
"int",
"(",
"8",
"+",
"math",
".",
"Max",
"(",
"math",
".",
"Ceil",
"(",
"a",
"/",
"b",
")",
"*",
"c",
",",
"0",
")",
")",
",",
"nil",
"\n",
"}"
] | // CalculateLoRaPayloadSymbolNumber returns the number of symbols that make
// up the packet payload and header. | [
"CalculateLoRaPayloadSymbolNumber",
"returns",
"the",
"number",
"of",
"symbols",
"that",
"make",
"up",
"the",
"packet",
"payload",
"and",
"header",
"."
] | 5bca41b178e93c384fb6442f55a2d692da890830 | https://github.com/brocaar/lorawan/blob/5bca41b178e93c384fb6442f55a2d692da890830/airtime/airtime.go#L48-L72 | train |
brocaar/lorawan | applayer/fragmentation/encode.go | Encode | func Encode(data []byte, fragmentSize, redundancy int) ([][]byte, error) {
if len(data)%fragmentSize != 0 {
return nil, errors.New("length of data must be a multiple of the given fragment-size")
}
// fragment the data into rows
var dataRows [][]byte
for i := 0; i < len(data)/fragmentSize; i++ {
offset := i * fragmentSize
dataRows = append(dataRows, data[offset:offset+fragmentSize])
}
w := len(dataRows)
for y := 0; y < redundancy; y++ {
s := make([]byte, fragmentSize)
a := matrixLine(y+1, w)
for x := 0; x < w; x++ {
if a[x] == 1 {
for m := 0; m < fragmentSize; m++ {
s[m] ^= dataRows[x][m]
}
}
}
dataRows = append(dataRows, s)
}
return dataRows, nil
} | go | func Encode(data []byte, fragmentSize, redundancy int) ([][]byte, error) {
if len(data)%fragmentSize != 0 {
return nil, errors.New("length of data must be a multiple of the given fragment-size")
}
// fragment the data into rows
var dataRows [][]byte
for i := 0; i < len(data)/fragmentSize; i++ {
offset := i * fragmentSize
dataRows = append(dataRows, data[offset:offset+fragmentSize])
}
w := len(dataRows)
for y := 0; y < redundancy; y++ {
s := make([]byte, fragmentSize)
a := matrixLine(y+1, w)
for x := 0; x < w; x++ {
if a[x] == 1 {
for m := 0; m < fragmentSize; m++ {
s[m] ^= dataRows[x][m]
}
}
}
dataRows = append(dataRows, s)
}
return dataRows, nil
} | [
"func",
"Encode",
"(",
"data",
"[",
"]",
"byte",
",",
"fragmentSize",
",",
"redundancy",
"int",
")",
"(",
"[",
"]",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"len",
"(",
"data",
")",
"%",
"fragmentSize",
"!=",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// fragment the data into rows",
"var",
"dataRows",
"[",
"]",
"[",
"]",
"byte",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"data",
")",
"/",
"fragmentSize",
";",
"i",
"++",
"{",
"offset",
":=",
"i",
"*",
"fragmentSize",
"\n",
"dataRows",
"=",
"append",
"(",
"dataRows",
",",
"data",
"[",
"offset",
":",
"offset",
"+",
"fragmentSize",
"]",
")",
"\n",
"}",
"\n",
"w",
":=",
"len",
"(",
"dataRows",
")",
"\n\n",
"for",
"y",
":=",
"0",
";",
"y",
"<",
"redundancy",
";",
"y",
"++",
"{",
"s",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"fragmentSize",
")",
"\n",
"a",
":=",
"matrixLine",
"(",
"y",
"+",
"1",
",",
"w",
")",
"\n\n",
"for",
"x",
":=",
"0",
";",
"x",
"<",
"w",
";",
"x",
"++",
"{",
"if",
"a",
"[",
"x",
"]",
"==",
"1",
"{",
"for",
"m",
":=",
"0",
";",
"m",
"<",
"fragmentSize",
";",
"m",
"++",
"{",
"s",
"[",
"m",
"]",
"^=",
"dataRows",
"[",
"x",
"]",
"[",
"m",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"dataRows",
"=",
"append",
"(",
"dataRows",
",",
"s",
")",
"\n",
"}",
"\n\n",
"return",
"dataRows",
",",
"nil",
"\n",
"}"
] | // Encode encodes the given slice of bytes to fragments including forward error correction.
// This is based on the proposed FEC code from the Fragmented Data Block Transport over
// LoRaWAN recommendation. | [
"Encode",
"encodes",
"the",
"given",
"slice",
"of",
"bytes",
"to",
"fragments",
"including",
"forward",
"error",
"correction",
".",
"This",
"is",
"based",
"on",
"the",
"proposed",
"FEC",
"code",
"from",
"the",
"Fragmented",
"Data",
"Block",
"Transport",
"over",
"LoRaWAN",
"recommendation",
"."
] | 5bca41b178e93c384fb6442f55a2d692da890830 | https://github.com/brocaar/lorawan/blob/5bca41b178e93c384fb6442f55a2d692da890830/applayer/fragmentation/encode.go#L10-L39 | train |
brocaar/lorawan | backend/joinserver/session_keys.go | getJSIntKey | func getJSIntKey(nwkKey lorawan.AES128Key, devEUI lorawan.EUI64) (lorawan.AES128Key, error) {
return getJSKey(0x06, devEUI, nwkKey)
} | go | func getJSIntKey(nwkKey lorawan.AES128Key, devEUI lorawan.EUI64) (lorawan.AES128Key, error) {
return getJSKey(0x06, devEUI, nwkKey)
} | [
"func",
"getJSIntKey",
"(",
"nwkKey",
"lorawan",
".",
"AES128Key",
",",
"devEUI",
"lorawan",
".",
"EUI64",
")",
"(",
"lorawan",
".",
"AES128Key",
",",
"error",
")",
"{",
"return",
"getJSKey",
"(",
"0x06",
",",
"devEUI",
",",
"nwkKey",
")",
"\n",
"}"
] | // getJSIntKey returns the JSIntKey. | [
"getJSIntKey",
"returns",
"the",
"JSIntKey",
"."
] | 5bca41b178e93c384fb6442f55a2d692da890830 | https://github.com/brocaar/lorawan/blob/5bca41b178e93c384fb6442f55a2d692da890830/backend/joinserver/session_keys.go#L34-L36 | train |
brocaar/lorawan | backend/joinserver/session_keys.go | getJSEncKey | func getJSEncKey(nwkKey lorawan.AES128Key, devEUI lorawan.EUI64) (lorawan.AES128Key, error) {
return getJSKey(0x05, devEUI, nwkKey)
} | go | func getJSEncKey(nwkKey lorawan.AES128Key, devEUI lorawan.EUI64) (lorawan.AES128Key, error) {
return getJSKey(0x05, devEUI, nwkKey)
} | [
"func",
"getJSEncKey",
"(",
"nwkKey",
"lorawan",
".",
"AES128Key",
",",
"devEUI",
"lorawan",
".",
"EUI64",
")",
"(",
"lorawan",
".",
"AES128Key",
",",
"error",
")",
"{",
"return",
"getJSKey",
"(",
"0x05",
",",
"devEUI",
",",
"nwkKey",
")",
"\n",
"}"
] | // getJSEncKey returns the JSEncKey. | [
"getJSEncKey",
"returns",
"the",
"JSEncKey",
"."
] | 5bca41b178e93c384fb6442f55a2d692da890830 | https://github.com/brocaar/lorawan/blob/5bca41b178e93c384fb6442f55a2d692da890830/backend/joinserver/session_keys.go#L39-L41 | train |
brocaar/lorawan | band/band.go | intSliceDiff | func intSliceDiff(x, y []int) []int {
var out []int
for _, cX := range x {
found := false
for _, cY := range y {
if cX == cY {
found = true
break
}
}
if !found {
out = append(out, cX)
}
}
for _, cY := range y {
found := false
for _, cX := range x {
if cY == cX {
found = true
break
}
}
if !found {
out = append(out, cY)
}
}
return out
} | go | func intSliceDiff(x, y []int) []int {
var out []int
for _, cX := range x {
found := false
for _, cY := range y {
if cX == cY {
found = true
break
}
}
if !found {
out = append(out, cX)
}
}
for _, cY := range y {
found := false
for _, cX := range x {
if cY == cX {
found = true
break
}
}
if !found {
out = append(out, cY)
}
}
return out
} | [
"func",
"intSliceDiff",
"(",
"x",
",",
"y",
"[",
"]",
"int",
")",
"[",
"]",
"int",
"{",
"var",
"out",
"[",
"]",
"int",
"\n\n",
"for",
"_",
",",
"cX",
":=",
"range",
"x",
"{",
"found",
":=",
"false",
"\n",
"for",
"_",
",",
"cY",
":=",
"range",
"y",
"{",
"if",
"cX",
"==",
"cY",
"{",
"found",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"found",
"{",
"out",
"=",
"append",
"(",
"out",
",",
"cX",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"cY",
":=",
"range",
"y",
"{",
"found",
":=",
"false",
"\n",
"for",
"_",
",",
"cX",
":=",
"range",
"x",
"{",
"if",
"cY",
"==",
"cX",
"{",
"found",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"found",
"{",
"out",
"=",
"append",
"(",
"out",
",",
"cY",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"out",
"\n",
"}"
] | // y that are not in x. | [
"y",
"that",
"are",
"not",
"in",
"x",
"."
] | 5bca41b178e93c384fb6442f55a2d692da890830 | https://github.com/brocaar/lorawan/blob/5bca41b178e93c384fb6442f55a2d692da890830/band/band.go#L558-L588 | train |
brocaar/lorawan | band/band.go | GetConfig | func GetConfig(name Name, repeaterCompatible bool, dt lorawan.DwellTime) (Band, error) {
switch name {
case AS_923, AS923:
return newAS923Band(repeaterCompatible, dt)
case AU_915_928, AU915:
return newAU915Band(repeaterCompatible, dt)
case CN_470_510, CN470:
return newCN470Band(repeaterCompatible)
case CN_779_787, CN779:
return newCN779Band(repeaterCompatible)
case EU_433, EU433:
return newEU433Band(repeaterCompatible)
case EU_863_870, EU868:
return newEU863Band(repeaterCompatible)
case IN_865_867, IN865:
return newIN865Band(repeaterCompatible)
case KR_920_923, KR920:
return newKR920Band(repeaterCompatible)
case US_902_928, US915:
return newUS902Band(repeaterCompatible)
case RU_864_870, RU864:
return newRU864Band(repeaterCompatible)
default:
return nil, fmt.Errorf("lorawan/band: band %s is undefined", name)
}
} | go | func GetConfig(name Name, repeaterCompatible bool, dt lorawan.DwellTime) (Band, error) {
switch name {
case AS_923, AS923:
return newAS923Band(repeaterCompatible, dt)
case AU_915_928, AU915:
return newAU915Band(repeaterCompatible, dt)
case CN_470_510, CN470:
return newCN470Band(repeaterCompatible)
case CN_779_787, CN779:
return newCN779Band(repeaterCompatible)
case EU_433, EU433:
return newEU433Band(repeaterCompatible)
case EU_863_870, EU868:
return newEU863Band(repeaterCompatible)
case IN_865_867, IN865:
return newIN865Band(repeaterCompatible)
case KR_920_923, KR920:
return newKR920Band(repeaterCompatible)
case US_902_928, US915:
return newUS902Band(repeaterCompatible)
case RU_864_870, RU864:
return newRU864Band(repeaterCompatible)
default:
return nil, fmt.Errorf("lorawan/band: band %s is undefined", name)
}
} | [
"func",
"GetConfig",
"(",
"name",
"Name",
",",
"repeaterCompatible",
"bool",
",",
"dt",
"lorawan",
".",
"DwellTime",
")",
"(",
"Band",
",",
"error",
")",
"{",
"switch",
"name",
"{",
"case",
"AS_923",
",",
"AS923",
":",
"return",
"newAS923Band",
"(",
"repeaterCompatible",
",",
"dt",
")",
"\n",
"case",
"AU_915_928",
",",
"AU915",
":",
"return",
"newAU915Band",
"(",
"repeaterCompatible",
",",
"dt",
")",
"\n",
"case",
"CN_470_510",
",",
"CN470",
":",
"return",
"newCN470Band",
"(",
"repeaterCompatible",
")",
"\n",
"case",
"CN_779_787",
",",
"CN779",
":",
"return",
"newCN779Band",
"(",
"repeaterCompatible",
")",
"\n",
"case",
"EU_433",
",",
"EU433",
":",
"return",
"newEU433Band",
"(",
"repeaterCompatible",
")",
"\n",
"case",
"EU_863_870",
",",
"EU868",
":",
"return",
"newEU863Band",
"(",
"repeaterCompatible",
")",
"\n",
"case",
"IN_865_867",
",",
"IN865",
":",
"return",
"newIN865Band",
"(",
"repeaterCompatible",
")",
"\n",
"case",
"KR_920_923",
",",
"KR920",
":",
"return",
"newKR920Band",
"(",
"repeaterCompatible",
")",
"\n",
"case",
"US_902_928",
",",
"US915",
":",
"return",
"newUS902Band",
"(",
"repeaterCompatible",
")",
"\n",
"case",
"RU_864_870",
",",
"RU864",
":",
"return",
"newRU864Band",
"(",
"repeaterCompatible",
")",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"}"
] | // GetConfig returns the band configuration for the given band.
// Please refer to the LoRaWAN specification for more details about the effect
// of the repeater and dwell time arguments. | [
"GetConfig",
"returns",
"the",
"band",
"configuration",
"for",
"the",
"given",
"band",
".",
"Please",
"refer",
"to",
"the",
"LoRaWAN",
"specification",
"for",
"more",
"details",
"about",
"the",
"effect",
"of",
"the",
"repeater",
"and",
"dwell",
"time",
"arguments",
"."
] | 5bca41b178e93c384fb6442f55a2d692da890830 | https://github.com/brocaar/lorawan/blob/5bca41b178e93c384fb6442f55a2d692da890830/band/band.go#L602-L627 | train |
brocaar/lorawan | mac_commands.go | GetMACPayloadAndSize | func GetMACPayloadAndSize(uplink bool, c CID) (MACCommandPayload, int, error) {
macPayloadMutex.RLock()
defer macPayloadMutex.RUnlock()
v, ok := macPayloadRegistry[uplink][c]
if !ok {
return nil, 0, fmt.Errorf("lorawan: payload unknown for uplink=%v and CID=%v", uplink, c)
}
return v.payload(), v.size, nil
} | go | func GetMACPayloadAndSize(uplink bool, c CID) (MACCommandPayload, int, error) {
macPayloadMutex.RLock()
defer macPayloadMutex.RUnlock()
v, ok := macPayloadRegistry[uplink][c]
if !ok {
return nil, 0, fmt.Errorf("lorawan: payload unknown for uplink=%v and CID=%v", uplink, c)
}
return v.payload(), v.size, nil
} | [
"func",
"GetMACPayloadAndSize",
"(",
"uplink",
"bool",
",",
"c",
"CID",
")",
"(",
"MACCommandPayload",
",",
"int",
",",
"error",
")",
"{",
"macPayloadMutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"macPayloadMutex",
".",
"RUnlock",
"(",
")",
"\n\n",
"v",
",",
"ok",
":=",
"macPayloadRegistry",
"[",
"uplink",
"]",
"[",
"c",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"uplink",
",",
"c",
")",
"\n",
"}",
"\n\n",
"return",
"v",
".",
"payload",
"(",
")",
",",
"v",
".",
"size",
",",
"nil",
"\n",
"}"
] | // GetMACPayloadAndSize returns a new MACCommandPayload instance and it's size. | [
"GetMACPayloadAndSize",
"returns",
"a",
"new",
"MACCommandPayload",
"instance",
"and",
"it",
"s",
"size",
"."
] | 5bca41b178e93c384fb6442f55a2d692da890830 | https://github.com/brocaar/lorawan/blob/5bca41b178e93c384fb6442f55a2d692da890830/mac_commands.go#L134-L144 | train |
brocaar/lorawan | mac_commands.go | RegisterProprietaryMACCommand | func RegisterProprietaryMACCommand(uplink bool, cid CID, payloadSize int) error {
if !(cid >= 128 && cid <= 255) {
return fmt.Errorf("lorawan: invalid CID %x", byte(cid))
}
if payloadSize == 0 {
// no need to register the payload size
return nil
}
macPayloadMutex.Lock()
defer macPayloadMutex.Unlock()
macPayloadRegistry[uplink][cid] = macPayloadInfo{
size: payloadSize,
payload: func() MACCommandPayload { return &ProprietaryMACCommandPayload{} },
}
return nil
} | go | func RegisterProprietaryMACCommand(uplink bool, cid CID, payloadSize int) error {
if !(cid >= 128 && cid <= 255) {
return fmt.Errorf("lorawan: invalid CID %x", byte(cid))
}
if payloadSize == 0 {
// no need to register the payload size
return nil
}
macPayloadMutex.Lock()
defer macPayloadMutex.Unlock()
macPayloadRegistry[uplink][cid] = macPayloadInfo{
size: payloadSize,
payload: func() MACCommandPayload { return &ProprietaryMACCommandPayload{} },
}
return nil
} | [
"func",
"RegisterProprietaryMACCommand",
"(",
"uplink",
"bool",
",",
"cid",
"CID",
",",
"payloadSize",
"int",
")",
"error",
"{",
"if",
"!",
"(",
"cid",
">=",
"128",
"&&",
"cid",
"<=",
"255",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"byte",
"(",
"cid",
")",
")",
"\n",
"}",
"\n\n",
"if",
"payloadSize",
"==",
"0",
"{",
"// no need to register the payload size",
"return",
"nil",
"\n",
"}",
"\n\n",
"macPayloadMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"macPayloadMutex",
".",
"Unlock",
"(",
")",
"\n\n",
"macPayloadRegistry",
"[",
"uplink",
"]",
"[",
"cid",
"]",
"=",
"macPayloadInfo",
"{",
"size",
":",
"payloadSize",
",",
"payload",
":",
"func",
"(",
")",
"MACCommandPayload",
"{",
"return",
"&",
"ProprietaryMACCommandPayload",
"{",
"}",
"}",
",",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // RegisterProprietaryMACCommand registers a proprietary MAC command. Note
// that there is no need to call this when the size of the payload is > 0 bytes. | [
"RegisterProprietaryMACCommand",
"registers",
"a",
"proprietary",
"MAC",
"command",
".",
"Note",
"that",
"there",
"is",
"no",
"need",
"to",
"call",
"this",
"when",
"the",
"size",
"of",
"the",
"payload",
"is",
">",
"0",
"bytes",
"."
] | 5bca41b178e93c384fb6442f55a2d692da890830 | https://github.com/brocaar/lorawan/blob/5bca41b178e93c384fb6442f55a2d692da890830/mac_commands.go#L148-L167 | train |
brocaar/lorawan | mac_commands.go | UnmarshalBinary | func (p *ProprietaryMACCommandPayload) UnmarshalBinary(data []byte) error {
p.Bytes = data
return nil
} | go | func (p *ProprietaryMACCommandPayload) UnmarshalBinary(data []byte) error {
p.Bytes = data
return nil
} | [
"func",
"(",
"p",
"*",
"ProprietaryMACCommandPayload",
")",
"UnmarshalBinary",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"p",
".",
"Bytes",
"=",
"data",
"\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalBinary decodes the object from a slice of bytes. | [
"UnmarshalBinary",
"decodes",
"the",
"object",
"from",
"a",
"slice",
"of",
"bytes",
"."
] | 5bca41b178e93c384fb6442f55a2d692da890830 | https://github.com/brocaar/lorawan/blob/5bca41b178e93c384fb6442f55a2d692da890830/mac_commands.go#L228-L231 | train |
brocaar/lorawan | mac_commands.go | MarshalBinary | func (p TXParamSetupReqPayload) MarshalBinary() ([]byte, error) {
var b uint8
for i, v := range []uint8{8, 10, 12, 13, 14, 16, 18, 20, 21, 24, 26, 27, 29, 30, 33, 36} {
if v == p.MaxEIRP {
b = uint8(i)
}
}
if b == 0 {
return nil, errors.New("lorawan: invalid MaxEIRP value")
}
if p.UplinkDwellTime == DwellTime400ms {
b = b ^ (1 << 4)
}
if p.DownlinkDwelltime == DwellTime400ms {
b = b ^ (1 << 5)
}
return []byte{b}, nil
} | go | func (p TXParamSetupReqPayload) MarshalBinary() ([]byte, error) {
var b uint8
for i, v := range []uint8{8, 10, 12, 13, 14, 16, 18, 20, 21, 24, 26, 27, 29, 30, 33, 36} {
if v == p.MaxEIRP {
b = uint8(i)
}
}
if b == 0 {
return nil, errors.New("lorawan: invalid MaxEIRP value")
}
if p.UplinkDwellTime == DwellTime400ms {
b = b ^ (1 << 4)
}
if p.DownlinkDwelltime == DwellTime400ms {
b = b ^ (1 << 5)
}
return []byte{b}, nil
} | [
"func",
"(",
"p",
"TXParamSetupReqPayload",
")",
"MarshalBinary",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"b",
"uint8",
"\n",
"for",
"i",
",",
"v",
":=",
"range",
"[",
"]",
"uint8",
"{",
"8",
",",
"10",
",",
"12",
",",
"13",
",",
"14",
",",
"16",
",",
"18",
",",
"20",
",",
"21",
",",
"24",
",",
"26",
",",
"27",
",",
"29",
",",
"30",
",",
"33",
",",
"36",
"}",
"{",
"if",
"v",
"==",
"p",
".",
"MaxEIRP",
"{",
"b",
"=",
"uint8",
"(",
"i",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"b",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"p",
".",
"UplinkDwellTime",
"==",
"DwellTime400ms",
"{",
"b",
"=",
"b",
"^",
"(",
"1",
"<<",
"4",
")",
"\n",
"}",
"\n",
"if",
"p",
".",
"DownlinkDwelltime",
"==",
"DwellTime400ms",
"{",
"b",
"=",
"b",
"^",
"(",
"1",
"<<",
"5",
")",
"\n",
"}",
"\n\n",
"return",
"[",
"]",
"byte",
"{",
"b",
"}",
",",
"nil",
"\n",
"}"
] | // MarshalBinary encodes the object into a bytes. | [
"MarshalBinary",
"encodes",
"the",
"object",
"into",
"a",
"bytes",
"."
] | 5bca41b178e93c384fb6442f55a2d692da890830 | https://github.com/brocaar/lorawan/blob/5bca41b178e93c384fb6442f55a2d692da890830/mac_commands.go#L706-L725 | train |
brocaar/lorawan | mac_commands.go | decodeDataPayloadToMACCommands | func decodeDataPayloadToMACCommands(uplink bool, payloads []Payload) ([]Payload, error) {
if len(payloads) != 1 {
return nil, errors.New("lorawan: exactly one Payload expected")
}
dataPL, ok := payloads[0].(*DataPayload)
if !ok {
return nil, fmt.Errorf("lorawan: expected *DataPayload, got %T", payloads[0])
}
var plLen int
var out []Payload
for i := 0; i < len(dataPL.Bytes); i++ {
if _, s, err := GetMACPayloadAndSize(uplink, CID(dataPL.Bytes[i])); err != nil {
plLen = 0
} else {
plLen = s
}
if len(dataPL.Bytes[i:]) < plLen+1 {
return nil, errors.New("lorawan: not enough remaining bytes")
}
mc := &MACCommand{}
if err := mc.UnmarshalBinary(uplink, dataPL.Bytes[i:i+1+plLen]); err != nil {
log.Printf("warning: unmarshal mac-command error (skipping remaining mac-command bytes): %s", err)
}
out = append(out, mc)
i = i + plLen
}
return out, nil
} | go | func decodeDataPayloadToMACCommands(uplink bool, payloads []Payload) ([]Payload, error) {
if len(payloads) != 1 {
return nil, errors.New("lorawan: exactly one Payload expected")
}
dataPL, ok := payloads[0].(*DataPayload)
if !ok {
return nil, fmt.Errorf("lorawan: expected *DataPayload, got %T", payloads[0])
}
var plLen int
var out []Payload
for i := 0; i < len(dataPL.Bytes); i++ {
if _, s, err := GetMACPayloadAndSize(uplink, CID(dataPL.Bytes[i])); err != nil {
plLen = 0
} else {
plLen = s
}
if len(dataPL.Bytes[i:]) < plLen+1 {
return nil, errors.New("lorawan: not enough remaining bytes")
}
mc := &MACCommand{}
if err := mc.UnmarshalBinary(uplink, dataPL.Bytes[i:i+1+plLen]); err != nil {
log.Printf("warning: unmarshal mac-command error (skipping remaining mac-command bytes): %s", err)
}
out = append(out, mc)
i = i + plLen
}
return out, nil
} | [
"func",
"decodeDataPayloadToMACCommands",
"(",
"uplink",
"bool",
",",
"payloads",
"[",
"]",
"Payload",
")",
"(",
"[",
"]",
"Payload",
",",
"error",
")",
"{",
"if",
"len",
"(",
"payloads",
")",
"!=",
"1",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"dataPL",
",",
"ok",
":=",
"payloads",
"[",
"0",
"]",
".",
"(",
"*",
"DataPayload",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"payloads",
"[",
"0",
"]",
")",
"\n",
"}",
"\n\n",
"var",
"plLen",
"int",
"\n",
"var",
"out",
"[",
"]",
"Payload",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"dataPL",
".",
"Bytes",
")",
";",
"i",
"++",
"{",
"if",
"_",
",",
"s",
",",
"err",
":=",
"GetMACPayloadAndSize",
"(",
"uplink",
",",
"CID",
"(",
"dataPL",
".",
"Bytes",
"[",
"i",
"]",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"plLen",
"=",
"0",
"\n",
"}",
"else",
"{",
"plLen",
"=",
"s",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"dataPL",
".",
"Bytes",
"[",
"i",
":",
"]",
")",
"<",
"plLen",
"+",
"1",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"mc",
":=",
"&",
"MACCommand",
"{",
"}",
"\n",
"if",
"err",
":=",
"mc",
".",
"UnmarshalBinary",
"(",
"uplink",
",",
"dataPL",
".",
"Bytes",
"[",
"i",
":",
"i",
"+",
"1",
"+",
"plLen",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"out",
"=",
"append",
"(",
"out",
",",
"mc",
")",
"\n",
"i",
"=",
"i",
"+",
"plLen",
"\n",
"}",
"\n\n",
"return",
"out",
",",
"nil",
"\n",
"}"
] | // decodeDataPayloadToMACCommands decodes a DataPayload into a slice of
// MACCommands. | [
"decodeDataPayloadToMACCommands",
"decodes",
"a",
"DataPayload",
"into",
"a",
"slice",
"of",
"MACCommands",
"."
] | 5bca41b178e93c384fb6442f55a2d692da890830 | https://github.com/brocaar/lorawan/blob/5bca41b178e93c384fb6442f55a2d692da890830/mac_commands.go#L1278-L1312 | train |
brocaar/lorawan | applayer/clocksync/clocksync.go | UnmarshalBinary | func (p *AppTimeAnsPayload) UnmarshalBinary(data []byte) error {
if len(data) < p.Size() {
return fmt.Errorf("lorawan/applayer/clocksync: %d bytes are expected", p.Size())
}
p.TimeCorrection = int32(binary.LittleEndian.Uint32(data[0:4]))
p.Param.TokenAns = uint8(data[4] & 0x0f)
return nil
} | go | func (p *AppTimeAnsPayload) UnmarshalBinary(data []byte) error {
if len(data) < p.Size() {
return fmt.Errorf("lorawan/applayer/clocksync: %d bytes are expected", p.Size())
}
p.TimeCorrection = int32(binary.LittleEndian.Uint32(data[0:4]))
p.Param.TokenAns = uint8(data[4] & 0x0f)
return nil
} | [
"func",
"(",
"p",
"*",
"AppTimeAnsPayload",
")",
"UnmarshalBinary",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"len",
"(",
"data",
")",
"<",
"p",
".",
"Size",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"p",
".",
"Size",
"(",
")",
")",
"\n",
"}",
"\n\n",
"p",
".",
"TimeCorrection",
"=",
"int32",
"(",
"binary",
".",
"LittleEndian",
".",
"Uint32",
"(",
"data",
"[",
"0",
":",
"4",
"]",
")",
")",
"\n",
"p",
".",
"Param",
".",
"TokenAns",
"=",
"uint8",
"(",
"data",
"[",
"4",
"]",
"&",
"0x0f",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalBinary decoces the payload from a slice of bytes. | [
"UnmarshalBinary",
"decoces",
"the",
"payload",
"from",
"a",
"slice",
"of",
"bytes",
"."
] | 5bca41b178e93c384fb6442f55a2d692da890830 | https://github.com/brocaar/lorawan/blob/5bca41b178e93c384fb6442f55a2d692da890830/applayer/clocksync/clocksync.go#L253-L262 | train |
brocaar/lorawan | applayer/fragmentation/fragmentation.go | MarshalBinary | func (p DataFragmentPayload) MarshalBinary() ([]byte, error) {
b := make([]byte, p.Size())
binary.LittleEndian.PutUint16(b[0:2], p.IndexAndN.N&0x3fff)
b[1] |= (p.IndexAndN.FragIndex & 0x03) << 6
copy(b[2:], p.Payload)
return b, nil
} | go | func (p DataFragmentPayload) MarshalBinary() ([]byte, error) {
b := make([]byte, p.Size())
binary.LittleEndian.PutUint16(b[0:2], p.IndexAndN.N&0x3fff)
b[1] |= (p.IndexAndN.FragIndex & 0x03) << 6
copy(b[2:], p.Payload)
return b, nil
} | [
"func",
"(",
"p",
"DataFragmentPayload",
")",
"MarshalBinary",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"p",
".",
"Size",
"(",
")",
")",
"\n\n",
"binary",
".",
"LittleEndian",
".",
"PutUint16",
"(",
"b",
"[",
"0",
":",
"2",
"]",
",",
"p",
".",
"IndexAndN",
".",
"N",
"&",
"0x3fff",
")",
"\n",
"b",
"[",
"1",
"]",
"|=",
"(",
"p",
".",
"IndexAndN",
".",
"FragIndex",
"&",
"0x03",
")",
"<<",
"6",
"\n",
"copy",
"(",
"b",
"[",
"2",
":",
"]",
",",
"p",
".",
"Payload",
")",
"\n\n",
"return",
"b",
",",
"nil",
"\n",
"}"
] | // MarshalBinary encodes the given payload to a slice of bytes. | [
"MarshalBinary",
"encodes",
"the",
"given",
"payload",
"to",
"a",
"slice",
"of",
"bytes",
"."
] | 5bca41b178e93c384fb6442f55a2d692da890830 | https://github.com/brocaar/lorawan/blob/5bca41b178e93c384fb6442f55a2d692da890830/applayer/fragmentation/fragmentation.go#L419-L427 | train |
Netflix/rend | server/listen.go | TCPListener | func TCPListener(port int) ListenConst {
return func() (Listener, error) {
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
return nil, fmt.Errorf("Error binding to port %d: %v", port, err.Error())
}
return &tcpListener{listener: listener}, nil
}
} | go | func TCPListener(port int) ListenConst {
return func() (Listener, error) {
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
return nil, fmt.Errorf("Error binding to port %d: %v", port, err.Error())
}
return &tcpListener{listener: listener}, nil
}
} | [
"func",
"TCPListener",
"(",
"port",
"int",
")",
"ListenConst",
"{",
"return",
"func",
"(",
")",
"(",
"Listener",
",",
"error",
")",
"{",
"listener",
",",
"err",
":=",
"net",
".",
"Listen",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"port",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"port",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"&",
"tcpListener",
"{",
"listener",
":",
"listener",
"}",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // TCPListener is a ListenConst that returns a tcp listener for the given port | [
"TCPListener",
"is",
"a",
"ListenConst",
"that",
"returns",
"a",
"tcp",
"listener",
"for",
"the",
"given",
"port"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/server/listen.go#L55-L63 | train |
Netflix/rend | server/listen.go | UnixListener | func UnixListener(path string) ListenConst {
return func() (Listener, error) {
err := os.Remove(path)
if err != nil && !os.IsNotExist(err) {
return nil, fmt.Errorf("Error removing previous unix socket file at %s", path)
}
listener, err := net.Listen("unix", path)
if err != nil {
return nil, fmt.Errorf("Error binding to unix socket at %s: %v", path, err.Error())
}
return &unixListener{listener: listener}, nil
}
} | go | func UnixListener(path string) ListenConst {
return func() (Listener, error) {
err := os.Remove(path)
if err != nil && !os.IsNotExist(err) {
return nil, fmt.Errorf("Error removing previous unix socket file at %s", path)
}
listener, err := net.Listen("unix", path)
if err != nil {
return nil, fmt.Errorf("Error binding to unix socket at %s: %v", path, err.Error())
}
return &unixListener{listener: listener}, nil
}
} | [
"func",
"UnixListener",
"(",
"path",
"string",
")",
"ListenConst",
"{",
"return",
"func",
"(",
")",
"(",
"Listener",
",",
"error",
")",
"{",
"err",
":=",
"os",
".",
"Remove",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"path",
")",
"\n",
"}",
"\n\n",
"listener",
",",
"err",
":=",
"net",
".",
"Listen",
"(",
"\"",
"\"",
",",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"path",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"unixListener",
"{",
"listener",
":",
"listener",
"}",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // UnixListener is a ListenConst that returns a unix domain socket listener for the given path | [
"UnixListener",
"is",
"a",
"ListenConst",
"that",
"returns",
"a",
"unix",
"domain",
"socket",
"listener",
"for",
"the",
"given",
"path"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/server/listen.go#L78-L92 | train |
Netflix/rend | metrics/bulkcallback.go | RegisterBulkCallback | func RegisterBulkCallback(bcb BulkCallback) {
id := atomic.AddUint32(curBulkCbID, 1) - 1
if id >= maxNumCallbacks {
panic("Too many callbacks")
}
bulkCBs[id] = bcb
} | go | func RegisterBulkCallback(bcb BulkCallback) {
id := atomic.AddUint32(curBulkCbID, 1) - 1
if id >= maxNumCallbacks {
panic("Too many callbacks")
}
bulkCBs[id] = bcb
} | [
"func",
"RegisterBulkCallback",
"(",
"bcb",
"BulkCallback",
")",
"{",
"id",
":=",
"atomic",
".",
"AddUint32",
"(",
"curBulkCbID",
",",
"1",
")",
"-",
"1",
"\n\n",
"if",
"id",
">=",
"maxNumCallbacks",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"bulkCBs",
"[",
"id",
"]",
"=",
"bcb",
"\n",
"}"
] | // RegisterBulkCallback registers a bulk callback which will be called every time
// metrics are requested.
// There is a maximum of 1024 bulk callbacks, after which adding a new one will panic. | [
"RegisterBulkCallback",
"registers",
"a",
"bulk",
"callback",
"which",
"will",
"be",
"called",
"every",
"time",
"metrics",
"are",
"requested",
".",
"There",
"is",
"a",
"maximum",
"of",
"1024",
"bulk",
"callbacks",
"after",
"which",
"adding",
"a",
"new",
"one",
"will",
"panic",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/metrics/bulkcallback.go#L38-L46 | train |
Netflix/rend | metrics/gauges.go | AddIntGauge | func AddIntGauge(name string, tgs Tags) uint32 {
id := atomic.AddUint32(curIntGaugeID, 1) - 1
if id >= maxNumGauges {
panic("Too many int gauges")
}
intgnames[id] = name
tgs = copyTags(tgs)
tgs[TagMetricType] = MetricTypeGauge
tgs[TagDataType] = DataTypeUint64
intgtags[id] = tgs
return id
} | go | func AddIntGauge(name string, tgs Tags) uint32 {
id := atomic.AddUint32(curIntGaugeID, 1) - 1
if id >= maxNumGauges {
panic("Too many int gauges")
}
intgnames[id] = name
tgs = copyTags(tgs)
tgs[TagMetricType] = MetricTypeGauge
tgs[TagDataType] = DataTypeUint64
intgtags[id] = tgs
return id
} | [
"func",
"AddIntGauge",
"(",
"name",
"string",
",",
"tgs",
"Tags",
")",
"uint32",
"{",
"id",
":=",
"atomic",
".",
"AddUint32",
"(",
"curIntGaugeID",
",",
"1",
")",
"-",
"1",
"\n\n",
"if",
"id",
">=",
"maxNumGauges",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"intgnames",
"[",
"id",
"]",
"=",
"name",
"\n\n",
"tgs",
"=",
"copyTags",
"(",
"tgs",
")",
"\n",
"tgs",
"[",
"TagMetricType",
"]",
"=",
"MetricTypeGauge",
"\n",
"tgs",
"[",
"TagDataType",
"]",
"=",
"DataTypeUint64",
"\n",
"intgtags",
"[",
"id",
"]",
"=",
"tgs",
"\n\n",
"return",
"id",
"\n",
"}"
] | // AddIntGauge registers an integer-based gauge and returns an ID that can be
// used to update it.
// There is a maximum of 1024 gauges, after which adding a new one will panic | [
"AddIntGauge",
"registers",
"an",
"integer",
"-",
"based",
"gauge",
"and",
"returns",
"an",
"ID",
"that",
"can",
"be",
"used",
"to",
"update",
"it",
".",
"There",
"is",
"a",
"maximum",
"of",
"1024",
"gauges",
"after",
"which",
"adding",
"a",
"new",
"one",
"will",
"panic"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/metrics/gauges.go#L39-L54 | train |
Netflix/rend | metrics/gauges.go | AddFloatGauge | func AddFloatGauge(name string, tgs Tags) uint32 {
id := atomic.AddUint32(curFloatGaugeID, 1) - 1
if id >= maxNumGauges {
panic("Too many float gauges")
}
floatgnames[id] = name
tgs = copyTags(tgs)
tgs[TagMetricType] = MetricTypeGauge
tgs[TagDataType] = DataTypeFloat64
floatgtags[id] = tgs
return id
} | go | func AddFloatGauge(name string, tgs Tags) uint32 {
id := atomic.AddUint32(curFloatGaugeID, 1) - 1
if id >= maxNumGauges {
panic("Too many float gauges")
}
floatgnames[id] = name
tgs = copyTags(tgs)
tgs[TagMetricType] = MetricTypeGauge
tgs[TagDataType] = DataTypeFloat64
floatgtags[id] = tgs
return id
} | [
"func",
"AddFloatGauge",
"(",
"name",
"string",
",",
"tgs",
"Tags",
")",
"uint32",
"{",
"id",
":=",
"atomic",
".",
"AddUint32",
"(",
"curFloatGaugeID",
",",
"1",
")",
"-",
"1",
"\n\n",
"if",
"id",
">=",
"maxNumGauges",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"floatgnames",
"[",
"id",
"]",
"=",
"name",
"\n\n",
"tgs",
"=",
"copyTags",
"(",
"tgs",
")",
"\n",
"tgs",
"[",
"TagMetricType",
"]",
"=",
"MetricTypeGauge",
"\n",
"tgs",
"[",
"TagDataType",
"]",
"=",
"DataTypeFloat64",
"\n",
"floatgtags",
"[",
"id",
"]",
"=",
"tgs",
"\n\n",
"return",
"id",
"\n",
"}"
] | // AddFloatGauge registers a float-based gauge and returns an ID that can be
// used to access it.
// There is a maximum of 1024 gauges, after which adding a new one will panic | [
"AddFloatGauge",
"registers",
"a",
"float",
"-",
"based",
"gauge",
"and",
"returns",
"an",
"ID",
"that",
"can",
"be",
"used",
"to",
"access",
"it",
".",
"There",
"is",
"a",
"maximum",
"of",
"1024",
"gauges",
"after",
"which",
"adding",
"a",
"new",
"one",
"will",
"panic"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/metrics/gauges.go#L59-L74 | train |
Netflix/rend | metrics/gauges.go | SetIntGauge | func SetIntGauge(id uint32, value uint64) {
atomic.StoreUint64(&intgauges[id], value)
} | go | func SetIntGauge(id uint32, value uint64) {
atomic.StoreUint64(&intgauges[id], value)
} | [
"func",
"SetIntGauge",
"(",
"id",
"uint32",
",",
"value",
"uint64",
")",
"{",
"atomic",
".",
"StoreUint64",
"(",
"&",
"intgauges",
"[",
"id",
"]",
",",
"value",
")",
"\n",
"}"
] | // SetIntGauge sets a gauge by the ID returned from AddIntGauge to the value given. | [
"SetIntGauge",
"sets",
"a",
"gauge",
"by",
"the",
"ID",
"returned",
"from",
"AddIntGauge",
"to",
"the",
"value",
"given",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/metrics/gauges.go#L77-L79 | train |
Netflix/rend | metrics/gauges.go | SetFloatGauge | func SetFloatGauge(id uint32, value float64) {
// The float64 value needs to be converted into an int64 here because
// there is no atomic store for float values. This is a literal
// reinterpretation of the same exact bits.
v2 := math.Float64bits(value)
atomic.StoreUint64(&floatgauges[id], v2)
} | go | func SetFloatGauge(id uint32, value float64) {
// The float64 value needs to be converted into an int64 here because
// there is no atomic store for float values. This is a literal
// reinterpretation of the same exact bits.
v2 := math.Float64bits(value)
atomic.StoreUint64(&floatgauges[id], v2)
} | [
"func",
"SetFloatGauge",
"(",
"id",
"uint32",
",",
"value",
"float64",
")",
"{",
"// The float64 value needs to be converted into an int64 here because",
"// there is no atomic store for float values. This is a literal",
"// reinterpretation of the same exact bits.",
"v2",
":=",
"math",
".",
"Float64bits",
"(",
"value",
")",
"\n",
"atomic",
".",
"StoreUint64",
"(",
"&",
"floatgauges",
"[",
"id",
"]",
",",
"v2",
")",
"\n",
"}"
] | // SetFloatGauge sets a gauge by the ID returned from AddFloatGauge to the value given. | [
"SetFloatGauge",
"sets",
"a",
"gauge",
"by",
"the",
"ID",
"returned",
"from",
"AddFloatGauge",
"to",
"the",
"value",
"given",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/metrics/gauges.go#L82-L88 | train |
Netflix/rend | client/cmd/setget/main.go | fillKeys | func fillKeys(chans []chan []byte) {
totalCap := 0
for _, c := range chans {
totalCap += cap(c)
}
if totalCap < f.NumOps {
panic("Channels cannot hold all the ops. Deadlock guaranteed.")
}
ci := 0
key := bytes.Repeat([]byte{byte('A')}, f.KeyLength)
for i := 0; i < f.NumOps; i++ {
key = nextKey(key)
chans[ci] <- key
ci = (ci + 1) % len(chans)
}
// close them as they have all the data they need
for _, c := range chans {
close(c)
}
} | go | func fillKeys(chans []chan []byte) {
totalCap := 0
for _, c := range chans {
totalCap += cap(c)
}
if totalCap < f.NumOps {
panic("Channels cannot hold all the ops. Deadlock guaranteed.")
}
ci := 0
key := bytes.Repeat([]byte{byte('A')}, f.KeyLength)
for i := 0; i < f.NumOps; i++ {
key = nextKey(key)
chans[ci] <- key
ci = (ci + 1) % len(chans)
}
// close them as they have all the data they need
for _, c := range chans {
close(c)
}
} | [
"func",
"fillKeys",
"(",
"chans",
"[",
"]",
"chan",
"[",
"]",
"byte",
")",
"{",
"totalCap",
":=",
"0",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"chans",
"{",
"totalCap",
"+=",
"cap",
"(",
"c",
")",
"\n",
"}",
"\n",
"if",
"totalCap",
"<",
"f",
".",
"NumOps",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"ci",
":=",
"0",
"\n",
"key",
":=",
"bytes",
".",
"Repeat",
"(",
"[",
"]",
"byte",
"{",
"byte",
"(",
"'A'",
")",
"}",
",",
"f",
".",
"KeyLength",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"f",
".",
"NumOps",
";",
"i",
"++",
"{",
"key",
"=",
"nextKey",
"(",
"key",
")",
"\n",
"chans",
"[",
"ci",
"]",
"<-",
"key",
"\n",
"ci",
"=",
"(",
"ci",
"+",
"1",
")",
"%",
"len",
"(",
"chans",
")",
"\n",
"}",
"\n\n",
"// close them as they have all the data they need",
"for",
"_",
",",
"c",
":=",
"range",
"chans",
"{",
"close",
"(",
"c",
")",
"\n",
"}",
"\n",
"}"
] | // fills a bunch of channels round robin with keys | [
"fills",
"a",
"bunch",
"of",
"channels",
"round",
"robin",
"with",
"keys"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/client/cmd/setget/main.go#L80-L101 | train |
Netflix/rend | handlers/memcached/std/handler.go | NewHandler | func NewHandler(conn io.ReadWriteCloser) Handler {
rw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))
return Handler{
rw: rw,
conn: conn,
}
} | go | func NewHandler(conn io.ReadWriteCloser) Handler {
rw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))
return Handler{
rw: rw,
conn: conn,
}
} | [
"func",
"NewHandler",
"(",
"conn",
"io",
".",
"ReadWriteCloser",
")",
"Handler",
"{",
"rw",
":=",
"bufio",
".",
"NewReadWriter",
"(",
"bufio",
".",
"NewReader",
"(",
"conn",
")",
",",
"bufio",
".",
"NewWriter",
"(",
"conn",
")",
")",
"\n",
"return",
"Handler",
"{",
"rw",
":",
"rw",
",",
"conn",
":",
"conn",
",",
"}",
"\n",
"}"
] | // NewHandler returns an implementation of handlers.Handler that implements a straightforward
// request-response like normal memcached usage. | [
"NewHandler",
"returns",
"an",
"implementation",
"of",
"handlers",
".",
"Handler",
"that",
"implements",
"a",
"straightforward",
"request",
"-",
"response",
"like",
"normal",
"memcached",
"usage",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/std/handler.go#L49-L55 | train |
Netflix/rend | metrics/callbackgauges.go | RegisterIntGaugeCallback | func RegisterIntGaugeCallback(name string, tgs Tags, cb IntGaugeCallback) {
id := atomic.AddUint32(curIntCbID, 1) - 1
if id >= maxNumCallbacks {
panic("Too many callbacks")
}
intcallbacks[id] = cb
intcbnames[id] = name
tgs = copyTags(tgs)
tgs[TagMetricType] = MetricTypeGauge
intcbtags[id] = tgs
} | go | func RegisterIntGaugeCallback(name string, tgs Tags, cb IntGaugeCallback) {
id := atomic.AddUint32(curIntCbID, 1) - 1
if id >= maxNumCallbacks {
panic("Too many callbacks")
}
intcallbacks[id] = cb
intcbnames[id] = name
tgs = copyTags(tgs)
tgs[TagMetricType] = MetricTypeGauge
intcbtags[id] = tgs
} | [
"func",
"RegisterIntGaugeCallback",
"(",
"name",
"string",
",",
"tgs",
"Tags",
",",
"cb",
"IntGaugeCallback",
")",
"{",
"id",
":=",
"atomic",
".",
"AddUint32",
"(",
"curIntCbID",
",",
"1",
")",
"-",
"1",
"\n\n",
"if",
"id",
">=",
"maxNumCallbacks",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"intcallbacks",
"[",
"id",
"]",
"=",
"cb",
"\n",
"intcbnames",
"[",
"id",
"]",
"=",
"name",
"\n\n",
"tgs",
"=",
"copyTags",
"(",
"tgs",
")",
"\n",
"tgs",
"[",
"TagMetricType",
"]",
"=",
"MetricTypeGauge",
"\n",
"intcbtags",
"[",
"id",
"]",
"=",
"tgs",
"\n",
"}"
] | // RegisterIntGaugeCallback registers a gauge callback which will be called every
// time metrics are requested.
// There is a maximum of 10240 int callbacks, after which adding a new one will panic. | [
"RegisterIntGaugeCallback",
"registers",
"a",
"gauge",
"callback",
"which",
"will",
"be",
"called",
"every",
"time",
"metrics",
"are",
"requested",
".",
"There",
"is",
"a",
"maximum",
"of",
"10240",
"int",
"callbacks",
"after",
"which",
"adding",
"a",
"new",
"one",
"will",
"panic",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/metrics/callbackgauges.go#L44-L57 | train |
Netflix/rend | metrics/callbackgauges.go | RegisterFloatGaugeCallback | func RegisterFloatGaugeCallback(name string, tgs Tags, cb FloatGaugeCallback) {
id := atomic.AddUint32(curFloatCbID, 1) - 1
if id >= maxNumCallbacks {
panic("Too many callbacks")
}
floatcallbacks[id] = cb
floatcbnames[id] = name
tgs = copyTags(tgs)
tgs[TagMetricType] = MetricTypeGauge
floatcbtags[id] = tgs
} | go | func RegisterFloatGaugeCallback(name string, tgs Tags, cb FloatGaugeCallback) {
id := atomic.AddUint32(curFloatCbID, 1) - 1
if id >= maxNumCallbacks {
panic("Too many callbacks")
}
floatcallbacks[id] = cb
floatcbnames[id] = name
tgs = copyTags(tgs)
tgs[TagMetricType] = MetricTypeGauge
floatcbtags[id] = tgs
} | [
"func",
"RegisterFloatGaugeCallback",
"(",
"name",
"string",
",",
"tgs",
"Tags",
",",
"cb",
"FloatGaugeCallback",
")",
"{",
"id",
":=",
"atomic",
".",
"AddUint32",
"(",
"curFloatCbID",
",",
"1",
")",
"-",
"1",
"\n\n",
"if",
"id",
">=",
"maxNumCallbacks",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"floatcallbacks",
"[",
"id",
"]",
"=",
"cb",
"\n",
"floatcbnames",
"[",
"id",
"]",
"=",
"name",
"\n\n",
"tgs",
"=",
"copyTags",
"(",
"tgs",
")",
"\n",
"tgs",
"[",
"TagMetricType",
"]",
"=",
"MetricTypeGauge",
"\n",
"floatcbtags",
"[",
"id",
"]",
"=",
"tgs",
"\n",
"}"
] | // RegisterFloatGaugeCallback registers a gauge callback which will be called every
// time metrics are requested.
// There is a maximum of 10240 float callbacks, after which adding a new one will panic. | [
"RegisterFloatGaugeCallback",
"registers",
"a",
"gauge",
"callback",
"which",
"will",
"be",
"called",
"every",
"time",
"metrics",
"are",
"requested",
".",
"There",
"is",
"a",
"maximum",
"of",
"10240",
"float",
"callbacks",
"after",
"which",
"adding",
"a",
"new",
"one",
"will",
"panic",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/metrics/callbackgauges.go#L62-L75 | train |
Netflix/rend | client/stats/stats.go | Get | func Get(data []int) Stats {
if len(data) == 0 {
return Stats{}
}
min, max := minmax(data)
return Stats{
Avg: avg(data) / msFactor,
Min: min / msFactor,
Max: max / msFactor,
P50: p(data, 0.5) / msFactor,
P75: p(data, 0.75) / msFactor,
P90: p(data, 0.9) / msFactor,
P95: p(data, 0.95) / msFactor,
P99: p(data, 0.99) / msFactor,
}
} | go | func Get(data []int) Stats {
if len(data) == 0 {
return Stats{}
}
min, max := minmax(data)
return Stats{
Avg: avg(data) / msFactor,
Min: min / msFactor,
Max: max / msFactor,
P50: p(data, 0.5) / msFactor,
P75: p(data, 0.75) / msFactor,
P90: p(data, 0.9) / msFactor,
P95: p(data, 0.95) / msFactor,
P99: p(data, 0.99) / msFactor,
}
} | [
"func",
"Get",
"(",
"data",
"[",
"]",
"int",
")",
"Stats",
"{",
"if",
"len",
"(",
"data",
")",
"==",
"0",
"{",
"return",
"Stats",
"{",
"}",
"\n",
"}",
"\n",
"min",
",",
"max",
":=",
"minmax",
"(",
"data",
")",
"\n\n",
"return",
"Stats",
"{",
"Avg",
":",
"avg",
"(",
"data",
")",
"/",
"msFactor",
",",
"Min",
":",
"min",
"/",
"msFactor",
",",
"Max",
":",
"max",
"/",
"msFactor",
",",
"P50",
":",
"p",
"(",
"data",
",",
"0.5",
")",
"/",
"msFactor",
",",
"P75",
":",
"p",
"(",
"data",
",",
"0.75",
")",
"/",
"msFactor",
",",
"P90",
":",
"p",
"(",
"data",
",",
"0.9",
")",
"/",
"msFactor",
",",
"P95",
":",
"p",
"(",
"data",
",",
"0.95",
")",
"/",
"msFactor",
",",
"P99",
":",
"p",
"(",
"data",
",",
"0.99",
")",
"/",
"msFactor",
",",
"}",
"\n",
"}"
] | // Accepts a sorted slice of durations in nanoseconds
// Returns a Stats struct of millisecond statistics | [
"Accepts",
"a",
"sorted",
"slice",
"of",
"durations",
"in",
"nanoseconds",
"Returns",
"a",
"Stats",
"struct",
"of",
"millisecond",
"statistics"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/client/stats/stats.go#L35-L51 | train |
Netflix/rend | handlers/memcached/chunked/chunkedLimitedReader.go | Read | func (c chunkedLimitedReader) Read(p []byte) (n int, err error) {
// If we've already read all our chunks and the remainders are <= 0, we're done
if c.d.doneChunks >= c.d.numChunks || (c.d.remaining <= 0 && c.d.chunkRem <= 0) {
return 0, io.EOF
}
// Data is done, returning only buffer bytes now
if c.d.remaining <= 0 {
if int64(len(p)) > c.d.chunkRem {
p = p[0:c.d.chunkRem]
}
for i := range p {
p[i] = 0
}
c.d.chunkRem -= int64(len(p))
return len(p), nil
}
// Data is not yet done, but chunk is
if c.d.chunkRem <= 0 {
return 0, io.EOF
}
// Data and chunk not yet done, need to read from outside reader
if int64(len(p)) > c.d.remaining || int64(len(p)) > c.d.chunkRem {
rem := int64(math.Min(float64(c.d.remaining), float64(c.d.chunkRem)))
p = p[0:rem]
}
n, err = c.d.reader.Read(p)
c.d.remaining -= int64(n)
c.d.chunkRem -= int64(n)
return
} | go | func (c chunkedLimitedReader) Read(p []byte) (n int, err error) {
// If we've already read all our chunks and the remainders are <= 0, we're done
if c.d.doneChunks >= c.d.numChunks || (c.d.remaining <= 0 && c.d.chunkRem <= 0) {
return 0, io.EOF
}
// Data is done, returning only buffer bytes now
if c.d.remaining <= 0 {
if int64(len(p)) > c.d.chunkRem {
p = p[0:c.d.chunkRem]
}
for i := range p {
p[i] = 0
}
c.d.chunkRem -= int64(len(p))
return len(p), nil
}
// Data is not yet done, but chunk is
if c.d.chunkRem <= 0 {
return 0, io.EOF
}
// Data and chunk not yet done, need to read from outside reader
if int64(len(p)) > c.d.remaining || int64(len(p)) > c.d.chunkRem {
rem := int64(math.Min(float64(c.d.remaining), float64(c.d.chunkRem)))
p = p[0:rem]
}
n, err = c.d.reader.Read(p)
c.d.remaining -= int64(n)
c.d.chunkRem -= int64(n)
return
} | [
"func",
"(",
"c",
"chunkedLimitedReader",
")",
"Read",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"// If we've already read all our chunks and the remainders are <= 0, we're done",
"if",
"c",
".",
"d",
".",
"doneChunks",
">=",
"c",
".",
"d",
".",
"numChunks",
"||",
"(",
"c",
".",
"d",
".",
"remaining",
"<=",
"0",
"&&",
"c",
".",
"d",
".",
"chunkRem",
"<=",
"0",
")",
"{",
"return",
"0",
",",
"io",
".",
"EOF",
"\n",
"}",
"\n\n",
"// Data is done, returning only buffer bytes now",
"if",
"c",
".",
"d",
".",
"remaining",
"<=",
"0",
"{",
"if",
"int64",
"(",
"len",
"(",
"p",
")",
")",
">",
"c",
".",
"d",
".",
"chunkRem",
"{",
"p",
"=",
"p",
"[",
"0",
":",
"c",
".",
"d",
".",
"chunkRem",
"]",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"range",
"p",
"{",
"p",
"[",
"i",
"]",
"=",
"0",
"\n",
"}",
"\n\n",
"c",
".",
"d",
".",
"chunkRem",
"-=",
"int64",
"(",
"len",
"(",
"p",
")",
")",
"\n",
"return",
"len",
"(",
"p",
")",
",",
"nil",
"\n",
"}",
"\n\n",
"// Data is not yet done, but chunk is",
"if",
"c",
".",
"d",
".",
"chunkRem",
"<=",
"0",
"{",
"return",
"0",
",",
"io",
".",
"EOF",
"\n",
"}",
"\n\n",
"// Data and chunk not yet done, need to read from outside reader",
"if",
"int64",
"(",
"len",
"(",
"p",
")",
")",
">",
"c",
".",
"d",
".",
"remaining",
"||",
"int64",
"(",
"len",
"(",
"p",
")",
")",
">",
"c",
".",
"d",
".",
"chunkRem",
"{",
"rem",
":=",
"int64",
"(",
"math",
".",
"Min",
"(",
"float64",
"(",
"c",
".",
"d",
".",
"remaining",
")",
",",
"float64",
"(",
"c",
".",
"d",
".",
"chunkRem",
")",
")",
")",
"\n",
"p",
"=",
"p",
"[",
"0",
":",
"rem",
"]",
"\n",
"}",
"\n\n",
"n",
",",
"err",
"=",
"c",
".",
"d",
".",
"reader",
".",
"Read",
"(",
"p",
")",
"\n",
"c",
".",
"d",
".",
"remaining",
"-=",
"int64",
"(",
"n",
")",
"\n",
"c",
".",
"d",
".",
"chunkRem",
"-=",
"int64",
"(",
"n",
")",
"\n\n",
"return",
"\n",
"}"
] | // io.Reader's interface implements this as a value method, not a pointer method. | [
"io",
".",
"Reader",
"s",
"interface",
"implements",
"this",
"as",
"a",
"value",
"method",
"not",
"a",
"pointer",
"method",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/chunked/chunkedLimitedReader.go#L53-L89 | train |
Netflix/rend | handlers/memcached/chunked/handler.go | Add | func (h Handler) Add(cmd common.SetRequest) error {
return h.handleSetCommon(cmd, common.RequestAdd)
} | go | func (h Handler) Add(cmd common.SetRequest) error {
return h.handleSetCommon(cmd, common.RequestAdd)
} | [
"func",
"(",
"h",
"Handler",
")",
"Add",
"(",
"cmd",
"common",
".",
"SetRequest",
")",
"error",
"{",
"return",
"h",
".",
"handleSetCommon",
"(",
"cmd",
",",
"common",
".",
"RequestAdd",
")",
"\n",
"}"
] | // Add performs an add request on the remote backend | [
"Add",
"performs",
"an",
"add",
"request",
"on",
"the",
"remote",
"backend"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/chunked/handler.go#L148-L150 | train |
Netflix/rend | handlers/memcached/chunked/handler.go | Replace | func (h Handler) Replace(cmd common.SetRequest) error {
return h.handleSetCommon(cmd, common.RequestReplace)
} | go | func (h Handler) Replace(cmd common.SetRequest) error {
return h.handleSetCommon(cmd, common.RequestReplace)
} | [
"func",
"(",
"h",
"Handler",
")",
"Replace",
"(",
"cmd",
"common",
".",
"SetRequest",
")",
"error",
"{",
"return",
"h",
".",
"handleSetCommon",
"(",
"cmd",
",",
"common",
".",
"RequestReplace",
")",
"\n",
"}"
] | // Replace performs a replace request on the remote backend | [
"Replace",
"performs",
"a",
"replace",
"request",
"on",
"the",
"remote",
"backend"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/chunked/handler.go#L153-L155 | train |
Netflix/rend | handlers/memcached/chunked/handler.go | exptime | func exptime(ttl uint32) (exp uint32, expired bool) {
// zero is the special forever case
if ttl == 0 {
return 0, false
}
now := uint32(time.Now().Unix())
// The memcached protocol has a... "quirk" where any expiration time over 30
// days is considered to be a unix timestamp.
if ttl > realTimeMaxDelta {
return ttl, (ttl < now)
}
// otherwise, this is a normal differential TTL
return now + ttl, false
} | go | func exptime(ttl uint32) (exp uint32, expired bool) {
// zero is the special forever case
if ttl == 0 {
return 0, false
}
now := uint32(time.Now().Unix())
// The memcached protocol has a... "quirk" where any expiration time over 30
// days is considered to be a unix timestamp.
if ttl > realTimeMaxDelta {
return ttl, (ttl < now)
}
// otherwise, this is a normal differential TTL
return now + ttl, false
} | [
"func",
"exptime",
"(",
"ttl",
"uint32",
")",
"(",
"exp",
"uint32",
",",
"expired",
"bool",
")",
"{",
"// zero is the special forever case",
"if",
"ttl",
"==",
"0",
"{",
"return",
"0",
",",
"false",
"\n",
"}",
"\n\n",
"now",
":=",
"uint32",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
")",
"\n\n",
"// The memcached protocol has a... \"quirk\" where any expiration time over 30",
"// days is considered to be a unix timestamp.",
"if",
"ttl",
">",
"realTimeMaxDelta",
"{",
"return",
"ttl",
",",
"(",
"ttl",
"<",
"now",
")",
"\n",
"}",
"\n\n",
"// otherwise, this is a normal differential TTL",
"return",
"now",
"+",
"ttl",
",",
"false",
"\n",
"}"
] | // Takes a TTL in seconds and returns the unix time in seconds when the item will expire. | [
"Takes",
"a",
"TTL",
"in",
"seconds",
"and",
"returns",
"the",
"unix",
"time",
"in",
"seconds",
"when",
"the",
"item",
"will",
"expire",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/chunked/handler.go#L191-L207 | train |
Netflix/rend | handlers/memcached/chunked/handler.go | Append | func (h Handler) Append(cmd common.SetRequest) error {
return h.handleAppendPrependCommon(cmd, common.RequestAppend)
} | go | func (h Handler) Append(cmd common.SetRequest) error {
return h.handleAppendPrependCommon(cmd, common.RequestAppend)
} | [
"func",
"(",
"h",
"Handler",
")",
"Append",
"(",
"cmd",
"common",
".",
"SetRequest",
")",
"error",
"{",
"return",
"h",
".",
"handleAppendPrependCommon",
"(",
"cmd",
",",
"common",
".",
"RequestAppend",
")",
"\n",
"}"
] | // Append performs an append request on the remote backend | [
"Append",
"performs",
"an",
"append",
"request",
"on",
"the",
"remote",
"backend"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/chunked/handler.go#L338-L340 | train |
Netflix/rend | handlers/memcached/chunked/handler.go | Prepend | func (h Handler) Prepend(cmd common.SetRequest) error {
return h.handleAppendPrependCommon(cmd, common.RequestPrepend)
} | go | func (h Handler) Prepend(cmd common.SetRequest) error {
return h.handleAppendPrependCommon(cmd, common.RequestPrepend)
} | [
"func",
"(",
"h",
"Handler",
")",
"Prepend",
"(",
"cmd",
"common",
".",
"SetRequest",
")",
"error",
"{",
"return",
"h",
".",
"handleAppendPrependCommon",
"(",
"cmd",
",",
"common",
".",
"RequestPrepend",
")",
"\n",
"}"
] | // Prepend performs a prepend request on the remote backend | [
"Prepend",
"performs",
"a",
"prepend",
"request",
"on",
"the",
"remote",
"backend"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/chunked/handler.go#L343-L345 | train |
Netflix/rend | handlers/memcached/chunked/handler.go | Get | func (h Handler) Get(cmd common.GetRequest) (<-chan common.GetResponse, <-chan error) {
// No buffering here so there's not multiple gets in memory
dataOut := make(chan common.GetResponse)
errorOut := make(chan error)
go realHandleGet(cmd, dataOut, errorOut, h.rw)
return dataOut, errorOut
} | go | func (h Handler) Get(cmd common.GetRequest) (<-chan common.GetResponse, <-chan error) {
// No buffering here so there's not multiple gets in memory
dataOut := make(chan common.GetResponse)
errorOut := make(chan error)
go realHandleGet(cmd, dataOut, errorOut, h.rw)
return dataOut, errorOut
} | [
"func",
"(",
"h",
"Handler",
")",
"Get",
"(",
"cmd",
"common",
".",
"GetRequest",
")",
"(",
"<-",
"chan",
"common",
".",
"GetResponse",
",",
"<-",
"chan",
"error",
")",
"{",
"// No buffering here so there's not multiple gets in memory",
"dataOut",
":=",
"make",
"(",
"chan",
"common",
".",
"GetResponse",
")",
"\n",
"errorOut",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"go",
"realHandleGet",
"(",
"cmd",
",",
"dataOut",
",",
"errorOut",
",",
"h",
".",
"rw",
")",
"\n",
"return",
"dataOut",
",",
"errorOut",
"\n",
"}"
] | // Get performs a batched get request on the remote backend. The channels returned
// are expected to be read from until either a single error is received or the
// response channel is exhausted. | [
"Get",
"performs",
"a",
"batched",
"get",
"request",
"on",
"the",
"remote",
"backend",
".",
"The",
"channels",
"returned",
"are",
"expected",
"to",
"be",
"read",
"from",
"until",
"either",
"a",
"single",
"error",
"is",
"received",
"or",
"the",
"response",
"channel",
"is",
"exhausted",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/chunked/handler.go#L468-L474 | train |
Netflix/rend | handlers/memcached/chunked/handler.go | GetE | func (h Handler) GetE(cmd common.GetRequest) (<-chan common.GetEResponse, <-chan error) {
// Being minimalist, not lazy. The chunked handler is not meant to be used with a
// backing store that supports the GetE protocol extension. It would be a waste of
// time and effort to support it here if it would "never" be used. It will be added
// as soon as a case for it exists.
//
// The GetE extension is an addition that only rend supports. This chunked handler
// is pretty explicitly for talking to memcached since it is a complex workaround
// for pathological behavior when data size rapidly changes that only happens in
// memcached. The chunked handler will not work well with the L2 the EVCache team
// uses.
panic("GetE not supported in Rend chunked mode")
} | go | func (h Handler) GetE(cmd common.GetRequest) (<-chan common.GetEResponse, <-chan error) {
// Being minimalist, not lazy. The chunked handler is not meant to be used with a
// backing store that supports the GetE protocol extension. It would be a waste of
// time and effort to support it here if it would "never" be used. It will be added
// as soon as a case for it exists.
//
// The GetE extension is an addition that only rend supports. This chunked handler
// is pretty explicitly for talking to memcached since it is a complex workaround
// for pathological behavior when data size rapidly changes that only happens in
// memcached. The chunked handler will not work well with the L2 the EVCache team
// uses.
panic("GetE not supported in Rend chunked mode")
} | [
"func",
"(",
"h",
"Handler",
")",
"GetE",
"(",
"cmd",
"common",
".",
"GetRequest",
")",
"(",
"<-",
"chan",
"common",
".",
"GetEResponse",
",",
"<-",
"chan",
"error",
")",
"{",
"// Being minimalist, not lazy. The chunked handler is not meant to be used with a",
"// backing store that supports the GetE protocol extension. It would be a waste of",
"// time and effort to support it here if it would \"never\" be used. It will be added",
"// as soon as a case for it exists.",
"//",
"// The GetE extension is an addition that only rend supports. This chunked handler",
"// is pretty explicitly for talking to memcached since it is a complex workaround",
"// for pathological behavior when data size rapidly changes that only happens in",
"// memcached. The chunked handler will not work well with the L2 the EVCache team",
"// uses.",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // GetE performs a batched gete request on the remote backend. The channels returned
// are expected to be read from until either a single error is received or the
// response channel is exhausted. | [
"GetE",
"performs",
"a",
"batched",
"gete",
"request",
"on",
"the",
"remote",
"backend",
".",
"The",
"channels",
"returned",
"are",
"expected",
"to",
"be",
"read",
"from",
"until",
"either",
"a",
"single",
"error",
"is",
"received",
"or",
"the",
"response",
"channel",
"is",
"exhausted",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/chunked/handler.go#L606-L618 | train |
Netflix/rend | metrics/counters.go | IncCounterBy | func IncCounterBy(id uint32, amount uint64) {
atomic.AddUint64(&counters[id], amount)
} | go | func IncCounterBy(id uint32, amount uint64) {
atomic.AddUint64(&counters[id], amount)
} | [
"func",
"IncCounterBy",
"(",
"id",
"uint32",
",",
"amount",
"uint64",
")",
"{",
"atomic",
".",
"AddUint64",
"(",
"&",
"counters",
"[",
"id",
"]",
",",
"amount",
")",
"\n",
"}"
] | // IncCounterBy increments the specified counter by the given amount. This is for situations
// where the count is not a one by one thing, like counting bytes in and out of a system. | [
"IncCounterBy",
"increments",
"the",
"specified",
"counter",
"by",
"the",
"given",
"amount",
".",
"This",
"is",
"for",
"situations",
"where",
"the",
"count",
"is",
"not",
"a",
"one",
"by",
"one",
"thing",
"like",
"counting",
"bytes",
"in",
"and",
"out",
"of",
"a",
"system",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/metrics/counters.go#L66-L68 | train |
Netflix/rend | orcas/locked.go | getlock | func (l *LockedOrca) getlock(key []byte, read bool) sync.Locker {
h := l.hpool.Get().(hash.Hash32)
defer l.hpool.Put(h)
h.Reset()
// Calculate bucket using hash and mod. hash.Hash.Write() never returns an error.
h.Write(key)
bucket := int(h.Sum32())
bucket &= len(l.locks) - 1
//atomic.AddUint32(&l.counts[bucket], 1)
//if (atomic.AddUint64(&numops, 1) % 10000) == 0 {
// for idx, count := range l.counts {
// fmt.Printf("%d: %d\n", idx, count)
// }
//}
if read {
return l.rlocks[bucket]
}
return l.locks[bucket]
} | go | func (l *LockedOrca) getlock(key []byte, read bool) sync.Locker {
h := l.hpool.Get().(hash.Hash32)
defer l.hpool.Put(h)
h.Reset()
// Calculate bucket using hash and mod. hash.Hash.Write() never returns an error.
h.Write(key)
bucket := int(h.Sum32())
bucket &= len(l.locks) - 1
//atomic.AddUint32(&l.counts[bucket], 1)
//if (atomic.AddUint64(&numops, 1) % 10000) == 0 {
// for idx, count := range l.counts {
// fmt.Printf("%d: %d\n", idx, count)
// }
//}
if read {
return l.rlocks[bucket]
}
return l.locks[bucket]
} | [
"func",
"(",
"l",
"*",
"LockedOrca",
")",
"getlock",
"(",
"key",
"[",
"]",
"byte",
",",
"read",
"bool",
")",
"sync",
".",
"Locker",
"{",
"h",
":=",
"l",
".",
"hpool",
".",
"Get",
"(",
")",
".",
"(",
"hash",
".",
"Hash32",
")",
"\n",
"defer",
"l",
".",
"hpool",
".",
"Put",
"(",
"h",
")",
"\n",
"h",
".",
"Reset",
"(",
")",
"\n\n",
"// Calculate bucket using hash and mod. hash.Hash.Write() never returns an error.",
"h",
".",
"Write",
"(",
"key",
")",
"\n",
"bucket",
":=",
"int",
"(",
"h",
".",
"Sum32",
"(",
")",
")",
"\n",
"bucket",
"&=",
"len",
"(",
"l",
".",
"locks",
")",
"-",
"1",
"\n\n",
"//atomic.AddUint32(&l.counts[bucket], 1)",
"//if (atomic.AddUint64(&numops, 1) % 10000) == 0 {",
"//\tfor idx, count := range l.counts {",
"//\t\tfmt.Printf(\"%d: %d\\n\", idx, count)",
"//\t}",
"//}",
"if",
"read",
"{",
"return",
"l",
".",
"rlocks",
"[",
"bucket",
"]",
"\n",
"}",
"\n\n",
"return",
"l",
".",
"locks",
"[",
"bucket",
"]",
"\n",
"}"
] | //var numops uint64 = 0 | [
"var",
"numops",
"uint64",
"=",
"0"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/orcas/locked.go#L126-L149 | train |
Netflix/rend | handlers/memcached/batched/relay.go | getRelay | func getRelay(sock string, opts Opts) *relay {
relayLock.RLock()
if r, ok := relays[sock]; ok {
relayLock.RUnlock()
return r
}
relayLock.RUnlock()
// Lock here because we are creating a new relay for the given socket path
// The rest of the new connections will block here and then pick it up on
// the double check
relayLock.Lock()
// double check
if r, ok := relays[sock]; ok {
relayLock.Unlock()
return r
}
metrics.IncCounter(MetricBatchRelaysCreated)
// Create a new relay and wait for the first connection to be established
// so it's usable.
r := &relay{
sock: sock,
conns: atomic.Value{},
addConnLock: new(sync.Mutex),
//expand: make(chan struct{}, 1),
opts: opts,
}
// initialize the atomic value
r.conns.Store(make([]*conn, 0))
firstConnSetup := make(chan struct{})
go r.monitor(firstConnSetup)
<-firstConnSetup
relays[sock] = r
relayLock.Unlock()
return r
} | go | func getRelay(sock string, opts Opts) *relay {
relayLock.RLock()
if r, ok := relays[sock]; ok {
relayLock.RUnlock()
return r
}
relayLock.RUnlock()
// Lock here because we are creating a new relay for the given socket path
// The rest of the new connections will block here and then pick it up on
// the double check
relayLock.Lock()
// double check
if r, ok := relays[sock]; ok {
relayLock.Unlock()
return r
}
metrics.IncCounter(MetricBatchRelaysCreated)
// Create a new relay and wait for the first connection to be established
// so it's usable.
r := &relay{
sock: sock,
conns: atomic.Value{},
addConnLock: new(sync.Mutex),
//expand: make(chan struct{}, 1),
opts: opts,
}
// initialize the atomic value
r.conns.Store(make([]*conn, 0))
firstConnSetup := make(chan struct{})
go r.monitor(firstConnSetup)
<-firstConnSetup
relays[sock] = r
relayLock.Unlock()
return r
} | [
"func",
"getRelay",
"(",
"sock",
"string",
",",
"opts",
"Opts",
")",
"*",
"relay",
"{",
"relayLock",
".",
"RLock",
"(",
")",
"\n",
"if",
"r",
",",
"ok",
":=",
"relays",
"[",
"sock",
"]",
";",
"ok",
"{",
"relayLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"r",
"\n",
"}",
"\n",
"relayLock",
".",
"RUnlock",
"(",
")",
"\n\n",
"// Lock here because we are creating a new relay for the given socket path",
"// The rest of the new connections will block here and then pick it up on",
"// the double check",
"relayLock",
".",
"Lock",
"(",
")",
"\n\n",
"// double check",
"if",
"r",
",",
"ok",
":=",
"relays",
"[",
"sock",
"]",
";",
"ok",
"{",
"relayLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"r",
"\n",
"}",
"\n\n",
"metrics",
".",
"IncCounter",
"(",
"MetricBatchRelaysCreated",
")",
"\n\n",
"// Create a new relay and wait for the first connection to be established",
"// so it's usable.",
"r",
":=",
"&",
"relay",
"{",
"sock",
":",
"sock",
",",
"conns",
":",
"atomic",
".",
"Value",
"{",
"}",
",",
"addConnLock",
":",
"new",
"(",
"sync",
".",
"Mutex",
")",
",",
"//expand: make(chan struct{}, 1),",
"opts",
":",
"opts",
",",
"}",
"\n\n",
"// initialize the atomic value",
"r",
".",
"conns",
".",
"Store",
"(",
"make",
"(",
"[",
"]",
"*",
"conn",
",",
"0",
")",
")",
"\n\n",
"firstConnSetup",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"go",
"r",
".",
"monitor",
"(",
"firstConnSetup",
")",
"\n",
"<-",
"firstConnSetup",
"\n\n",
"relays",
"[",
"sock",
"]",
"=",
"r",
"\n",
"relayLock",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"r",
"\n",
"}"
] | // Creates a new relay with one connection or returns an existing relay for the
// given socket. | [
"Creates",
"a",
"new",
"relay",
"with",
"one",
"connection",
"or",
"returns",
"an",
"existing",
"relay",
"for",
"the",
"given",
"socket",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/batched/relay.go#L53-L95 | train |
Netflix/rend | handlers/memcached/batched/relay.go | addConn | func (r *relay) addConn() {
// Ensure there's no races when adding a connection
r.addConnLock.Lock()
defer r.addConnLock.Unlock()
temp := r.conns.Load().([]*conn)
connID := uint32(len(temp))
batchDelay := time.Duration(r.opts.BatchDelayMicros) * time.Microsecond
poolconn := newConn(r.sock, connID, batchDelay, r.opts.BatchSize, r.opts.ReadBufSize, r.opts.WriteBufSize, r.expand)
// Add the new connection (but with a new slice header)
temp = append(temp, poolconn)
// Store the modified slice
r.conns.Store(temp)
} | go | func (r *relay) addConn() {
// Ensure there's no races when adding a connection
r.addConnLock.Lock()
defer r.addConnLock.Unlock()
temp := r.conns.Load().([]*conn)
connID := uint32(len(temp))
batchDelay := time.Duration(r.opts.BatchDelayMicros) * time.Microsecond
poolconn := newConn(r.sock, connID, batchDelay, r.opts.BatchSize, r.opts.ReadBufSize, r.opts.WriteBufSize, r.expand)
// Add the new connection (but with a new slice header)
temp = append(temp, poolconn)
// Store the modified slice
r.conns.Store(temp)
} | [
"func",
"(",
"r",
"*",
"relay",
")",
"addConn",
"(",
")",
"{",
"// Ensure there's no races when adding a connection",
"r",
".",
"addConnLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"addConnLock",
".",
"Unlock",
"(",
")",
"\n\n",
"temp",
":=",
"r",
".",
"conns",
".",
"Load",
"(",
")",
".",
"(",
"[",
"]",
"*",
"conn",
")",
"\n\n",
"connID",
":=",
"uint32",
"(",
"len",
"(",
"temp",
")",
")",
"\n",
"batchDelay",
":=",
"time",
".",
"Duration",
"(",
"r",
".",
"opts",
".",
"BatchDelayMicros",
")",
"*",
"time",
".",
"Microsecond",
"\n",
"poolconn",
":=",
"newConn",
"(",
"r",
".",
"sock",
",",
"connID",
",",
"batchDelay",
",",
"r",
".",
"opts",
".",
"BatchSize",
",",
"r",
".",
"opts",
".",
"ReadBufSize",
",",
"r",
".",
"opts",
".",
"WriteBufSize",
",",
"r",
".",
"expand",
")",
"\n\n",
"// Add the new connection (but with a new slice header)",
"temp",
"=",
"append",
"(",
"temp",
",",
"poolconn",
")",
"\n\n",
"// Store the modified slice",
"r",
".",
"conns",
".",
"Store",
"(",
"temp",
")",
"\n",
"}"
] | // Adds a connection to the pool. This is one way only, making this effectively
// a high-water-mark pool with no connections being torn down. | [
"Adds",
"a",
"connection",
"to",
"the",
"pool",
".",
"This",
"is",
"one",
"way",
"only",
"making",
"this",
"effectively",
"a",
"high",
"-",
"water",
"-",
"mark",
"pool",
"with",
"no",
"connections",
"being",
"torn",
"down",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/batched/relay.go#L99-L115 | train |
Netflix/rend | handlers/memcached/batched/relay.go | submit | func (r *relay) submit(rand *rand.Rand, req request) {
// use rand to select a connection to submit to
// the connection should notify the frontend by the channel
// in the request struct
cs := r.conns.Load().([]*conn)
idx := rand.Intn(len(cs))
c := cs[idx]
c.reqchan <- req
} | go | func (r *relay) submit(rand *rand.Rand, req request) {
// use rand to select a connection to submit to
// the connection should notify the frontend by the channel
// in the request struct
cs := r.conns.Load().([]*conn)
idx := rand.Intn(len(cs))
c := cs[idx]
c.reqchan <- req
} | [
"func",
"(",
"r",
"*",
"relay",
")",
"submit",
"(",
"rand",
"*",
"rand",
".",
"Rand",
",",
"req",
"request",
")",
"{",
"// use rand to select a connection to submit to",
"// the connection should notify the frontend by the channel",
"// in the request struct",
"cs",
":=",
"r",
".",
"conns",
".",
"Load",
"(",
")",
".",
"(",
"[",
"]",
"*",
"conn",
")",
"\n",
"idx",
":=",
"rand",
".",
"Intn",
"(",
"len",
"(",
"cs",
")",
")",
"\n",
"c",
":=",
"cs",
"[",
"idx",
"]",
"\n",
"c",
".",
"reqchan",
"<-",
"req",
"\n",
"}"
] | // Submits a request to a random connection in the pool. The random number generator
// is passed in so there is no sharing between external connections. | [
"Submits",
"a",
"request",
"to",
"a",
"random",
"connection",
"in",
"the",
"pool",
".",
"The",
"random",
"number",
"generator",
"is",
"passed",
"in",
"so",
"there",
"is",
"no",
"sharing",
"between",
"external",
"connections",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/batched/relay.go#L119-L127 | train |
Netflix/rend | handlers/memcached/batched/handler.go | Set | func (h Handler) Set(cmd common.SetRequest) error {
_, err := h.doRequest(cmd, common.RequestSet)
return err
} | go | func (h Handler) Set(cmd common.SetRequest) error {
_, err := h.doRequest(cmd, common.RequestSet)
return err
} | [
"func",
"(",
"h",
"Handler",
")",
"Set",
"(",
"cmd",
"common",
".",
"SetRequest",
")",
"error",
"{",
"_",
",",
"err",
":=",
"h",
".",
"doRequest",
"(",
"cmd",
",",
"common",
".",
"RequestSet",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Set performs a set operation on the backend. It unconditionally sets a key to a value. | [
"Set",
"performs",
"a",
"set",
"operation",
"on",
"the",
"backend",
".",
"It",
"unconditionally",
"sets",
"a",
"key",
"to",
"a",
"value",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/batched/handler.go#L177-L180 | train |
Netflix/rend | handlers/memcached/batched/handler.go | Add | func (h Handler) Add(cmd common.SetRequest) error {
_, err := h.doRequest(cmd, common.RequestAdd)
return err
} | go | func (h Handler) Add(cmd common.SetRequest) error {
_, err := h.doRequest(cmd, common.RequestAdd)
return err
} | [
"func",
"(",
"h",
"Handler",
")",
"Add",
"(",
"cmd",
"common",
".",
"SetRequest",
")",
"error",
"{",
"_",
",",
"err",
":=",
"h",
".",
"doRequest",
"(",
"cmd",
",",
"common",
".",
"RequestAdd",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Add performs an add operation on the backend. It only sets the value if it does not already exist. | [
"Add",
"performs",
"an",
"add",
"operation",
"on",
"the",
"backend",
".",
"It",
"only",
"sets",
"the",
"value",
"if",
"it",
"does",
"not",
"already",
"exist",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/batched/handler.go#L183-L186 | train |
Netflix/rend | handlers/memcached/batched/handler.go | Replace | func (h Handler) Replace(cmd common.SetRequest) error {
_, err := h.doRequest(cmd, common.RequestReplace)
return err
} | go | func (h Handler) Replace(cmd common.SetRequest) error {
_, err := h.doRequest(cmd, common.RequestReplace)
return err
} | [
"func",
"(",
"h",
"Handler",
")",
"Replace",
"(",
"cmd",
"common",
".",
"SetRequest",
")",
"error",
"{",
"_",
",",
"err",
":=",
"h",
".",
"doRequest",
"(",
"cmd",
",",
"common",
".",
"RequestReplace",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Replace performs a replace operation on the backend. It only sets the value if it already exists. | [
"Replace",
"performs",
"a",
"replace",
"operation",
"on",
"the",
"backend",
".",
"It",
"only",
"sets",
"the",
"value",
"if",
"it",
"already",
"exists",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/batched/handler.go#L189-L192 | train |
Netflix/rend | handlers/memcached/batched/handler.go | Append | func (h Handler) Append(cmd common.SetRequest) error {
_, err := h.doRequest(cmd, common.RequestAppend)
return err
} | go | func (h Handler) Append(cmd common.SetRequest) error {
_, err := h.doRequest(cmd, common.RequestAppend)
return err
} | [
"func",
"(",
"h",
"Handler",
")",
"Append",
"(",
"cmd",
"common",
".",
"SetRequest",
")",
"error",
"{",
"_",
",",
"err",
":=",
"h",
".",
"doRequest",
"(",
"cmd",
",",
"common",
".",
"RequestAppend",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Append performs an append operation on the backend. It will append the data to the value only if it already exists. | [
"Append",
"performs",
"an",
"append",
"operation",
"on",
"the",
"backend",
".",
"It",
"will",
"append",
"the",
"data",
"to",
"the",
"value",
"only",
"if",
"it",
"already",
"exists",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/batched/handler.go#L195-L198 | train |
Netflix/rend | handlers/memcached/batched/handler.go | Prepend | func (h Handler) Prepend(cmd common.SetRequest) error {
_, err := h.doRequest(cmd, common.RequestPrepend)
return err
} | go | func (h Handler) Prepend(cmd common.SetRequest) error {
_, err := h.doRequest(cmd, common.RequestPrepend)
return err
} | [
"func",
"(",
"h",
"Handler",
")",
"Prepend",
"(",
"cmd",
"common",
".",
"SetRequest",
")",
"error",
"{",
"_",
",",
"err",
":=",
"h",
".",
"doRequest",
"(",
"cmd",
",",
"common",
".",
"RequestPrepend",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Prepend performs a prepend operation on the backend. It will prepend the data to the value only if it already exists. | [
"Prepend",
"performs",
"a",
"prepend",
"operation",
"on",
"the",
"backend",
".",
"It",
"will",
"prepend",
"the",
"data",
"to",
"the",
"value",
"only",
"if",
"it",
"already",
"exists",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/batched/handler.go#L201-L204 | train |
Netflix/rend | handlers/memcached/batched/handler.go | Delete | func (h Handler) Delete(cmd common.DeleteRequest) error {
_, err := h.doRequest(cmd, common.RequestDelete)
return err
} | go | func (h Handler) Delete(cmd common.DeleteRequest) error {
_, err := h.doRequest(cmd, common.RequestDelete)
return err
} | [
"func",
"(",
"h",
"Handler",
")",
"Delete",
"(",
"cmd",
"common",
".",
"DeleteRequest",
")",
"error",
"{",
"_",
",",
"err",
":=",
"h",
".",
"doRequest",
"(",
"cmd",
",",
"common",
".",
"RequestDelete",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Delete performs a delete operation on the backend. It will unconditionally remove the value. | [
"Delete",
"performs",
"a",
"delete",
"operation",
"on",
"the",
"backend",
".",
"It",
"will",
"unconditionally",
"remove",
"the",
"value",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/batched/handler.go#L207-L210 | train |
Netflix/rend | handlers/memcached/batched/handler.go | Touch | func (h Handler) Touch(cmd common.TouchRequest) error {
_, err := h.doRequest(cmd, common.RequestTouch)
return err
} | go | func (h Handler) Touch(cmd common.TouchRequest) error {
_, err := h.doRequest(cmd, common.RequestTouch)
return err
} | [
"func",
"(",
"h",
"Handler",
")",
"Touch",
"(",
"cmd",
"common",
".",
"TouchRequest",
")",
"error",
"{",
"_",
",",
"err",
":=",
"h",
".",
"doRequest",
"(",
"cmd",
",",
"common",
".",
"RequestTouch",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Touch performs a touch operation on the backend. It will overwrite the expiration time with a new one. | [
"Touch",
"performs",
"a",
"touch",
"operation",
"on",
"the",
"backend",
".",
"It",
"will",
"overwrite",
"the",
"expiration",
"time",
"with",
"a",
"new",
"one",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/batched/handler.go#L213-L216 | train |
Netflix/rend | handlers/memcached/batched/handler.go | GAT | func (h Handler) GAT(cmd common.GATRequest) (common.GetResponse, error) {
gr, err := h.doRequest(cmd, common.RequestGat)
return getEResponseToGetResponse(gr), err
} | go | func (h Handler) GAT(cmd common.GATRequest) (common.GetResponse, error) {
gr, err := h.doRequest(cmd, common.RequestGat)
return getEResponseToGetResponse(gr), err
} | [
"func",
"(",
"h",
"Handler",
")",
"GAT",
"(",
"cmd",
"common",
".",
"GATRequest",
")",
"(",
"common",
".",
"GetResponse",
",",
"error",
")",
"{",
"gr",
",",
"err",
":=",
"h",
".",
"doRequest",
"(",
"cmd",
",",
"common",
".",
"RequestGat",
")",
"\n",
"return",
"getEResponseToGetResponse",
"(",
"gr",
")",
",",
"err",
"\n",
"}"
] | // GAT performs a get-and-touch on the backend for the given key. It will retrieve the value while updating the TTL to
// the one supplied. | [
"GAT",
"performs",
"a",
"get",
"-",
"and",
"-",
"touch",
"on",
"the",
"backend",
"for",
"the",
"given",
"key",
".",
"It",
"will",
"retrieve",
"the",
"value",
"while",
"updating",
"the",
"TTL",
"to",
"the",
"one",
"supplied",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/batched/handler.go#L231-L234 | train |
Netflix/rend | handlers/memcached/batched/handler.go | getRequestToTrackerMap | func getRequestToTrackerMap(cmd common.GetRequest) trackermap {
tm := make(trackermap)
for i := range cmd.Keys {
key := keyAttrs{
key: string(cmd.Keys[i]),
opaque: cmd.Opaques[i],
quiet: cmd.Quiet[i],
}
// we get the 0 value when the map doesn't contain the data so this
// i correct even for values that don't yet exist
count := tm[key]
tm[key] = count + 1
}
return tm
} | go | func getRequestToTrackerMap(cmd common.GetRequest) trackermap {
tm := make(trackermap)
for i := range cmd.Keys {
key := keyAttrs{
key: string(cmd.Keys[i]),
opaque: cmd.Opaques[i],
quiet: cmd.Quiet[i],
}
// we get the 0 value when the map doesn't contain the data so this
// i correct even for values that don't yet exist
count := tm[key]
tm[key] = count + 1
}
return tm
} | [
"func",
"getRequestToTrackerMap",
"(",
"cmd",
"common",
".",
"GetRequest",
")",
"trackermap",
"{",
"tm",
":=",
"make",
"(",
"trackermap",
")",
"\n\n",
"for",
"i",
":=",
"range",
"cmd",
".",
"Keys",
"{",
"key",
":=",
"keyAttrs",
"{",
"key",
":",
"string",
"(",
"cmd",
".",
"Keys",
"[",
"i",
"]",
")",
",",
"opaque",
":",
"cmd",
".",
"Opaques",
"[",
"i",
"]",
",",
"quiet",
":",
"cmd",
".",
"Quiet",
"[",
"i",
"]",
",",
"}",
"\n\n",
"// we get the 0 value when the map doesn't contain the data so this",
"// i correct even for values that don't yet exist",
"count",
":=",
"tm",
"[",
"key",
"]",
"\n",
"tm",
"[",
"key",
"]",
"=",
"count",
"+",
"1",
"\n",
"}",
"\n\n",
"return",
"tm",
"\n",
"}"
] | // There may be more than one request with the same key and a different opaque
// We may also get "malicious" input where multiple requests have the same
// key and opaque. If the quiet value is the same | [
"There",
"may",
"be",
"more",
"than",
"one",
"request",
"with",
"the",
"same",
"key",
"and",
"a",
"different",
"opaque",
"We",
"may",
"also",
"get",
"malicious",
"input",
"where",
"multiple",
"requests",
"have",
"the",
"same",
"key",
"and",
"opaque",
".",
"If",
"the",
"quiet",
"value",
"is",
"the",
"same"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/batched/handler.go#L247-L264 | train |
Netflix/rend | handlers/memcached/batched/handler.go | GetE | func (h Handler) GetE(cmd common.GetRequest) (<-chan common.GetEResponse, <-chan error) {
dataOut := make(chan common.GetEResponse)
errorOut := make(chan error)
go realHandleGetE(h, cmd, dataOut, errorOut)
return dataOut, errorOut
} | go | func (h Handler) GetE(cmd common.GetRequest) (<-chan common.GetEResponse, <-chan error) {
dataOut := make(chan common.GetEResponse)
errorOut := make(chan error)
go realHandleGetE(h, cmd, dataOut, errorOut)
return dataOut, errorOut
} | [
"func",
"(",
"h",
"Handler",
")",
"GetE",
"(",
"cmd",
"common",
".",
"GetRequest",
")",
"(",
"<-",
"chan",
"common",
".",
"GetEResponse",
",",
"<-",
"chan",
"error",
")",
"{",
"dataOut",
":=",
"make",
"(",
"chan",
"common",
".",
"GetEResponse",
")",
"\n",
"errorOut",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"go",
"realHandleGetE",
"(",
"h",
",",
"cmd",
",",
"dataOut",
",",
"errorOut",
")",
"\n",
"return",
"dataOut",
",",
"errorOut",
"\n",
"}"
] | // GetE performs a get-with-expiration on the backend. It is a custom command only implemented in Rend. It retrieves the
// whole batch of keys given as a group and returns them one at a time over the request channel. | [
"GetE",
"performs",
"a",
"get",
"-",
"with",
"-",
"expiration",
"on",
"the",
"backend",
".",
"It",
"is",
"a",
"custom",
"command",
"only",
"implemented",
"in",
"Rend",
".",
"It",
"retrieves",
"the",
"whole",
"batch",
"of",
"keys",
"given",
"as",
"a",
"group",
"and",
"returns",
"them",
"one",
"at",
"a",
"time",
"over",
"the",
"request",
"channel",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/batched/handler.go#L383-L388 | train |
Netflix/rend | memproxy.go | main | func main() {
var l server.ListenConst
if useDomainSocket {
l = server.UnixListener(sockPath)
} else {
l = server.TCPListener(port)
}
protocols := []protocol.Components{binprot.Components, textprot.Components}
var o orcas.OrcaConst
var h2 handlers.HandlerConst
var h1 handlers.HandlerConst
// Choose the proper L1 handler
if l1inmem {
h1 = inmem.New
} else if chunked {
h1 = memcached.Chunked(l1sock)
} else if l1batched {
h1 = memcached.Batched(l1sock, batchOpts)
} else {
h1 = memcached.Regular(l1sock)
}
if l2enabled {
o = orcas.L1L2
h2 = memcached.Regular(l2sock)
} else {
o = orcas.L1Only
h2 = handlers.NilHandler
}
// Add the locking wrapper if requested. The locking wrapper can either allow mutltiple readers
// or not, with the same difference in semantics between a sync.Mutex and a sync.RWMutex. If
// chunking is enabled, we want to ensure that stricter locking is enabled, since concurrent
// sets into L1 with chunking can collide and cause data corruption.
var lockset uint32
if locked {
if chunked || !multiReader {
o, lockset = orcas.Locked(o, false, uint8(concurrency))
} else {
o, lockset = orcas.Locked(o, true, uint8(concurrency))
}
}
go server.ListenAndServe(l, protocols, server.Default, o, h1, h2)
if l2enabled {
// If L2 is enabled, start the batch L1 / L2 orchestrator
l = server.TCPListener(batchPort)
o := orcas.L1L2Batch
if locked {
o = orcas.LockedWithExisting(o, lockset)
}
go server.ListenAndServe(l, protocols, server.Default, o, h1, h2)
}
// Block forever
wg := sync.WaitGroup{}
wg.Add(1)
wg.Wait()
} | go | func main() {
var l server.ListenConst
if useDomainSocket {
l = server.UnixListener(sockPath)
} else {
l = server.TCPListener(port)
}
protocols := []protocol.Components{binprot.Components, textprot.Components}
var o orcas.OrcaConst
var h2 handlers.HandlerConst
var h1 handlers.HandlerConst
// Choose the proper L1 handler
if l1inmem {
h1 = inmem.New
} else if chunked {
h1 = memcached.Chunked(l1sock)
} else if l1batched {
h1 = memcached.Batched(l1sock, batchOpts)
} else {
h1 = memcached.Regular(l1sock)
}
if l2enabled {
o = orcas.L1L2
h2 = memcached.Regular(l2sock)
} else {
o = orcas.L1Only
h2 = handlers.NilHandler
}
// Add the locking wrapper if requested. The locking wrapper can either allow mutltiple readers
// or not, with the same difference in semantics between a sync.Mutex and a sync.RWMutex. If
// chunking is enabled, we want to ensure that stricter locking is enabled, since concurrent
// sets into L1 with chunking can collide and cause data corruption.
var lockset uint32
if locked {
if chunked || !multiReader {
o, lockset = orcas.Locked(o, false, uint8(concurrency))
} else {
o, lockset = orcas.Locked(o, true, uint8(concurrency))
}
}
go server.ListenAndServe(l, protocols, server.Default, o, h1, h2)
if l2enabled {
// If L2 is enabled, start the batch L1 / L2 orchestrator
l = server.TCPListener(batchPort)
o := orcas.L1L2Batch
if locked {
o = orcas.LockedWithExisting(o, lockset)
}
go server.ListenAndServe(l, protocols, server.Default, o, h1, h2)
}
// Block forever
wg := sync.WaitGroup{}
wg.Add(1)
wg.Wait()
} | [
"func",
"main",
"(",
")",
"{",
"var",
"l",
"server",
".",
"ListenConst",
"\n\n",
"if",
"useDomainSocket",
"{",
"l",
"=",
"server",
".",
"UnixListener",
"(",
"sockPath",
")",
"\n",
"}",
"else",
"{",
"l",
"=",
"server",
".",
"TCPListener",
"(",
"port",
")",
"\n",
"}",
"\n\n",
"protocols",
":=",
"[",
"]",
"protocol",
".",
"Components",
"{",
"binprot",
".",
"Components",
",",
"textprot",
".",
"Components",
"}",
"\n\n",
"var",
"o",
"orcas",
".",
"OrcaConst",
"\n",
"var",
"h2",
"handlers",
".",
"HandlerConst",
"\n",
"var",
"h1",
"handlers",
".",
"HandlerConst",
"\n\n",
"// Choose the proper L1 handler",
"if",
"l1inmem",
"{",
"h1",
"=",
"inmem",
".",
"New",
"\n",
"}",
"else",
"if",
"chunked",
"{",
"h1",
"=",
"memcached",
".",
"Chunked",
"(",
"l1sock",
")",
"\n",
"}",
"else",
"if",
"l1batched",
"{",
"h1",
"=",
"memcached",
".",
"Batched",
"(",
"l1sock",
",",
"batchOpts",
")",
"\n",
"}",
"else",
"{",
"h1",
"=",
"memcached",
".",
"Regular",
"(",
"l1sock",
")",
"\n",
"}",
"\n\n",
"if",
"l2enabled",
"{",
"o",
"=",
"orcas",
".",
"L1L2",
"\n",
"h2",
"=",
"memcached",
".",
"Regular",
"(",
"l2sock",
")",
"\n",
"}",
"else",
"{",
"o",
"=",
"orcas",
".",
"L1Only",
"\n",
"h2",
"=",
"handlers",
".",
"NilHandler",
"\n",
"}",
"\n\n",
"// Add the locking wrapper if requested. The locking wrapper can either allow mutltiple readers",
"// or not, with the same difference in semantics between a sync.Mutex and a sync.RWMutex. If",
"// chunking is enabled, we want to ensure that stricter locking is enabled, since concurrent",
"// sets into L1 with chunking can collide and cause data corruption.",
"var",
"lockset",
"uint32",
"\n",
"if",
"locked",
"{",
"if",
"chunked",
"||",
"!",
"multiReader",
"{",
"o",
",",
"lockset",
"=",
"orcas",
".",
"Locked",
"(",
"o",
",",
"false",
",",
"uint8",
"(",
"concurrency",
")",
")",
"\n",
"}",
"else",
"{",
"o",
",",
"lockset",
"=",
"orcas",
".",
"Locked",
"(",
"o",
",",
"true",
",",
"uint8",
"(",
"concurrency",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"go",
"server",
".",
"ListenAndServe",
"(",
"l",
",",
"protocols",
",",
"server",
".",
"Default",
",",
"o",
",",
"h1",
",",
"h2",
")",
"\n\n",
"if",
"l2enabled",
"{",
"// If L2 is enabled, start the batch L1 / L2 orchestrator",
"l",
"=",
"server",
".",
"TCPListener",
"(",
"batchPort",
")",
"\n",
"o",
":=",
"orcas",
".",
"L1L2Batch",
"\n\n",
"if",
"locked",
"{",
"o",
"=",
"orcas",
".",
"LockedWithExisting",
"(",
"o",
",",
"lockset",
")",
"\n",
"}",
"\n\n",
"go",
"server",
".",
"ListenAndServe",
"(",
"l",
",",
"protocols",
",",
"server",
".",
"Default",
",",
"o",
",",
"h1",
",",
"h2",
")",
"\n",
"}",
"\n\n",
"// Block forever",
"wg",
":=",
"sync",
".",
"WaitGroup",
"{",
"}",
"\n",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"}"
] | // And away we go | [
"And",
"away",
"we",
"go"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/memproxy.go#L167-L232 | train |
Netflix/rend | handlers/memcached/constructors.go | Regular | func Regular(sock string) handlers.HandlerConst {
return func() (handlers.Handler, error) {
conn, err := net.Dial("unix", sock)
if err != nil {
if conn != nil {
conn.Close()
}
return nil, err
}
return std.NewHandler(conn), nil
}
} | go | func Regular(sock string) handlers.HandlerConst {
return func() (handlers.Handler, error) {
conn, err := net.Dial("unix", sock)
if err != nil {
if conn != nil {
conn.Close()
}
return nil, err
}
return std.NewHandler(conn), nil
}
} | [
"func",
"Regular",
"(",
"sock",
"string",
")",
"handlers",
".",
"HandlerConst",
"{",
"return",
"func",
"(",
")",
"(",
"handlers",
".",
"Handler",
",",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"net",
".",
"Dial",
"(",
"\"",
"\"",
",",
"sock",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"conn",
"!=",
"nil",
"{",
"conn",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"std",
".",
"NewHandler",
"(",
"conn",
")",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // Regular returns an implementation of the Handler interface that does standard,
// direct interactions with the external memcached backend which is listening on
// the specified unix domain socket. | [
"Regular",
"returns",
"an",
"implementation",
"of",
"the",
"Handler",
"interface",
"that",
"does",
"standard",
"direct",
"interactions",
"with",
"the",
"external",
"memcached",
"backend",
"which",
"is",
"listening",
"on",
"the",
"specified",
"unix",
"domain",
"socket",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/constructors.go#L30-L41 | train |
Netflix/rend | handlers/memcached/constructors.go | Chunked | func Chunked(sock string) handlers.HandlerConst {
return func() (handlers.Handler, error) {
conn, err := net.Dial("unix", sock)
if err != nil {
log.Println("Error opening connection:", err.Error())
if conn != nil {
conn.Close()
}
return nil, err
}
return chunked.NewHandler(conn), nil
}
} | go | func Chunked(sock string) handlers.HandlerConst {
return func() (handlers.Handler, error) {
conn, err := net.Dial("unix", sock)
if err != nil {
log.Println("Error opening connection:", err.Error())
if conn != nil {
conn.Close()
}
return nil, err
}
return chunked.NewHandler(conn), nil
}
} | [
"func",
"Chunked",
"(",
"sock",
"string",
")",
"handlers",
".",
"HandlerConst",
"{",
"return",
"func",
"(",
")",
"(",
"handlers",
".",
"Handler",
",",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"net",
".",
"Dial",
"(",
"\"",
"\"",
",",
"sock",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"if",
"conn",
"!=",
"nil",
"{",
"conn",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"chunked",
".",
"NewHandler",
"(",
"conn",
")",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // Chunked returns an implementation of the Handler interface that implements an
// interaction model which splits data to set size chunks before inserting. the
// external memcached backend is expected to be listening on the specified unix
// domain socket. | [
"Chunked",
"returns",
"an",
"implementation",
"of",
"the",
"Handler",
"interface",
"that",
"implements",
"an",
"interaction",
"model",
"which",
"splits",
"data",
"to",
"set",
"size",
"chunks",
"before",
"inserting",
".",
"the",
"external",
"memcached",
"backend",
"is",
"expected",
"to",
"be",
"listening",
"on",
"the",
"specified",
"unix",
"domain",
"socket",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/constructors.go#L47-L59 | train |
Netflix/rend | handlers/memcached/constructors.go | Batched | func Batched(sock string, opts batched.Opts) handlers.HandlerConst {
return func() (handlers.Handler, error) {
return batched.NewHandler(sock, opts), nil
}
} | go | func Batched(sock string, opts batched.Opts) handlers.HandlerConst {
return func() (handlers.Handler, error) {
return batched.NewHandler(sock, opts), nil
}
} | [
"func",
"Batched",
"(",
"sock",
"string",
",",
"opts",
"batched",
".",
"Opts",
")",
"handlers",
".",
"HandlerConst",
"{",
"return",
"func",
"(",
")",
"(",
"handlers",
".",
"Handler",
",",
"error",
")",
"{",
"return",
"batched",
".",
"NewHandler",
"(",
"sock",
",",
"opts",
")",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // Batched returns an implementation of the Handler interface that multiplexes
// requests on to a connection pool in order to reduce the overhead per request. | [
"Batched",
"returns",
"an",
"implementation",
"of",
"the",
"Handler",
"interface",
"that",
"multiplexes",
"requests",
"on",
"to",
"a",
"connection",
"pool",
"in",
"order",
"to",
"reduce",
"the",
"overhead",
"per",
"request",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/handlers/memcached/constructors.go#L63-L67 | train |
Netflix/rend | protocol/binprot/commands.go | writeDataCmdCommon | func writeDataCmdCommon(w io.Writer, opcode uint8, key []byte, flags, exptime, dataSize, opaque uint32) error {
// opcode, keyLength, extraLength, totalBodyLength
// key + extras + body
extrasLen := 8
totalBodyLength := len(key) + extrasLen + int(dataSize)
header := makeRequestHeader(opcode, len(key), extrasLen, totalBodyLength, opaque)
writeRequestHeader(w, header)
buf := make([]byte, len(key)+8)
binary.BigEndian.PutUint32(buf[0:4], flags)
binary.BigEndian.PutUint32(buf[4:8], exptime)
copy(buf[8:], key)
n, err := w.Write(buf)
metrics.IncCounterBy(common.MetricBytesWrittenLocal, uint64(n))
reqHeadPool.Put(header)
return err
} | go | func writeDataCmdCommon(w io.Writer, opcode uint8, key []byte, flags, exptime, dataSize, opaque uint32) error {
// opcode, keyLength, extraLength, totalBodyLength
// key + extras + body
extrasLen := 8
totalBodyLength := len(key) + extrasLen + int(dataSize)
header := makeRequestHeader(opcode, len(key), extrasLen, totalBodyLength, opaque)
writeRequestHeader(w, header)
buf := make([]byte, len(key)+8)
binary.BigEndian.PutUint32(buf[0:4], flags)
binary.BigEndian.PutUint32(buf[4:8], exptime)
copy(buf[8:], key)
n, err := w.Write(buf)
metrics.IncCounterBy(common.MetricBytesWrittenLocal, uint64(n))
reqHeadPool.Put(header)
return err
} | [
"func",
"writeDataCmdCommon",
"(",
"w",
"io",
".",
"Writer",
",",
"opcode",
"uint8",
",",
"key",
"[",
"]",
"byte",
",",
"flags",
",",
"exptime",
",",
"dataSize",
",",
"opaque",
"uint32",
")",
"error",
"{",
"// opcode, keyLength, extraLength, totalBodyLength",
"// key + extras + body",
"extrasLen",
":=",
"8",
"\n",
"totalBodyLength",
":=",
"len",
"(",
"key",
")",
"+",
"extrasLen",
"+",
"int",
"(",
"dataSize",
")",
"\n",
"header",
":=",
"makeRequestHeader",
"(",
"opcode",
",",
"len",
"(",
"key",
")",
",",
"extrasLen",
",",
"totalBodyLength",
",",
"opaque",
")",
"\n\n",
"writeRequestHeader",
"(",
"w",
",",
"header",
")",
"\n\n",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"key",
")",
"+",
"8",
")",
"\n",
"binary",
".",
"BigEndian",
".",
"PutUint32",
"(",
"buf",
"[",
"0",
":",
"4",
"]",
",",
"flags",
")",
"\n",
"binary",
".",
"BigEndian",
".",
"PutUint32",
"(",
"buf",
"[",
"4",
":",
"8",
"]",
",",
"exptime",
")",
"\n",
"copy",
"(",
"buf",
"[",
"8",
":",
"]",
",",
"key",
")",
"\n\n",
"n",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"buf",
")",
"\n",
"metrics",
".",
"IncCounterBy",
"(",
"common",
".",
"MetricBytesWrittenLocal",
",",
"uint64",
"(",
"n",
")",
")",
"\n\n",
"reqHeadPool",
".",
"Put",
"(",
"header",
")",
"\n\n",
"return",
"err",
"\n",
"}"
] | // Data commands are those that send a header, key, exptime, and data | [
"Data",
"commands",
"are",
"those",
"that",
"send",
"a",
"header",
"key",
"exptime",
"and",
"data"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/protocol/binprot/commands.go#L26-L46 | train |
Netflix/rend | protocol/binprot/commands.go | WriteSetCmd | func WriteSetCmd(w io.Writer, key []byte, flags, exptime, dataSize, opaque uint32) error {
//fmt.Printf("Set: key: %v | flags: %v | exptime: %v | dataSize: %v | totalBodyLength: %v\n",
//string(key), flags, exptime, dataSize, totalBodyLength)
return writeDataCmdCommon(w, OpcodeSet, key, flags, exptime, dataSize, opaque)
} | go | func WriteSetCmd(w io.Writer, key []byte, flags, exptime, dataSize, opaque uint32) error {
//fmt.Printf("Set: key: %v | flags: %v | exptime: %v | dataSize: %v | totalBodyLength: %v\n",
//string(key), flags, exptime, dataSize, totalBodyLength)
return writeDataCmdCommon(w, OpcodeSet, key, flags, exptime, dataSize, opaque)
} | [
"func",
"WriteSetCmd",
"(",
"w",
"io",
".",
"Writer",
",",
"key",
"[",
"]",
"byte",
",",
"flags",
",",
"exptime",
",",
"dataSize",
",",
"opaque",
"uint32",
")",
"error",
"{",
"//fmt.Printf(\"Set: key: %v | flags: %v | exptime: %v | dataSize: %v | totalBodyLength: %v\\n\",",
"//string(key), flags, exptime, dataSize, totalBodyLength)",
"return",
"writeDataCmdCommon",
"(",
"w",
",",
"OpcodeSet",
",",
"key",
",",
"flags",
",",
"exptime",
",",
"dataSize",
",",
"opaque",
")",
"\n",
"}"
] | // WriteSetCmd writes out the binary representation of a set request header to the given io.Writer | [
"WriteSetCmd",
"writes",
"out",
"the",
"binary",
"representation",
"of",
"a",
"set",
"request",
"header",
"to",
"the",
"given",
"io",
".",
"Writer"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/protocol/binprot/commands.go#L49-L53 | train |
Netflix/rend | protocol/binprot/commands.go | WriteAddCmd | func WriteAddCmd(w io.Writer, key []byte, flags, exptime, dataSize, opaque uint32) error {
//fmt.Printf("Add: key: %v | flags: %v | exptime: %v | dataSize: %v | totalBodyLength: %v\n",
//string(key), flags, exptime, dataSize, totalBodyLength)
return writeDataCmdCommon(w, OpcodeAdd, key, flags, exptime, dataSize, opaque)
} | go | func WriteAddCmd(w io.Writer, key []byte, flags, exptime, dataSize, opaque uint32) error {
//fmt.Printf("Add: key: %v | flags: %v | exptime: %v | dataSize: %v | totalBodyLength: %v\n",
//string(key), flags, exptime, dataSize, totalBodyLength)
return writeDataCmdCommon(w, OpcodeAdd, key, flags, exptime, dataSize, opaque)
} | [
"func",
"WriteAddCmd",
"(",
"w",
"io",
".",
"Writer",
",",
"key",
"[",
"]",
"byte",
",",
"flags",
",",
"exptime",
",",
"dataSize",
",",
"opaque",
"uint32",
")",
"error",
"{",
"//fmt.Printf(\"Add: key: %v | flags: %v | exptime: %v | dataSize: %v | totalBodyLength: %v\\n\",",
"//string(key), flags, exptime, dataSize, totalBodyLength)",
"return",
"writeDataCmdCommon",
"(",
"w",
",",
"OpcodeAdd",
",",
"key",
",",
"flags",
",",
"exptime",
",",
"dataSize",
",",
"opaque",
")",
"\n",
"}"
] | // WriteAddCmd writes out the binary representation of an add request header to the given io.Writer | [
"WriteAddCmd",
"writes",
"out",
"the",
"binary",
"representation",
"of",
"an",
"add",
"request",
"header",
"to",
"the",
"given",
"io",
".",
"Writer"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/protocol/binprot/commands.go#L56-L60 | train |
Netflix/rend | protocol/binprot/commands.go | WriteReplaceCmd | func WriteReplaceCmd(w io.Writer, key []byte, flags, exptime, dataSize, opaque uint32) error {
//fmt.Printf("Replace: key: %v | flags: %v | exptime: %v | dataSize: %v | totalBodyLength: %v\n",
//string(key), flags, exptime, dataSize, totalBodyLength)
return writeDataCmdCommon(w, OpcodeReplace, key, flags, exptime, dataSize, opaque)
} | go | func WriteReplaceCmd(w io.Writer, key []byte, flags, exptime, dataSize, opaque uint32) error {
//fmt.Printf("Replace: key: %v | flags: %v | exptime: %v | dataSize: %v | totalBodyLength: %v\n",
//string(key), flags, exptime, dataSize, totalBodyLength)
return writeDataCmdCommon(w, OpcodeReplace, key, flags, exptime, dataSize, opaque)
} | [
"func",
"WriteReplaceCmd",
"(",
"w",
"io",
".",
"Writer",
",",
"key",
"[",
"]",
"byte",
",",
"flags",
",",
"exptime",
",",
"dataSize",
",",
"opaque",
"uint32",
")",
"error",
"{",
"//fmt.Printf(\"Replace: key: %v | flags: %v | exptime: %v | dataSize: %v | totalBodyLength: %v\\n\",",
"//string(key), flags, exptime, dataSize, totalBodyLength)",
"return",
"writeDataCmdCommon",
"(",
"w",
",",
"OpcodeReplace",
",",
"key",
",",
"flags",
",",
"exptime",
",",
"dataSize",
",",
"opaque",
")",
"\n",
"}"
] | // WriteReplaceCmd writes out the binary representation of a replace request header to the given io.Writer | [
"WriteReplaceCmd",
"writes",
"out",
"the",
"binary",
"representation",
"of",
"a",
"replace",
"request",
"header",
"to",
"the",
"given",
"io",
".",
"Writer"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/protocol/binprot/commands.go#L63-L67 | train |
Netflix/rend | protocol/binprot/commands.go | WriteAppendCmd | func WriteAppendCmd(w io.Writer, key []byte, flags, exptime, dataSize, opaque uint32) error {
//fmt.Printf("Append: key: %v | flags: %v | exptime: %v | dataSize: %v | totalBodyLength: %v\n",
//string(key), flags, exptime, dataSize, totalBodyLength)
return writeAppendPrependCmdCommon(w, OpcodeAppend, key, flags, exptime, dataSize, opaque)
} | go | func WriteAppendCmd(w io.Writer, key []byte, flags, exptime, dataSize, opaque uint32) error {
//fmt.Printf("Append: key: %v | flags: %v | exptime: %v | dataSize: %v | totalBodyLength: %v\n",
//string(key), flags, exptime, dataSize, totalBodyLength)
return writeAppendPrependCmdCommon(w, OpcodeAppend, key, flags, exptime, dataSize, opaque)
} | [
"func",
"WriteAppendCmd",
"(",
"w",
"io",
".",
"Writer",
",",
"key",
"[",
"]",
"byte",
",",
"flags",
",",
"exptime",
",",
"dataSize",
",",
"opaque",
"uint32",
")",
"error",
"{",
"//fmt.Printf(\"Append: key: %v | flags: %v | exptime: %v | dataSize: %v | totalBodyLength: %v\\n\",",
"//string(key), flags, exptime, dataSize, totalBodyLength)",
"return",
"writeAppendPrependCmdCommon",
"(",
"w",
",",
"OpcodeAppend",
",",
"key",
",",
"flags",
",",
"exptime",
",",
"dataSize",
",",
"opaque",
")",
"\n",
"}"
] | // WriteAppendCmd writes out the binary representation of an append request header to the given io.Writer | [
"WriteAppendCmd",
"writes",
"out",
"the",
"binary",
"representation",
"of",
"an",
"append",
"request",
"header",
"to",
"the",
"given",
"io",
".",
"Writer"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/protocol/binprot/commands.go#L86-L90 | train |
Netflix/rend | protocol/binprot/commands.go | WritePrependCmd | func WritePrependCmd(w io.Writer, key []byte, flags, exptime, dataSize, opaque uint32) error {
//fmt.Printf("Prepend: key: %v | flags: %v | exptime: %v | dataSize: %v | totalBodyLength: %v\n",
//string(key), flags, exptime, dataSize, totalBodyLength)
return writeAppendPrependCmdCommon(w, OpcodePrepend, key, flags, exptime, dataSize, opaque)
} | go | func WritePrependCmd(w io.Writer, key []byte, flags, exptime, dataSize, opaque uint32) error {
//fmt.Printf("Prepend: key: %v | flags: %v | exptime: %v | dataSize: %v | totalBodyLength: %v\n",
//string(key), flags, exptime, dataSize, totalBodyLength)
return writeAppendPrependCmdCommon(w, OpcodePrepend, key, flags, exptime, dataSize, opaque)
} | [
"func",
"WritePrependCmd",
"(",
"w",
"io",
".",
"Writer",
",",
"key",
"[",
"]",
"byte",
",",
"flags",
",",
"exptime",
",",
"dataSize",
",",
"opaque",
"uint32",
")",
"error",
"{",
"//fmt.Printf(\"Prepend: key: %v | flags: %v | exptime: %v | dataSize: %v | totalBodyLength: %v\\n\",",
"//string(key), flags, exptime, dataSize, totalBodyLength)",
"return",
"writeAppendPrependCmdCommon",
"(",
"w",
",",
"OpcodePrepend",
",",
"key",
",",
"flags",
",",
"exptime",
",",
"dataSize",
",",
"opaque",
")",
"\n",
"}"
] | // WritePrependCmd writes out the binary representation of a prepend request header to the given io.Writer | [
"WritePrependCmd",
"writes",
"out",
"the",
"binary",
"representation",
"of",
"a",
"prepend",
"request",
"header",
"to",
"the",
"given",
"io",
".",
"Writer"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/protocol/binprot/commands.go#L93-L97 | train |
Netflix/rend | protocol/binprot/commands.go | writeKeyCmd | func writeKeyCmd(w io.Writer, opcode uint8, key []byte, opaque uint32) error {
// opcode, keyLength, extraLength, totalBodyLength
header := makeRequestHeader(opcode, len(key), 0, len(key), opaque)
writeRequestHeader(w, header)
n, err := w.Write(key)
metrics.IncCounterBy(common.MetricBytesWrittenLocal, uint64(ReqHeaderLen+n))
reqHeadPool.Put(header)
return err
} | go | func writeKeyCmd(w io.Writer, opcode uint8, key []byte, opaque uint32) error {
// opcode, keyLength, extraLength, totalBodyLength
header := makeRequestHeader(opcode, len(key), 0, len(key), opaque)
writeRequestHeader(w, header)
n, err := w.Write(key)
metrics.IncCounterBy(common.MetricBytesWrittenLocal, uint64(ReqHeaderLen+n))
reqHeadPool.Put(header)
return err
} | [
"func",
"writeKeyCmd",
"(",
"w",
"io",
".",
"Writer",
",",
"opcode",
"uint8",
",",
"key",
"[",
"]",
"byte",
",",
"opaque",
"uint32",
")",
"error",
"{",
"// opcode, keyLength, extraLength, totalBodyLength",
"header",
":=",
"makeRequestHeader",
"(",
"opcode",
",",
"len",
"(",
"key",
")",
",",
"0",
",",
"len",
"(",
"key",
")",
",",
"opaque",
")",
"\n",
"writeRequestHeader",
"(",
"w",
",",
"header",
")",
"\n\n",
"n",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"key",
")",
"\n\n",
"metrics",
".",
"IncCounterBy",
"(",
"common",
".",
"MetricBytesWrittenLocal",
",",
"uint64",
"(",
"ReqHeaderLen",
"+",
"n",
")",
")",
"\n",
"reqHeadPool",
".",
"Put",
"(",
"header",
")",
"\n\n",
"return",
"err",
"\n",
"}"
] | // Key commands send the header and key only | [
"Key",
"commands",
"send",
"the",
"header",
"and",
"key",
"only"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/protocol/binprot/commands.go#L100-L111 | train |
Netflix/rend | protocol/binprot/commands.go | WriteGetCmd | func WriteGetCmd(w io.Writer, key []byte, opaque uint32) error {
//fmt.Printf("Get: key: %v | totalBodyLength: %v\n", string(key), len(key))
return writeKeyCmd(w, OpcodeGet, key, opaque)
} | go | func WriteGetCmd(w io.Writer, key []byte, opaque uint32) error {
//fmt.Printf("Get: key: %v | totalBodyLength: %v\n", string(key), len(key))
return writeKeyCmd(w, OpcodeGet, key, opaque)
} | [
"func",
"WriteGetCmd",
"(",
"w",
"io",
".",
"Writer",
",",
"key",
"[",
"]",
"byte",
",",
"opaque",
"uint32",
")",
"error",
"{",
"//fmt.Printf(\"Get: key: %v | totalBodyLength: %v\\n\", string(key), len(key))",
"return",
"writeKeyCmd",
"(",
"w",
",",
"OpcodeGet",
",",
"key",
",",
"opaque",
")",
"\n",
"}"
] | // WriteGetCmd writes out the binary representation of a get request header to the given io.Writer | [
"WriteGetCmd",
"writes",
"out",
"the",
"binary",
"representation",
"of",
"a",
"get",
"request",
"header",
"to",
"the",
"given",
"io",
".",
"Writer"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/protocol/binprot/commands.go#L114-L117 | train |
Netflix/rend | protocol/binprot/commands.go | WriteGetQCmd | func WriteGetQCmd(w io.Writer, key []byte, opaque uint32) error {
//fmt.Printf("GetQ: key: %v | totalBodyLength: %v\n", string(key), len(key))
return writeKeyCmd(w, OpcodeGetQ, key, opaque)
} | go | func WriteGetQCmd(w io.Writer, key []byte, opaque uint32) error {
//fmt.Printf("GetQ: key: %v | totalBodyLength: %v\n", string(key), len(key))
return writeKeyCmd(w, OpcodeGetQ, key, opaque)
} | [
"func",
"WriteGetQCmd",
"(",
"w",
"io",
".",
"Writer",
",",
"key",
"[",
"]",
"byte",
",",
"opaque",
"uint32",
")",
"error",
"{",
"//fmt.Printf(\"GetQ: key: %v | totalBodyLength: %v\\n\", string(key), len(key))",
"return",
"writeKeyCmd",
"(",
"w",
",",
"OpcodeGetQ",
",",
"key",
",",
"opaque",
")",
"\n",
"}"
] | // WriteGetQCmd writes out the binary representation of a getq request header to the given io.Writer | [
"WriteGetQCmd",
"writes",
"out",
"the",
"binary",
"representation",
"of",
"a",
"getq",
"request",
"header",
"to",
"the",
"given",
"io",
".",
"Writer"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/protocol/binprot/commands.go#L120-L123 | train |
Netflix/rend | protocol/binprot/commands.go | WriteGetECmd | func WriteGetECmd(w io.Writer, key []byte, opaque uint32) error {
//fmt.Printf("GetE: key: %v | totalBodyLength: %v\n", string(key), len(key))
return writeKeyCmd(w, OpcodeGetE, key, opaque)
} | go | func WriteGetECmd(w io.Writer, key []byte, opaque uint32) error {
//fmt.Printf("GetE: key: %v | totalBodyLength: %v\n", string(key), len(key))
return writeKeyCmd(w, OpcodeGetE, key, opaque)
} | [
"func",
"WriteGetECmd",
"(",
"w",
"io",
".",
"Writer",
",",
"key",
"[",
"]",
"byte",
",",
"opaque",
"uint32",
")",
"error",
"{",
"//fmt.Printf(\"GetE: key: %v | totalBodyLength: %v\\n\", string(key), len(key))",
"return",
"writeKeyCmd",
"(",
"w",
",",
"OpcodeGetE",
",",
"key",
",",
"opaque",
")",
"\n",
"}"
] | // WriteGetECmd writes out the binary representation of a gete request header to the given io.Writer | [
"WriteGetECmd",
"writes",
"out",
"the",
"binary",
"representation",
"of",
"a",
"gete",
"request",
"header",
"to",
"the",
"given",
"io",
".",
"Writer"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/protocol/binprot/commands.go#L126-L129 | train |
Netflix/rend | protocol/binprot/commands.go | WriteGetEQCmd | func WriteGetEQCmd(w io.Writer, key []byte, opaque uint32) error {
//fmt.Printf("GetEQ: key: %v | totalBodyLength: %v\n", string(key), len(key))
return writeKeyCmd(w, OpcodeGetEQ, key, opaque)
} | go | func WriteGetEQCmd(w io.Writer, key []byte, opaque uint32) error {
//fmt.Printf("GetEQ: key: %v | totalBodyLength: %v\n", string(key), len(key))
return writeKeyCmd(w, OpcodeGetEQ, key, opaque)
} | [
"func",
"WriteGetEQCmd",
"(",
"w",
"io",
".",
"Writer",
",",
"key",
"[",
"]",
"byte",
",",
"opaque",
"uint32",
")",
"error",
"{",
"//fmt.Printf(\"GetEQ: key: %v | totalBodyLength: %v\\n\", string(key), len(key))",
"return",
"writeKeyCmd",
"(",
"w",
",",
"OpcodeGetEQ",
",",
"key",
",",
"opaque",
")",
"\n",
"}"
] | // WriteGetEQCmd writes out the binary representation of a geteq request header to the given io.Writer | [
"WriteGetEQCmd",
"writes",
"out",
"the",
"binary",
"representation",
"of",
"a",
"geteq",
"request",
"header",
"to",
"the",
"given",
"io",
".",
"Writer"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/protocol/binprot/commands.go#L132-L135 | train |
Netflix/rend | protocol/binprot/commands.go | WriteDeleteCmd | func WriteDeleteCmd(w io.Writer, key []byte, opaque uint32) error {
//fmt.Printf("Delete: key: %v | totalBodyLength: %v\n", string(key), len(key))
return writeKeyCmd(w, OpcodeDelete, key, opaque)
} | go | func WriteDeleteCmd(w io.Writer, key []byte, opaque uint32) error {
//fmt.Printf("Delete: key: %v | totalBodyLength: %v\n", string(key), len(key))
return writeKeyCmd(w, OpcodeDelete, key, opaque)
} | [
"func",
"WriteDeleteCmd",
"(",
"w",
"io",
".",
"Writer",
",",
"key",
"[",
"]",
"byte",
",",
"opaque",
"uint32",
")",
"error",
"{",
"//fmt.Printf(\"Delete: key: %v | totalBodyLength: %v\\n\", string(key), len(key))",
"return",
"writeKeyCmd",
"(",
"w",
",",
"OpcodeDelete",
",",
"key",
",",
"opaque",
")",
"\n",
"}"
] | // WriteDeleteCmd writes out the binary representation of a delete request header to the given io.Writer | [
"WriteDeleteCmd",
"writes",
"out",
"the",
"binary",
"representation",
"of",
"a",
"delete",
"request",
"header",
"to",
"the",
"given",
"io",
".",
"Writer"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/protocol/binprot/commands.go#L138-L141 | train |
Netflix/rend | protocol/binprot/commands.go | WriteTouchCmd | func WriteTouchCmd(w io.Writer, key []byte, exptime, opaque uint32) error {
//fmt.Printf("Touch: key: %v | exptime: %v | totalBodyLength: %v\n", string(key),
//exptime, totalBodyLength)
return writeKeyExptimeCmd(w, OpcodeTouch, key, exptime, opaque)
} | go | func WriteTouchCmd(w io.Writer, key []byte, exptime, opaque uint32) error {
//fmt.Printf("Touch: key: %v | exptime: %v | totalBodyLength: %v\n", string(key),
//exptime, totalBodyLength)
return writeKeyExptimeCmd(w, OpcodeTouch, key, exptime, opaque)
} | [
"func",
"WriteTouchCmd",
"(",
"w",
"io",
".",
"Writer",
",",
"key",
"[",
"]",
"byte",
",",
"exptime",
",",
"opaque",
"uint32",
")",
"error",
"{",
"//fmt.Printf(\"Touch: key: %v | exptime: %v | totalBodyLength: %v\\n\", string(key),",
"//exptime, totalBodyLength)",
"return",
"writeKeyExptimeCmd",
"(",
"w",
",",
"OpcodeTouch",
",",
"key",
",",
"exptime",
",",
"opaque",
")",
"\n",
"}"
] | // WriteTouchCmd writes out the binary representation of a touch request header to the given io.Writer | [
"WriteTouchCmd",
"writes",
"out",
"the",
"binary",
"representation",
"of",
"a",
"touch",
"request",
"header",
"to",
"the",
"given",
"io",
".",
"Writer"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/protocol/binprot/commands.go#L166-L170 | train |
Netflix/rend | protocol/binprot/commands.go | WriteGATCmd | func WriteGATCmd(w io.Writer, key []byte, exptime, opaque uint32) error {
//fmt.Printf("GAT: key: %v | exptime: %v | totalBodyLength: %v\n", string(key),
//exptime, len(key))
return writeKeyExptimeCmd(w, OpcodeGat, key, exptime, opaque)
} | go | func WriteGATCmd(w io.Writer, key []byte, exptime, opaque uint32) error {
//fmt.Printf("GAT: key: %v | exptime: %v | totalBodyLength: %v\n", string(key),
//exptime, len(key))
return writeKeyExptimeCmd(w, OpcodeGat, key, exptime, opaque)
} | [
"func",
"WriteGATCmd",
"(",
"w",
"io",
".",
"Writer",
",",
"key",
"[",
"]",
"byte",
",",
"exptime",
",",
"opaque",
"uint32",
")",
"error",
"{",
"//fmt.Printf(\"GAT: key: %v | exptime: %v | totalBodyLength: %v\\n\", string(key),",
"//exptime, len(key))",
"return",
"writeKeyExptimeCmd",
"(",
"w",
",",
"OpcodeGat",
",",
"key",
",",
"exptime",
",",
"opaque",
")",
"\n",
"}"
] | // WriteGATCmd writes out the binary representation of a get-and-touch request header to the given io.Writer | [
"WriteGATCmd",
"writes",
"out",
"the",
"binary",
"representation",
"of",
"a",
"get",
"-",
"and",
"-",
"touch",
"request",
"header",
"to",
"the",
"given",
"io",
".",
"Writer"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/protocol/binprot/commands.go#L173-L177 | train |
Netflix/rend | protocol/binprot/commands.go | WriteGATQCmd | func WriteGATQCmd(w io.Writer, key []byte, exptime, opaque uint32) error {
//fmt.Printf("GATQ: key: %v | exptime: %v | totalBodyLength: %v\n", string(key),
//exptime, len(key))
return writeKeyExptimeCmd(w, OpcodeGatQ, key, exptime, opaque)
} | go | func WriteGATQCmd(w io.Writer, key []byte, exptime, opaque uint32) error {
//fmt.Printf("GATQ: key: %v | exptime: %v | totalBodyLength: %v\n", string(key),
//exptime, len(key))
return writeKeyExptimeCmd(w, OpcodeGatQ, key, exptime, opaque)
} | [
"func",
"WriteGATQCmd",
"(",
"w",
"io",
".",
"Writer",
",",
"key",
"[",
"]",
"byte",
",",
"exptime",
",",
"opaque",
"uint32",
")",
"error",
"{",
"//fmt.Printf(\"GATQ: key: %v | exptime: %v | totalBodyLength: %v\\n\", string(key),",
"//exptime, len(key))",
"return",
"writeKeyExptimeCmd",
"(",
"w",
",",
"OpcodeGatQ",
",",
"key",
",",
"exptime",
",",
"opaque",
")",
"\n",
"}"
] | // WriteGATQCmd writes out the binary representation of a get-and-touch quiet request header to the given io.Writer | [
"WriteGATQCmd",
"writes",
"out",
"the",
"binary",
"representation",
"of",
"a",
"get",
"-",
"and",
"-",
"touch",
"quiet",
"request",
"header",
"to",
"the",
"given",
"io",
".",
"Writer"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/protocol/binprot/commands.go#L180-L184 | train |
Netflix/rend | protocol/binprot/commands.go | WriteNoopCmd | func WriteNoopCmd(w io.Writer, opaque uint32) error {
// opcode, keyLength, extraLength, totalBodyLength
header := makeRequestHeader(OpcodeNoop, 0, 0, 0, opaque)
//fmt.Printf("Delete: key: %v | totalBodyLength: %v\n", string(key), len(key))
err := writeRequestHeader(w, header)
metrics.IncCounterBy(common.MetricBytesWrittenLocal, uint64(ReqHeaderLen))
reqHeadPool.Put(header)
return err
} | go | func WriteNoopCmd(w io.Writer, opaque uint32) error {
// opcode, keyLength, extraLength, totalBodyLength
header := makeRequestHeader(OpcodeNoop, 0, 0, 0, opaque)
//fmt.Printf("Delete: key: %v | totalBodyLength: %v\n", string(key), len(key))
err := writeRequestHeader(w, header)
metrics.IncCounterBy(common.MetricBytesWrittenLocal, uint64(ReqHeaderLen))
reqHeadPool.Put(header)
return err
} | [
"func",
"WriteNoopCmd",
"(",
"w",
"io",
".",
"Writer",
",",
"opaque",
"uint32",
")",
"error",
"{",
"// opcode, keyLength, extraLength, totalBodyLength",
"header",
":=",
"makeRequestHeader",
"(",
"OpcodeNoop",
",",
"0",
",",
"0",
",",
"0",
",",
"opaque",
")",
"\n",
"//fmt.Printf(\"Delete: key: %v | totalBodyLength: %v\\n\", string(key), len(key))",
"err",
":=",
"writeRequestHeader",
"(",
"w",
",",
"header",
")",
"\n\n",
"metrics",
".",
"IncCounterBy",
"(",
"common",
".",
"MetricBytesWrittenLocal",
",",
"uint64",
"(",
"ReqHeaderLen",
")",
")",
"\n\n",
"reqHeadPool",
".",
"Put",
"(",
"header",
")",
"\n\n",
"return",
"err",
"\n",
"}"
] | // WriteNoopCmd writes out the binary representation of a noop request header to the given io.Writer | [
"WriteNoopCmd",
"writes",
"out",
"the",
"binary",
"representation",
"of",
"a",
"noop",
"request",
"header",
"to",
"the",
"given",
"io",
".",
"Writer"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/protocol/binprot/commands.go#L187-L199 | train |
Netflix/rend | metrics/histograms.go | ObserveHist | func ObserveHist(id uint32, value uint64) {
h := &hists[id]
// We lock here to ensure that the min and max values are true to this time
// period, meaning extractAndReset won't pull the data out from under us
// while the current observation is being compared. Otherwise, min and max
// could come from the previous period on the next read. Same with average.
h.lock.RLock()
// Keep a running total for average
atomic.AddUint64(&h.dat.total, value)
// Set max and min (if needed) in an atomic fashion
for {
max := atomic.LoadUint64(&h.dat.max)
if value < max || atomic.CompareAndSwapUint64(&h.dat.max, max, value) {
break
}
}
for {
min := atomic.LoadUint64(&h.dat.min)
if value > min || atomic.CompareAndSwapUint64(&h.dat.min, min, value) {
break
}
}
// Record the bucketized histograms
bucket := getBucket(value)
atomic.AddUint64(&bhists[id].buckets[bucket], 1)
// Count and possibly return for sampling
c := atomic.AddUint64(&h.dat.count, 1)
if hSampled[id] {
// Sample, keep every 4th observation
if (c & 0x3) > 0 {
h.lock.RUnlock()
return
}
}
// Get the current index as the count % buflen
idx := atomic.AddUint64(&h.dat.kept, 1) & buflen
// Add observation
h.dat.buf[idx] = value
// No longer "reading"
h.lock.RUnlock()
} | go | func ObserveHist(id uint32, value uint64) {
h := &hists[id]
// We lock here to ensure that the min and max values are true to this time
// period, meaning extractAndReset won't pull the data out from under us
// while the current observation is being compared. Otherwise, min and max
// could come from the previous period on the next read. Same with average.
h.lock.RLock()
// Keep a running total for average
atomic.AddUint64(&h.dat.total, value)
// Set max and min (if needed) in an atomic fashion
for {
max := atomic.LoadUint64(&h.dat.max)
if value < max || atomic.CompareAndSwapUint64(&h.dat.max, max, value) {
break
}
}
for {
min := atomic.LoadUint64(&h.dat.min)
if value > min || atomic.CompareAndSwapUint64(&h.dat.min, min, value) {
break
}
}
// Record the bucketized histograms
bucket := getBucket(value)
atomic.AddUint64(&bhists[id].buckets[bucket], 1)
// Count and possibly return for sampling
c := atomic.AddUint64(&h.dat.count, 1)
if hSampled[id] {
// Sample, keep every 4th observation
if (c & 0x3) > 0 {
h.lock.RUnlock()
return
}
}
// Get the current index as the count % buflen
idx := atomic.AddUint64(&h.dat.kept, 1) & buflen
// Add observation
h.dat.buf[idx] = value
// No longer "reading"
h.lock.RUnlock()
} | [
"func",
"ObserveHist",
"(",
"id",
"uint32",
",",
"value",
"uint64",
")",
"{",
"h",
":=",
"&",
"hists",
"[",
"id",
"]",
"\n\n",
"// We lock here to ensure that the min and max values are true to this time",
"// period, meaning extractAndReset won't pull the data out from under us",
"// while the current observation is being compared. Otherwise, min and max",
"// could come from the previous period on the next read. Same with average.",
"h",
".",
"lock",
".",
"RLock",
"(",
")",
"\n\n",
"// Keep a running total for average",
"atomic",
".",
"AddUint64",
"(",
"&",
"h",
".",
"dat",
".",
"total",
",",
"value",
")",
"\n\n",
"// Set max and min (if needed) in an atomic fashion",
"for",
"{",
"max",
":=",
"atomic",
".",
"LoadUint64",
"(",
"&",
"h",
".",
"dat",
".",
"max",
")",
"\n",
"if",
"value",
"<",
"max",
"||",
"atomic",
".",
"CompareAndSwapUint64",
"(",
"&",
"h",
".",
"dat",
".",
"max",
",",
"max",
",",
"value",
")",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"{",
"min",
":=",
"atomic",
".",
"LoadUint64",
"(",
"&",
"h",
".",
"dat",
".",
"min",
")",
"\n",
"if",
"value",
">",
"min",
"||",
"atomic",
".",
"CompareAndSwapUint64",
"(",
"&",
"h",
".",
"dat",
".",
"min",
",",
"min",
",",
"value",
")",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Record the bucketized histograms",
"bucket",
":=",
"getBucket",
"(",
"value",
")",
"\n",
"atomic",
".",
"AddUint64",
"(",
"&",
"bhists",
"[",
"id",
"]",
".",
"buckets",
"[",
"bucket",
"]",
",",
"1",
")",
"\n\n",
"// Count and possibly return for sampling",
"c",
":=",
"atomic",
".",
"AddUint64",
"(",
"&",
"h",
".",
"dat",
".",
"count",
",",
"1",
")",
"\n",
"if",
"hSampled",
"[",
"id",
"]",
"{",
"// Sample, keep every 4th observation",
"if",
"(",
"c",
"&",
"0x3",
")",
">",
"0",
"{",
"h",
".",
"lock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Get the current index as the count % buflen",
"idx",
":=",
"atomic",
".",
"AddUint64",
"(",
"&",
"h",
".",
"dat",
".",
"kept",
",",
"1",
")",
"&",
"buflen",
"\n\n",
"// Add observation",
"h",
".",
"dat",
".",
"buf",
"[",
"idx",
"]",
"=",
"value",
"\n\n",
"// No longer \"reading\"",
"h",
".",
"lock",
".",
"RUnlock",
"(",
")",
"\n",
"}"
] | // ObserveHist adds an observation to the given histogram. The id parameter is a handle
// returned by the AddHistogram method. Using numbers not returned by AddHistogram is
// undefined behavior and may cause a panic. | [
"ObserveHist",
"adds",
"an",
"observation",
"to",
"the",
"given",
"histogram",
".",
"The",
"id",
"parameter",
"is",
"a",
"handle",
"returned",
"by",
"the",
"AddHistogram",
"method",
".",
"Using",
"numbers",
"not",
"returned",
"by",
"AddHistogram",
"is",
"undefined",
"behavior",
"and",
"may",
"cause",
"a",
"panic",
"."
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/metrics/histograms.go#L252-L300 | train |
Netflix/rend | metrics/endpoint.go | pausePercentiles | func pausePercentiles(pauses []uint64, ngc uint32) []uint64 {
if ngc < uint32(len(pauses)) {
pauses = pauses[:ngc]
}
sort.Sort(uint64slice(pauses))
pctls := make([]uint64, 22)
// Take care of 0th and 100th specially
pctls[0] = pauses[0]
pctls[20] = pauses[len(pauses)-1]
// 5th - 95th
for i := 1; i < 20; i++ {
idx := len(pauses) * i / 20
pctls[i] = pauses[idx]
}
// Add 99th
idx := len(pauses) * 99 / 100
pctls[21] = pauses[idx]
return pctls
} | go | func pausePercentiles(pauses []uint64, ngc uint32) []uint64 {
if ngc < uint32(len(pauses)) {
pauses = pauses[:ngc]
}
sort.Sort(uint64slice(pauses))
pctls := make([]uint64, 22)
// Take care of 0th and 100th specially
pctls[0] = pauses[0]
pctls[20] = pauses[len(pauses)-1]
// 5th - 95th
for i := 1; i < 20; i++ {
idx := len(pauses) * i / 20
pctls[i] = pauses[idx]
}
// Add 99th
idx := len(pauses) * 99 / 100
pctls[21] = pauses[idx]
return pctls
} | [
"func",
"pausePercentiles",
"(",
"pauses",
"[",
"]",
"uint64",
",",
"ngc",
"uint32",
")",
"[",
"]",
"uint64",
"{",
"if",
"ngc",
"<",
"uint32",
"(",
"len",
"(",
"pauses",
")",
")",
"{",
"pauses",
"=",
"pauses",
"[",
":",
"ngc",
"]",
"\n",
"}",
"\n\n",
"sort",
".",
"Sort",
"(",
"uint64slice",
"(",
"pauses",
")",
")",
"\n\n",
"pctls",
":=",
"make",
"(",
"[",
"]",
"uint64",
",",
"22",
")",
"\n\n",
"// Take care of 0th and 100th specially",
"pctls",
"[",
"0",
"]",
"=",
"pauses",
"[",
"0",
"]",
"\n",
"pctls",
"[",
"20",
"]",
"=",
"pauses",
"[",
"len",
"(",
"pauses",
")",
"-",
"1",
"]",
"\n\n",
"// 5th - 95th",
"for",
"i",
":=",
"1",
";",
"i",
"<",
"20",
";",
"i",
"++",
"{",
"idx",
":=",
"len",
"(",
"pauses",
")",
"*",
"i",
"/",
"20",
"\n",
"pctls",
"[",
"i",
"]",
"=",
"pauses",
"[",
"idx",
"]",
"\n",
"}",
"\n\n",
"// Add 99th",
"idx",
":=",
"len",
"(",
"pauses",
")",
"*",
"99",
"/",
"100",
"\n",
"pctls",
"[",
"21",
"]",
"=",
"pauses",
"[",
"idx",
"]",
"\n\n",
"return",
"pctls",
"\n",
"}"
] | // the first 21 positions are the percentiles by 5's from 0 to 100
// the 22nd position is the bonus 99th percentile
// this makes looping over the values easier | [
"the",
"first",
"21",
"positions",
"are",
"the",
"percentiles",
"by",
"5",
"s",
"from",
"0",
"to",
"100",
"the",
"22nd",
"position",
"is",
"the",
"bonus",
"99th",
"percentile",
"this",
"makes",
"looping",
"over",
"the",
"values",
"easier"
] | d3db570668d3ecd97cbdf0988c92145a9040e235 | https://github.com/Netflix/rend/blob/d3db570668d3ecd97cbdf0988c92145a9040e235/metrics/endpoint.go#L223-L247 | train |
ipfs/go-datastore | keytransform/transforms.go | ConvertKey | func (p PrefixTransform) ConvertKey(k ds.Key) ds.Key {
return p.Prefix.Child(k)
} | go | func (p PrefixTransform) ConvertKey(k ds.Key) ds.Key {
return p.Prefix.Child(k)
} | [
"func",
"(",
"p",
"PrefixTransform",
")",
"ConvertKey",
"(",
"k",
"ds",
".",
"Key",
")",
"ds",
".",
"Key",
"{",
"return",
"p",
".",
"Prefix",
".",
"Child",
"(",
"k",
")",
"\n",
"}"
] | // ConvertKey adds the prefix. | [
"ConvertKey",
"adds",
"the",
"prefix",
"."
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/keytransform/transforms.go#L31-L33 | train |
ipfs/go-datastore | keytransform/transforms.go | InvertKey | func (p PrefixTransform) InvertKey(k ds.Key) ds.Key {
if p.Prefix.String() == "/" {
return k
}
if !p.Prefix.IsAncestorOf(k) {
panic("expected prefix not found")
}
s := k.String()[len(p.Prefix.String()):]
return ds.RawKey(s)
} | go | func (p PrefixTransform) InvertKey(k ds.Key) ds.Key {
if p.Prefix.String() == "/" {
return k
}
if !p.Prefix.IsAncestorOf(k) {
panic("expected prefix not found")
}
s := k.String()[len(p.Prefix.String()):]
return ds.RawKey(s)
} | [
"func",
"(",
"p",
"PrefixTransform",
")",
"InvertKey",
"(",
"k",
"ds",
".",
"Key",
")",
"ds",
".",
"Key",
"{",
"if",
"p",
".",
"Prefix",
".",
"String",
"(",
")",
"==",
"\"",
"\"",
"{",
"return",
"k",
"\n",
"}",
"\n\n",
"if",
"!",
"p",
".",
"Prefix",
".",
"IsAncestorOf",
"(",
"k",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"s",
":=",
"k",
".",
"String",
"(",
")",
"[",
"len",
"(",
"p",
".",
"Prefix",
".",
"String",
"(",
")",
")",
":",
"]",
"\n",
"return",
"ds",
".",
"RawKey",
"(",
"s",
")",
"\n",
"}"
] | // InvertKey removes the prefix. panics if prefix not found. | [
"InvertKey",
"removes",
"the",
"prefix",
".",
"panics",
"if",
"prefix",
"not",
"found",
"."
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/keytransform/transforms.go#L36-L47 | train |
ipfs/go-datastore | basic_ds.go | GetSize | func (d *NullDatastore) GetSize(key Key) (size int, err error) {
return -1, ErrNotFound
} | go | func (d *NullDatastore) GetSize(key Key) (size int, err error) {
return -1, ErrNotFound
} | [
"func",
"(",
"d",
"*",
"NullDatastore",
")",
"GetSize",
"(",
"key",
"Key",
")",
"(",
"size",
"int",
",",
"err",
"error",
")",
"{",
"return",
"-",
"1",
",",
"ErrNotFound",
"\n",
"}"
] | // Has implements Datastore.GetSize | [
"Has",
"implements",
"Datastore",
".",
"GetSize"
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/basic_ds.go#L112-L114 | train |
ipfs/go-datastore | basic_ds.go | NewLogDatastore | func NewLogDatastore(ds Datastore, name string) *LogDatastore {
if len(name) < 1 {
name = "LogDatastore"
}
return &LogDatastore{Name: name, child: ds}
} | go | func NewLogDatastore(ds Datastore, name string) *LogDatastore {
if len(name) < 1 {
name = "LogDatastore"
}
return &LogDatastore{Name: name, child: ds}
} | [
"func",
"NewLogDatastore",
"(",
"ds",
"Datastore",
",",
"name",
"string",
")",
"*",
"LogDatastore",
"{",
"if",
"len",
"(",
"name",
")",
"<",
"1",
"{",
"name",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"&",
"LogDatastore",
"{",
"Name",
":",
"name",
",",
"child",
":",
"ds",
"}",
"\n",
"}"
] | // NewLogDatastore constructs a log datastore. | [
"NewLogDatastore",
"constructs",
"a",
"log",
"datastore",
"."
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/basic_ds.go#L148-L153 | train |
ipfs/go-datastore | basic_ds.go | Delete | func (d *LogBatch) Delete(key Key) (err error) {
log.Printf("%s: BatchDelete %s\n", d.Name, key)
return d.child.Delete(key)
} | go | func (d *LogBatch) Delete(key Key) (err error) {
log.Printf("%s: BatchDelete %s\n", d.Name, key)
return d.child.Delete(key)
} | [
"func",
"(",
"d",
"*",
"LogBatch",
")",
"Delete",
"(",
"key",
"Key",
")",
"(",
"err",
"error",
")",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"d",
".",
"Name",
",",
"key",
")",
"\n",
"return",
"d",
".",
"child",
".",
"Delete",
"(",
"key",
")",
"\n",
"}"
] | // Delete implements Batch.Delete | [
"Delete",
"implements",
"Batch",
".",
"Delete"
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/basic_ds.go#L239-L242 | train |
ipfs/go-datastore | basic_ds.go | Commit | func (d *LogBatch) Commit() (err error) {
log.Printf("%s: BatchCommit\n", d.Name)
return d.child.Commit()
} | go | func (d *LogBatch) Commit() (err error) {
log.Printf("%s: BatchCommit\n", d.Name)
return d.child.Commit()
} | [
"func",
"(",
"d",
"*",
"LogBatch",
")",
"Commit",
"(",
")",
"(",
"err",
"error",
")",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"d",
".",
"Name",
")",
"\n",
"return",
"d",
".",
"child",
".",
"Commit",
"(",
")",
"\n",
"}"
] | // Commit implements Batch.Commit | [
"Commit",
"implements",
"Batch",
".",
"Commit"
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/basic_ds.go#L245-L248 | train |
ipfs/go-datastore | examples/fs.go | NewDatastore | func NewDatastore(path string) (ds.Datastore, error) {
if !isDir(path) {
return nil, fmt.Errorf("Failed to find directory at: %v (file? perms?)", path)
}
return &Datastore{path: path}, nil
} | go | func NewDatastore(path string) (ds.Datastore, error) {
if !isDir(path) {
return nil, fmt.Errorf("Failed to find directory at: %v (file? perms?)", path)
}
return &Datastore{path: path}, nil
} | [
"func",
"NewDatastore",
"(",
"path",
"string",
")",
"(",
"ds",
".",
"Datastore",
",",
"error",
")",
"{",
"if",
"!",
"isDir",
"(",
"path",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"path",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"Datastore",
"{",
"path",
":",
"path",
"}",
",",
"nil",
"\n",
"}"
] | // NewDatastore returns a new fs Datastore at given `path` | [
"NewDatastore",
"returns",
"a",
"new",
"fs",
"Datastore",
"at",
"given",
"path"
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/examples/fs.go#L40-L46 | train |
ipfs/go-datastore | examples/fs.go | KeyFilename | func (d *Datastore) KeyFilename(key ds.Key) string {
return filepath.Join(d.path, key.String(), ObjectKeySuffix)
} | go | func (d *Datastore) KeyFilename(key ds.Key) string {
return filepath.Join(d.path, key.String(), ObjectKeySuffix)
} | [
"func",
"(",
"d",
"*",
"Datastore",
")",
"KeyFilename",
"(",
"key",
"ds",
".",
"Key",
")",
"string",
"{",
"return",
"filepath",
".",
"Join",
"(",
"d",
".",
"path",
",",
"key",
".",
"String",
"(",
")",
",",
"ObjectKeySuffix",
")",
"\n",
"}"
] | // KeyFilename returns the filename associated with `key` | [
"KeyFilename",
"returns",
"the",
"filename",
"associated",
"with",
"key"
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/examples/fs.go#L49-L51 | train |
ipfs/go-datastore | examples/fs.go | Put | func (d *Datastore) Put(key ds.Key, value []byte) (err error) {
fn := d.KeyFilename(key)
// mkdirall above.
err = os.MkdirAll(filepath.Dir(fn), 0755)
if err != nil {
return err
}
return ioutil.WriteFile(fn, value, 0666)
} | go | func (d *Datastore) Put(key ds.Key, value []byte) (err error) {
fn := d.KeyFilename(key)
// mkdirall above.
err = os.MkdirAll(filepath.Dir(fn), 0755)
if err != nil {
return err
}
return ioutil.WriteFile(fn, value, 0666)
} | [
"func",
"(",
"d",
"*",
"Datastore",
")",
"Put",
"(",
"key",
"ds",
".",
"Key",
",",
"value",
"[",
"]",
"byte",
")",
"(",
"err",
"error",
")",
"{",
"fn",
":=",
"d",
".",
"KeyFilename",
"(",
"key",
")",
"\n\n",
"// mkdirall above.",
"err",
"=",
"os",
".",
"MkdirAll",
"(",
"filepath",
".",
"Dir",
"(",
"fn",
")",
",",
"0755",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"ioutil",
".",
"WriteFile",
"(",
"fn",
",",
"value",
",",
"0666",
")",
"\n",
"}"
] | // Put stores the given value. | [
"Put",
"stores",
"the",
"given",
"value",
"."
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/examples/fs.go#L54-L64 | train |
ipfs/go-datastore | examples/fs.go | Get | func (d *Datastore) Get(key ds.Key) (value []byte, err error) {
fn := d.KeyFilename(key)
if !isFile(fn) {
return nil, ds.ErrNotFound
}
return ioutil.ReadFile(fn)
} | go | func (d *Datastore) Get(key ds.Key) (value []byte, err error) {
fn := d.KeyFilename(key)
if !isFile(fn) {
return nil, ds.ErrNotFound
}
return ioutil.ReadFile(fn)
} | [
"func",
"(",
"d",
"*",
"Datastore",
")",
"Get",
"(",
"key",
"ds",
".",
"Key",
")",
"(",
"value",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"fn",
":=",
"d",
".",
"KeyFilename",
"(",
"key",
")",
"\n",
"if",
"!",
"isFile",
"(",
"fn",
")",
"{",
"return",
"nil",
",",
"ds",
".",
"ErrNotFound",
"\n",
"}",
"\n\n",
"return",
"ioutil",
".",
"ReadFile",
"(",
"fn",
")",
"\n",
"}"
] | // Get returns the value for given key | [
"Get",
"returns",
"the",
"value",
"for",
"given",
"key"
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/examples/fs.go#L67-L74 | train |
ipfs/go-datastore | examples/fs.go | Has | func (d *Datastore) Has(key ds.Key) (exists bool, err error) {
return ds.GetBackedHas(d, key)
} | go | func (d *Datastore) Has(key ds.Key) (exists bool, err error) {
return ds.GetBackedHas(d, key)
} | [
"func",
"(",
"d",
"*",
"Datastore",
")",
"Has",
"(",
"key",
"ds",
".",
"Key",
")",
"(",
"exists",
"bool",
",",
"err",
"error",
")",
"{",
"return",
"ds",
".",
"GetBackedHas",
"(",
"d",
",",
"key",
")",
"\n",
"}"
] | // Has returns whether the datastore has a value for a given key | [
"Has",
"returns",
"whether",
"the",
"datastore",
"has",
"a",
"value",
"for",
"a",
"given",
"key"
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/examples/fs.go#L77-L79 | train |
ipfs/go-datastore | examples/fs.go | DiskUsage | func (d *Datastore) DiskUsage() (uint64, error) {
var du uint64
err := filepath.Walk(d.path, func(p string, f os.FileInfo, err error) error {
if err != nil {
log.Println(err)
return err
}
if f != nil {
du += uint64(f.Size())
}
return nil
})
return du, err
} | go | func (d *Datastore) DiskUsage() (uint64, error) {
var du uint64
err := filepath.Walk(d.path, func(p string, f os.FileInfo, err error) error {
if err != nil {
log.Println(err)
return err
}
if f != nil {
du += uint64(f.Size())
}
return nil
})
return du, err
} | [
"func",
"(",
"d",
"*",
"Datastore",
")",
"DiskUsage",
"(",
")",
"(",
"uint64",
",",
"error",
")",
"{",
"var",
"du",
"uint64",
"\n",
"err",
":=",
"filepath",
".",
"Walk",
"(",
"d",
".",
"path",
",",
"func",
"(",
"p",
"string",
",",
"f",
"os",
".",
"FileInfo",
",",
"err",
"error",
")",
"error",
"{",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"if",
"f",
"!=",
"nil",
"{",
"du",
"+=",
"uint64",
"(",
"f",
".",
"Size",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"return",
"du",
",",
"err",
"\n",
"}"
] | // DiskUsage returns the disk size used by the datastore in bytes. | [
"DiskUsage",
"returns",
"the",
"disk",
"size",
"used",
"by",
"the",
"datastore",
"in",
"bytes",
"."
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/examples/fs.go#L159-L172 | train |
ipfs/go-datastore | key.go | NewKey | func NewKey(s string) Key {
k := Key{s}
k.Clean()
return k
} | go | func NewKey(s string) Key {
k := Key{s}
k.Clean()
return k
} | [
"func",
"NewKey",
"(",
"s",
"string",
")",
"Key",
"{",
"k",
":=",
"Key",
"{",
"s",
"}",
"\n",
"k",
".",
"Clean",
"(",
")",
"\n",
"return",
"k",
"\n",
"}"
] | // NewKey constructs a key from string. it will clean the value. | [
"NewKey",
"constructs",
"a",
"key",
"from",
"string",
".",
"it",
"will",
"clean",
"the",
"value",
"."
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/key.go#L38-L42 | train |
ipfs/go-datastore | key.go | RawKey | func RawKey(s string) Key {
// accept an empty string and fix it to avoid special cases
// elsewhere
if len(s) == 0 {
return Key{"/"}
}
// perform a quick sanity check that the key is in the correct
// format, if it is not then it is a programmer error and it is
// okay to panic
if len(s) == 0 || s[0] != '/' || (len(s) > 1 && s[len(s)-1] == '/') {
panic("invalid datastore key: " + s)
}
return Key{s}
} | go | func RawKey(s string) Key {
// accept an empty string and fix it to avoid special cases
// elsewhere
if len(s) == 0 {
return Key{"/"}
}
// perform a quick sanity check that the key is in the correct
// format, if it is not then it is a programmer error and it is
// okay to panic
if len(s) == 0 || s[0] != '/' || (len(s) > 1 && s[len(s)-1] == '/') {
panic("invalid datastore key: " + s)
}
return Key{s}
} | [
"func",
"RawKey",
"(",
"s",
"string",
")",
"Key",
"{",
"// accept an empty string and fix it to avoid special cases",
"// elsewhere",
"if",
"len",
"(",
"s",
")",
"==",
"0",
"{",
"return",
"Key",
"{",
"\"",
"\"",
"}",
"\n",
"}",
"\n\n",
"// perform a quick sanity check that the key is in the correct",
"// format, if it is not then it is a programmer error and it is",
"// okay to panic",
"if",
"len",
"(",
"s",
")",
"==",
"0",
"||",
"s",
"[",
"0",
"]",
"!=",
"'/'",
"||",
"(",
"len",
"(",
"s",
")",
">",
"1",
"&&",
"s",
"[",
"len",
"(",
"s",
")",
"-",
"1",
"]",
"==",
"'/'",
")",
"{",
"panic",
"(",
"\"",
"\"",
"+",
"s",
")",
"\n",
"}",
"\n\n",
"return",
"Key",
"{",
"s",
"}",
"\n",
"}"
] | // RawKey creates a new Key without safety checking the input. Use with care. | [
"RawKey",
"creates",
"a",
"new",
"Key",
"without",
"safety",
"checking",
"the",
"input",
".",
"Use",
"with",
"care",
"."
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/key.go#L45-L60 | train |
ipfs/go-datastore | key.go | Clean | func (k *Key) Clean() {
switch {
case len(k.string) == 0:
k.string = "/"
case k.string[0] == '/':
k.string = path.Clean(k.string)
default:
k.string = path.Clean("/" + k.string)
}
} | go | func (k *Key) Clean() {
switch {
case len(k.string) == 0:
k.string = "/"
case k.string[0] == '/':
k.string = path.Clean(k.string)
default:
k.string = path.Clean("/" + k.string)
}
} | [
"func",
"(",
"k",
"*",
"Key",
")",
"Clean",
"(",
")",
"{",
"switch",
"{",
"case",
"len",
"(",
"k",
".",
"string",
")",
"==",
"0",
":",
"k",
".",
"string",
"=",
"\"",
"\"",
"\n",
"case",
"k",
".",
"string",
"[",
"0",
"]",
"==",
"'/'",
":",
"k",
".",
"string",
"=",
"path",
".",
"Clean",
"(",
"k",
".",
"string",
")",
"\n",
"default",
":",
"k",
".",
"string",
"=",
"path",
".",
"Clean",
"(",
"\"",
"\"",
"+",
"k",
".",
"string",
")",
"\n",
"}",
"\n",
"}"
] | // Clean up a Key, using path.Clean. | [
"Clean",
"up",
"a",
"Key",
"using",
"path",
".",
"Clean",
"."
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/key.go#L68-L77 | train |
ipfs/go-datastore | key.go | Equal | func (k Key) Equal(k2 Key) bool {
return k.string == k2.string
} | go | func (k Key) Equal(k2 Key) bool {
return k.string == k2.string
} | [
"func",
"(",
"k",
"Key",
")",
"Equal",
"(",
"k2",
"Key",
")",
"bool",
"{",
"return",
"k",
".",
"string",
"==",
"k2",
".",
"string",
"\n",
"}"
] | // Equal checks equality of two keys | [
"Equal",
"checks",
"equality",
"of",
"two",
"keys"
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/key.go#L90-L92 | train |
ipfs/go-datastore | key.go | Less | func (k Key) Less(k2 Key) bool {
list1 := k.List()
list2 := k2.List()
for i, c1 := range list1 {
if len(list2) < (i + 1) {
return false
}
c2 := list2[i]
if c1 < c2 {
return true
} else if c1 > c2 {
return false
}
// c1 == c2, continue
}
// list1 is shorter or exactly the same.
return len(list1) < len(list2)
} | go | func (k Key) Less(k2 Key) bool {
list1 := k.List()
list2 := k2.List()
for i, c1 := range list1 {
if len(list2) < (i + 1) {
return false
}
c2 := list2[i]
if c1 < c2 {
return true
} else if c1 > c2 {
return false
}
// c1 == c2, continue
}
// list1 is shorter or exactly the same.
return len(list1) < len(list2)
} | [
"func",
"(",
"k",
"Key",
")",
"Less",
"(",
"k2",
"Key",
")",
"bool",
"{",
"list1",
":=",
"k",
".",
"List",
"(",
")",
"\n",
"list2",
":=",
"k2",
".",
"List",
"(",
")",
"\n",
"for",
"i",
",",
"c1",
":=",
"range",
"list1",
"{",
"if",
"len",
"(",
"list2",
")",
"<",
"(",
"i",
"+",
"1",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"c2",
":=",
"list2",
"[",
"i",
"]",
"\n",
"if",
"c1",
"<",
"c2",
"{",
"return",
"true",
"\n",
"}",
"else",
"if",
"c1",
">",
"c2",
"{",
"return",
"false",
"\n",
"}",
"\n",
"// c1 == c2, continue",
"}",
"\n\n",
"// list1 is shorter or exactly the same.",
"return",
"len",
"(",
"list1",
")",
"<",
"len",
"(",
"list2",
")",
"\n",
"}"
] | // Less checks whether this key is sorted lower than another. | [
"Less",
"checks",
"whether",
"this",
"key",
"is",
"sorted",
"lower",
"than",
"another",
"."
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/key.go#L95-L114 | train |
ipfs/go-datastore | key.go | UnmarshalJSON | func (k *Key) UnmarshalJSON(data []byte) error {
var key string
if err := json.Unmarshal(data, &key); err != nil {
return err
}
*k = NewKey(key)
return nil
} | go | func (k *Key) UnmarshalJSON(data []byte) error {
var key string
if err := json.Unmarshal(data, &key); err != nil {
return err
}
*k = NewKey(key)
return nil
} | [
"func",
"(",
"k",
"*",
"Key",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"key",
"string",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"key",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"*",
"k",
"=",
"NewKey",
"(",
"key",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalJSON implements the json.Unmarshaler interface,
// keys will parse any value specified as a key to a string | [
"UnmarshalJSON",
"implements",
"the",
"json",
".",
"Unmarshaler",
"interface",
"keys",
"will",
"parse",
"any",
"value",
"specified",
"as",
"a",
"key",
"to",
"a",
"string"
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/key.go#L244-L251 | train |
ipfs/go-datastore | query/query_impl.go | NaiveFilter | func NaiveFilter(qr Results, filter Filter) Results {
return ResultsFromIterator(qr.Query(), Iterator{
Next: func() (Result, bool) {
for {
e, ok := qr.NextSync()
if !ok {
return Result{}, false
}
if e.Error != nil || filter.Filter(e.Entry) {
return e, true
}
}
},
Close: func() error {
return qr.Close()
},
})
} | go | func NaiveFilter(qr Results, filter Filter) Results {
return ResultsFromIterator(qr.Query(), Iterator{
Next: func() (Result, bool) {
for {
e, ok := qr.NextSync()
if !ok {
return Result{}, false
}
if e.Error != nil || filter.Filter(e.Entry) {
return e, true
}
}
},
Close: func() error {
return qr.Close()
},
})
} | [
"func",
"NaiveFilter",
"(",
"qr",
"Results",
",",
"filter",
"Filter",
")",
"Results",
"{",
"return",
"ResultsFromIterator",
"(",
"qr",
".",
"Query",
"(",
")",
",",
"Iterator",
"{",
"Next",
":",
"func",
"(",
")",
"(",
"Result",
",",
"bool",
")",
"{",
"for",
"{",
"e",
",",
"ok",
":=",
"qr",
".",
"NextSync",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"Result",
"{",
"}",
",",
"false",
"\n",
"}",
"\n",
"if",
"e",
".",
"Error",
"!=",
"nil",
"||",
"filter",
".",
"Filter",
"(",
"e",
".",
"Entry",
")",
"{",
"return",
"e",
",",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
",",
"Close",
":",
"func",
"(",
")",
"error",
"{",
"return",
"qr",
".",
"Close",
"(",
")",
"\n",
"}",
",",
"}",
")",
"\n",
"}"
] | // NaiveFilter applies a filter to the results. | [
"NaiveFilter",
"applies",
"a",
"filter",
"to",
"the",
"results",
"."
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/query/query_impl.go#L8-L25 | train |
ipfs/go-datastore | query/query_impl.go | NaiveLimit | func NaiveLimit(qr Results, limit int) Results {
if limit == 0 {
// 0 means no limit
return qr
}
closed := false
return ResultsFromIterator(qr.Query(), Iterator{
Next: func() (Result, bool) {
if limit == 0 {
if !closed {
closed = true
err := qr.Close()
if err != nil {
return Result{Error: err}, true
}
}
return Result{}, false
}
limit--
return qr.NextSync()
},
Close: func() error {
if closed {
return nil
}
closed = true
return qr.Close()
},
})
} | go | func NaiveLimit(qr Results, limit int) Results {
if limit == 0 {
// 0 means no limit
return qr
}
closed := false
return ResultsFromIterator(qr.Query(), Iterator{
Next: func() (Result, bool) {
if limit == 0 {
if !closed {
closed = true
err := qr.Close()
if err != nil {
return Result{Error: err}, true
}
}
return Result{}, false
}
limit--
return qr.NextSync()
},
Close: func() error {
if closed {
return nil
}
closed = true
return qr.Close()
},
})
} | [
"func",
"NaiveLimit",
"(",
"qr",
"Results",
",",
"limit",
"int",
")",
"Results",
"{",
"if",
"limit",
"==",
"0",
"{",
"// 0 means no limit",
"return",
"qr",
"\n",
"}",
"\n",
"closed",
":=",
"false",
"\n",
"return",
"ResultsFromIterator",
"(",
"qr",
".",
"Query",
"(",
")",
",",
"Iterator",
"{",
"Next",
":",
"func",
"(",
")",
"(",
"Result",
",",
"bool",
")",
"{",
"if",
"limit",
"==",
"0",
"{",
"if",
"!",
"closed",
"{",
"closed",
"=",
"true",
"\n",
"err",
":=",
"qr",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Result",
"{",
"Error",
":",
"err",
"}",
",",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"Result",
"{",
"}",
",",
"false",
"\n",
"}",
"\n",
"limit",
"--",
"\n",
"return",
"qr",
".",
"NextSync",
"(",
")",
"\n",
"}",
",",
"Close",
":",
"func",
"(",
")",
"error",
"{",
"if",
"closed",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"closed",
"=",
"true",
"\n",
"return",
"qr",
".",
"Close",
"(",
")",
"\n",
"}",
",",
"}",
")",
"\n",
"}"
] | // NaiveLimit truncates the results to a given int limit | [
"NaiveLimit",
"truncates",
"the",
"results",
"to",
"a",
"given",
"int",
"limit"
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/query/query_impl.go#L28-L57 | train |
ipfs/go-datastore | query/query_impl.go | NaiveOffset | func NaiveOffset(qr Results, offset int) Results {
return ResultsFromIterator(qr.Query(), Iterator{
Next: func() (Result, bool) {
for ; offset > 0; offset-- {
res, ok := qr.NextSync()
if !ok || res.Error != nil {
return res, ok
}
}
return qr.NextSync()
},
Close: func() error {
return qr.Close()
},
})
} | go | func NaiveOffset(qr Results, offset int) Results {
return ResultsFromIterator(qr.Query(), Iterator{
Next: func() (Result, bool) {
for ; offset > 0; offset-- {
res, ok := qr.NextSync()
if !ok || res.Error != nil {
return res, ok
}
}
return qr.NextSync()
},
Close: func() error {
return qr.Close()
},
})
} | [
"func",
"NaiveOffset",
"(",
"qr",
"Results",
",",
"offset",
"int",
")",
"Results",
"{",
"return",
"ResultsFromIterator",
"(",
"qr",
".",
"Query",
"(",
")",
",",
"Iterator",
"{",
"Next",
":",
"func",
"(",
")",
"(",
"Result",
",",
"bool",
")",
"{",
"for",
";",
"offset",
">",
"0",
";",
"offset",
"--",
"{",
"res",
",",
"ok",
":=",
"qr",
".",
"NextSync",
"(",
")",
"\n",
"if",
"!",
"ok",
"||",
"res",
".",
"Error",
"!=",
"nil",
"{",
"return",
"res",
",",
"ok",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"qr",
".",
"NextSync",
"(",
")",
"\n",
"}",
",",
"Close",
":",
"func",
"(",
")",
"error",
"{",
"return",
"qr",
".",
"Close",
"(",
")",
"\n",
"}",
",",
"}",
")",
"\n",
"}"
] | // NaiveOffset skips a given number of results | [
"NaiveOffset",
"skips",
"a",
"given",
"number",
"of",
"results"
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/query/query_impl.go#L60-L75 | train |
ipfs/go-datastore | query/order.go | Less | func Less(orders []Order, a, b Entry) bool {
for _, cmp := range orders {
switch cmp.Compare(a, b) {
case 0:
case -1:
return true
case 1:
return false
}
}
// This gives us a *stable* sort for free. We don't care
// preserving the order from the underlying datastore
// because it's undefined.
return a.Key < b.Key
} | go | func Less(orders []Order, a, b Entry) bool {
for _, cmp := range orders {
switch cmp.Compare(a, b) {
case 0:
case -1:
return true
case 1:
return false
}
}
// This gives us a *stable* sort for free. We don't care
// preserving the order from the underlying datastore
// because it's undefined.
return a.Key < b.Key
} | [
"func",
"Less",
"(",
"orders",
"[",
"]",
"Order",
",",
"a",
",",
"b",
"Entry",
")",
"bool",
"{",
"for",
"_",
",",
"cmp",
":=",
"range",
"orders",
"{",
"switch",
"cmp",
".",
"Compare",
"(",
"a",
",",
"b",
")",
"{",
"case",
"0",
":",
"case",
"-",
"1",
":",
"return",
"true",
"\n",
"case",
"1",
":",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n\n",
"// This gives us a *stable* sort for free. We don't care",
"// preserving the order from the underlying datastore",
"// because it's undefined.",
"return",
"a",
".",
"Key",
"<",
"b",
".",
"Key",
"\n",
"}"
] | // Less returns true if a comes before b with the requested orderings. | [
"Less",
"returns",
"true",
"if",
"a",
"comes",
"before",
"b",
"with",
"the",
"requested",
"orderings",
"."
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/query/order.go#L52-L67 | train |
ipfs/go-datastore | query/order.go | Sort | func Sort(orders []Order, entries []Entry) {
sort.Slice(entries, func(i int, j int) bool {
return Less(orders, entries[i], entries[j])
})
} | go | func Sort(orders []Order, entries []Entry) {
sort.Slice(entries, func(i int, j int) bool {
return Less(orders, entries[i], entries[j])
})
} | [
"func",
"Sort",
"(",
"orders",
"[",
"]",
"Order",
",",
"entries",
"[",
"]",
"Entry",
")",
"{",
"sort",
".",
"Slice",
"(",
"entries",
",",
"func",
"(",
"i",
"int",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"Less",
"(",
"orders",
",",
"entries",
"[",
"i",
"]",
",",
"entries",
"[",
"j",
"]",
")",
"\n",
"}",
")",
"\n",
"}"
] | // Sort sorts the given entries using the given orders. | [
"Sort",
"sorts",
"the",
"given",
"entries",
"using",
"the",
"given",
"orders",
"."
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/query/order.go#L70-L74 | train |
ipfs/go-datastore | delayed/delayed.go | New | func New(ds ds.Datastore, delay delay.D) *Delayed {
return &Delayed{ds: ds, delay: delay}
} | go | func New(ds ds.Datastore, delay delay.D) *Delayed {
return &Delayed{ds: ds, delay: delay}
} | [
"func",
"New",
"(",
"ds",
"ds",
".",
"Datastore",
",",
"delay",
"delay",
".",
"D",
")",
"*",
"Delayed",
"{",
"return",
"&",
"Delayed",
"{",
"ds",
":",
"ds",
",",
"delay",
":",
"delay",
"}",
"\n",
"}"
] | // New returns a new delayed datastore. | [
"New",
"returns",
"a",
"new",
"delayed",
"datastore",
"."
] | aa9190c18f1576be98e974359fd08c64ca0b5a94 | https://github.com/ipfs/go-datastore/blob/aa9190c18f1576be98e974359fd08c64ca0b5a94/delayed/delayed.go#L14-L16 | 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.