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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
vsergeev/btckeygenie | btckey/btckey.go | ToWIF | func (priv *PrivateKey) ToWIF() (wif string) {
/* See https://en.bitcoin.it/wiki/Wallet_import_format */
/* Convert the private key to bytes */
priv_bytes := priv.ToBytes()
/* Convert bytes to base-58 check encoded string with version 0x80 */
wif = b58checkencode(0x80, priv_bytes)
return wif
} | go | func (priv *PrivateKey) ToWIF() (wif string) {
/* See https://en.bitcoin.it/wiki/Wallet_import_format */
/* Convert the private key to bytes */
priv_bytes := priv.ToBytes()
/* Convert bytes to base-58 check encoded string with version 0x80 */
wif = b58checkencode(0x80, priv_bytes)
return wif
} | [
"func",
"(",
"priv",
"*",
"PrivateKey",
")",
"ToWIF",
"(",
")",
"(",
"wif",
"string",
")",
"{",
"/* See https://en.bitcoin.it/wiki/Wallet_import_format */",
"/* Convert the private key to bytes */",
"priv_bytes",
":=",
"priv",
".",
"ToBytes",
"(",
")",
"\n\n",
"/* Con... | // ToWIF converts a Bitcoin private key to a Wallet Import Format string. | [
"ToWIF",
"converts",
"a",
"Bitcoin",
"private",
"key",
"to",
"a",
"Wallet",
"Import",
"Format",
"string",
"."
] | 413cbe3261adadbc974cecdbb4ea0b86c813c1a0 | https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/btckey.go#L302-L312 | train |
vsergeev/btckeygenie | btckey/btckey.go | ToWIFC | func (priv *PrivateKey) ToWIFC() (wifc string) {
/* See https://en.bitcoin.it/wiki/Wallet_import_format */
/* Convert the private key to bytes */
priv_bytes := priv.ToBytes()
/* Append 0x01 to tell Bitcoin wallet to use compressed public keys */
priv_bytes = append(priv_bytes, []byte{0x01}...)
/* Convert bytes to base-58 check encoded string with version 0x80 */
wifc = b58checkencode(0x80, priv_bytes)
return wifc
} | go | func (priv *PrivateKey) ToWIFC() (wifc string) {
/* See https://en.bitcoin.it/wiki/Wallet_import_format */
/* Convert the private key to bytes */
priv_bytes := priv.ToBytes()
/* Append 0x01 to tell Bitcoin wallet to use compressed public keys */
priv_bytes = append(priv_bytes, []byte{0x01}...)
/* Convert bytes to base-58 check encoded string with version 0x80 */
wifc = b58checkencode(0x80, priv_bytes)
return wifc
} | [
"func",
"(",
"priv",
"*",
"PrivateKey",
")",
"ToWIFC",
"(",
")",
"(",
"wifc",
"string",
")",
"{",
"/* See https://en.bitcoin.it/wiki/Wallet_import_format */",
"/* Convert the private key to bytes */",
"priv_bytes",
":=",
"priv",
".",
"ToBytes",
"(",
")",
"\n\n",
"/* A... | // ToWIFC converts a Bitcoin private key to a Wallet Import Format string with the public key compressed flag. | [
"ToWIFC",
"converts",
"a",
"Bitcoin",
"private",
"key",
"to",
"a",
"Wallet",
"Import",
"Format",
"string",
"with",
"the",
"public",
"key",
"compressed",
"flag",
"."
] | 413cbe3261adadbc974cecdbb4ea0b86c813c1a0 | https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/btckey.go#L315-L328 | train |
vsergeev/btckeygenie | btckey/btckey.go | FromWIF | func (priv *PrivateKey) FromWIF(wif string) (err error) {
/* See https://en.bitcoin.it/wiki/Wallet_import_format */
/* Base58 Check Decode the WIF string */
ver, priv_bytes, err := b58checkdecode(wif)
if err != nil {
return err
}
/* Check that the version byte is 0x80 */
if ver != 0x80 {
return fmt.Errorf("Invalid WIF version 0x%02x, expected 0x80.", ver)
}
/* If the private key bytes length is 33, check that suffix byte is 0x01 (for compression) and strip it off */
if len(priv_bytes) == 33 {
if priv_bytes[len(priv_bytes)-1] != 0x01 {
return fmt.Errorf("Invalid private key, unknown suffix byte 0x%02x.", priv_bytes[len(priv_bytes)-1])
}
priv_bytes = priv_bytes[0:32]
}
/* Convert from bytes to a private key */
err = priv.FromBytes(priv_bytes)
if err != nil {
return err
}
/* Derive public key from private key */
priv.derive()
return nil
} | go | func (priv *PrivateKey) FromWIF(wif string) (err error) {
/* See https://en.bitcoin.it/wiki/Wallet_import_format */
/* Base58 Check Decode the WIF string */
ver, priv_bytes, err := b58checkdecode(wif)
if err != nil {
return err
}
/* Check that the version byte is 0x80 */
if ver != 0x80 {
return fmt.Errorf("Invalid WIF version 0x%02x, expected 0x80.", ver)
}
/* If the private key bytes length is 33, check that suffix byte is 0x01 (for compression) and strip it off */
if len(priv_bytes) == 33 {
if priv_bytes[len(priv_bytes)-1] != 0x01 {
return fmt.Errorf("Invalid private key, unknown suffix byte 0x%02x.", priv_bytes[len(priv_bytes)-1])
}
priv_bytes = priv_bytes[0:32]
}
/* Convert from bytes to a private key */
err = priv.FromBytes(priv_bytes)
if err != nil {
return err
}
/* Derive public key from private key */
priv.derive()
return nil
} | [
"func",
"(",
"priv",
"*",
"PrivateKey",
")",
"FromWIF",
"(",
"wif",
"string",
")",
"(",
"err",
"error",
")",
"{",
"/* See https://en.bitcoin.it/wiki/Wallet_import_format */",
"/* Base58 Check Decode the WIF string */",
"ver",
",",
"priv_bytes",
",",
"err",
":=",
"b58c... | // FromWIF converts a Wallet Import Format string to a Bitcoin private key and derives the corresponding Bitcoin public key. | [
"FromWIF",
"converts",
"a",
"Wallet",
"Import",
"Format",
"string",
"to",
"a",
"Bitcoin",
"private",
"key",
"and",
"derives",
"the",
"corresponding",
"Bitcoin",
"public",
"key",
"."
] | 413cbe3261adadbc974cecdbb4ea0b86c813c1a0 | https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/btckey.go#L331-L363 | train |
vsergeev/btckeygenie | btckey/btckey.go | ToBytesUncompressed | func (pub *PublicKey) ToBytesUncompressed() (b []byte) {
/* See Certicom SEC1 2.3.3, pg. 10 */
x := pub.X.Bytes()
y := pub.Y.Bytes()
/* Pad X and Y coordinate bytes to 32-bytes */
padded_x := append(bytes.Repeat([]byte{0x00}, 32-len(x)), x...)
padded_y := append(bytes.Repeat([]byte{0x00}, 32-len(y)), y...)
/* Add prefix 0x04 for uncompressed coordinates */
return append([]byte{0x04}, append(padded_x, padded_y...)...)
} | go | func (pub *PublicKey) ToBytesUncompressed() (b []byte) {
/* See Certicom SEC1 2.3.3, pg. 10 */
x := pub.X.Bytes()
y := pub.Y.Bytes()
/* Pad X and Y coordinate bytes to 32-bytes */
padded_x := append(bytes.Repeat([]byte{0x00}, 32-len(x)), x...)
padded_y := append(bytes.Repeat([]byte{0x00}, 32-len(y)), y...)
/* Add prefix 0x04 for uncompressed coordinates */
return append([]byte{0x04}, append(padded_x, padded_y...)...)
} | [
"func",
"(",
"pub",
"*",
"PublicKey",
")",
"ToBytesUncompressed",
"(",
")",
"(",
"b",
"[",
"]",
"byte",
")",
"{",
"/* See Certicom SEC1 2.3.3, pg. 10 */",
"x",
":=",
"pub",
".",
"X",
".",
"Bytes",
"(",
")",
"\n",
"y",
":=",
"pub",
".",
"Y",
".",
"Byt... | // ToBytesUncompressed converts a Bitcoin public key to a 65-byte byte slice without point compression. | [
"ToBytesUncompressed",
"converts",
"a",
"Bitcoin",
"public",
"key",
"to",
"a",
"65",
"-",
"byte",
"byte",
"slice",
"without",
"point",
"compression",
"."
] | 413cbe3261adadbc974cecdbb4ea0b86c813c1a0 | https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/btckey.go#L387-L399 | train |
vsergeev/btckeygenie | btckey/btckey.go | ToAddress | func (pub *PublicKey) ToAddress() (address string) {
/* See https://en.bitcoin.it/wiki/Technical_background_of_Bitcoin_addresses */
/* Convert the public key to bytes */
pub_bytes := pub.ToBytes()
/* SHA256 Hash */
sha256_h := sha256.New()
sha256_h.Reset()
sha256_h.Write(pub_bytes)
pub_hash_1 := sha256_h.Sum(nil)
/* RIPEMD-160 Hash */
ripemd160_h := ripemd160.New()
ripemd160_h.Reset()
ripemd160_h.Write(pub_hash_1)
pub_hash_2 := ripemd160_h.Sum(nil)
/* Convert hash bytes to base58 check encoded sequence */
address = b58checkencode(0x00, pub_hash_2)
return address
} | go | func (pub *PublicKey) ToAddress() (address string) {
/* See https://en.bitcoin.it/wiki/Technical_background_of_Bitcoin_addresses */
/* Convert the public key to bytes */
pub_bytes := pub.ToBytes()
/* SHA256 Hash */
sha256_h := sha256.New()
sha256_h.Reset()
sha256_h.Write(pub_bytes)
pub_hash_1 := sha256_h.Sum(nil)
/* RIPEMD-160 Hash */
ripemd160_h := ripemd160.New()
ripemd160_h.Reset()
ripemd160_h.Write(pub_hash_1)
pub_hash_2 := ripemd160_h.Sum(nil)
/* Convert hash bytes to base58 check encoded sequence */
address = b58checkencode(0x00, pub_hash_2)
return address
} | [
"func",
"(",
"pub",
"*",
"PublicKey",
")",
"ToAddress",
"(",
")",
"(",
"address",
"string",
")",
"{",
"/* See https://en.bitcoin.it/wiki/Technical_background_of_Bitcoin_addresses */",
"/* Convert the public key to bytes */",
"pub_bytes",
":=",
"pub",
".",
"ToBytes",
"(",
... | // ToAddress converts a Bitcoin public key to a compressed Bitcoin address string. | [
"ToAddress",
"converts",
"a",
"Bitcoin",
"public",
"key",
"to",
"a",
"compressed",
"Bitcoin",
"address",
"string",
"."
] | 413cbe3261adadbc974cecdbb4ea0b86c813c1a0 | https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/btckey.go#L447-L469 | train |
vsergeev/btckeygenie | btckey/elliptic.go | format | func (p *Point) format() string {
if p.X == nil && p.Y == nil {
return "(inf,inf)"
}
return fmt.Sprintf("(%s,%s)", hex.EncodeToString(p.X.Bytes()), hex.EncodeToString(p.Y.Bytes()))
} | go | func (p *Point) format() string {
if p.X == nil && p.Y == nil {
return "(inf,inf)"
}
return fmt.Sprintf("(%s,%s)", hex.EncodeToString(p.X.Bytes()), hex.EncodeToString(p.Y.Bytes()))
} | [
"func",
"(",
"p",
"*",
"Point",
")",
"format",
"(",
")",
"string",
"{",
"if",
"p",
".",
"X",
"==",
"nil",
"&&",
"p",
".",
"Y",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"... | // format formats the bytes of a point for debugging. | [
"format",
"formats",
"the",
"bytes",
"of",
"a",
"point",
"for",
"debugging",
"."
] | 413cbe3261adadbc974cecdbb4ea0b86c813c1a0 | https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/elliptic.go#L43-L48 | train |
vsergeev/btckeygenie | btckey/elliptic.go | IsOnCurve | func (ec *EllipticCurve) IsOnCurve(P Point) bool {
if ec.IsInfinity(P) {
return false
}
/* y**2 = x**3 + a*x + b % p */
lhs := mulMod(P.Y, P.Y, ec.P)
rhs := addMod(
addMod(
expMod(P.X, big.NewInt(3), ec.P),
mulMod(ec.A, P.X, ec.P), ec.P),
ec.B, ec.P)
if lhs.Cmp(rhs) == 0 {
return true
}
return false
} | go | func (ec *EllipticCurve) IsOnCurve(P Point) bool {
if ec.IsInfinity(P) {
return false
}
/* y**2 = x**3 + a*x + b % p */
lhs := mulMod(P.Y, P.Y, ec.P)
rhs := addMod(
addMod(
expMod(P.X, big.NewInt(3), ec.P),
mulMod(ec.A, P.X, ec.P), ec.P),
ec.B, ec.P)
if lhs.Cmp(rhs) == 0 {
return true
}
return false
} | [
"func",
"(",
"ec",
"*",
"EllipticCurve",
")",
"IsOnCurve",
"(",
"P",
"Point",
")",
"bool",
"{",
"if",
"ec",
".",
"IsInfinity",
"(",
"P",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"/* y**2 = x**3 + a*x + b % p */",
"lhs",
":=",
"mulMod",
"(",
"P",
... | // IsOnCurve checks if point P is on EllipticCurve ec. | [
"IsOnCurve",
"checks",
"if",
"point",
"P",
"is",
"on",
"EllipticCurve",
"ec",
"."
] | 413cbe3261adadbc974cecdbb4ea0b86c813c1a0 | https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/elliptic.go#L128-L146 | train |
gocarina/gocsv | csv.go | LazyCSVReader | func LazyCSVReader(in io.Reader) CSVReader {
csvReader := csv.NewReader(in)
csvReader.LazyQuotes = true
csvReader.TrimLeadingSpace = true
return csvReader
} | go | func LazyCSVReader(in io.Reader) CSVReader {
csvReader := csv.NewReader(in)
csvReader.LazyQuotes = true
csvReader.TrimLeadingSpace = true
return csvReader
} | [
"func",
"LazyCSVReader",
"(",
"in",
"io",
".",
"Reader",
")",
"CSVReader",
"{",
"csvReader",
":=",
"csv",
".",
"NewReader",
"(",
"in",
")",
"\n",
"csvReader",
".",
"LazyQuotes",
"=",
"true",
"\n",
"csvReader",
".",
"TrimLeadingSpace",
"=",
"true",
"\n",
... | // LazyCSVReader returns a lazy CSV reader, with LazyQuotes and TrimLeadingSpace. | [
"LazyCSVReader",
"returns",
"a",
"lazy",
"CSV",
"reader",
"with",
"LazyQuotes",
"and",
"TrimLeadingSpace",
"."
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L72-L77 | train |
gocarina/gocsv | csv.go | MarshalString | func MarshalString(in interface{}) (out string, err error) {
bufferString := bytes.NewBufferString(out)
if err := Marshal(in, bufferString); err != nil {
return "", err
}
return bufferString.String(), nil
} | go | func MarshalString(in interface{}) (out string, err error) {
bufferString := bytes.NewBufferString(out)
if err := Marshal(in, bufferString); err != nil {
return "", err
}
return bufferString.String(), nil
} | [
"func",
"MarshalString",
"(",
"in",
"interface",
"{",
"}",
")",
"(",
"out",
"string",
",",
"err",
"error",
")",
"{",
"bufferString",
":=",
"bytes",
".",
"NewBufferString",
"(",
"out",
")",
"\n",
"if",
"err",
":=",
"Marshal",
"(",
"in",
",",
"bufferStri... | // MarshalString returns the CSV string from the interface. | [
"MarshalString",
"returns",
"the",
"CSV",
"string",
"from",
"the",
"interface",
"."
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L97-L103 | train |
gocarina/gocsv | csv.go | MarshalBytes | func MarshalBytes(in interface{}) (out []byte, err error) {
bufferString := bytes.NewBuffer(out)
if err := Marshal(in, bufferString); err != nil {
return nil, err
}
return bufferString.Bytes(), nil
} | go | func MarshalBytes(in interface{}) (out []byte, err error) {
bufferString := bytes.NewBuffer(out)
if err := Marshal(in, bufferString); err != nil {
return nil, err
}
return bufferString.Bytes(), nil
} | [
"func",
"MarshalBytes",
"(",
"in",
"interface",
"{",
"}",
")",
"(",
"out",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"bufferString",
":=",
"bytes",
".",
"NewBuffer",
"(",
"out",
")",
"\n",
"if",
"err",
":=",
"Marshal",
"(",
"in",
",",
"buffe... | // MarshalBytes returns the CSV bytes from the interface. | [
"MarshalBytes",
"returns",
"the",
"CSV",
"bytes",
"from",
"the",
"interface",
"."
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L106-L112 | train |
gocarina/gocsv | csv.go | MarshalCSV | func MarshalCSV(in interface{}, out *SafeCSVWriter) (err error) {
return writeTo(out, in, false)
} | go | func MarshalCSV(in interface{}, out *SafeCSVWriter) (err error) {
return writeTo(out, in, false)
} | [
"func",
"MarshalCSV",
"(",
"in",
"interface",
"{",
"}",
",",
"out",
"*",
"SafeCSVWriter",
")",
"(",
"err",
"error",
")",
"{",
"return",
"writeTo",
"(",
"out",
",",
"in",
",",
"false",
")",
"\n",
"}"
] | // MarshalCSV returns the CSV in writer from the interface. | [
"MarshalCSV",
"returns",
"the",
"CSV",
"in",
"writer",
"from",
"the",
"interface",
"."
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L132-L134 | train |
gocarina/gocsv | csv.go | MarshalCSVWithoutHeaders | func MarshalCSVWithoutHeaders(in interface{}, out *SafeCSVWriter) (err error) {
return writeTo(out, in, true)
} | go | func MarshalCSVWithoutHeaders(in interface{}, out *SafeCSVWriter) (err error) {
return writeTo(out, in, true)
} | [
"func",
"MarshalCSVWithoutHeaders",
"(",
"in",
"interface",
"{",
"}",
",",
"out",
"*",
"SafeCSVWriter",
")",
"(",
"err",
"error",
")",
"{",
"return",
"writeTo",
"(",
"out",
",",
"in",
",",
"true",
")",
"\n",
"}"
] | // MarshalCSVWithoutHeaders returns the CSV in writer from the interface. | [
"MarshalCSVWithoutHeaders",
"returns",
"the",
"CSV",
"in",
"writer",
"from",
"the",
"interface",
"."
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L137-L139 | train |
gocarina/gocsv | csv.go | UnmarshalString | func UnmarshalString(in string, out interface{}) error {
return Unmarshal(strings.NewReader(in), out)
} | go | func UnmarshalString(in string, out interface{}) error {
return Unmarshal(strings.NewReader(in), out)
} | [
"func",
"UnmarshalString",
"(",
"in",
"string",
",",
"out",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"Unmarshal",
"(",
"strings",
".",
"NewReader",
"(",
"in",
")",
",",
"out",
")",
"\n",
"}"
] | // UnmarshalString parses the CSV from the string in the interface. | [
"UnmarshalString",
"parses",
"the",
"CSV",
"from",
"the",
"string",
"in",
"the",
"interface",
"."
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L150-L152 | train |
gocarina/gocsv | csv.go | UnmarshalBytes | func UnmarshalBytes(in []byte, out interface{}) error {
return Unmarshal(bytes.NewReader(in), out)
} | go | func UnmarshalBytes(in []byte, out interface{}) error {
return Unmarshal(bytes.NewReader(in), out)
} | [
"func",
"UnmarshalBytes",
"(",
"in",
"[",
"]",
"byte",
",",
"out",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"Unmarshal",
"(",
"bytes",
".",
"NewReader",
"(",
"in",
")",
",",
"out",
")",
"\n",
"}"
] | // UnmarshalBytes parses the CSV from the bytes in the interface. | [
"UnmarshalBytes",
"parses",
"the",
"CSV",
"from",
"the",
"bytes",
"in",
"the",
"interface",
"."
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L155-L157 | train |
gocarina/gocsv | csv.go | Unmarshal | func Unmarshal(in io.Reader, out interface{}) error {
return readTo(newDecoder(in), out)
} | go | func Unmarshal(in io.Reader, out interface{}) error {
return readTo(newDecoder(in), out)
} | [
"func",
"Unmarshal",
"(",
"in",
"io",
".",
"Reader",
",",
"out",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"readTo",
"(",
"newDecoder",
"(",
"in",
")",
",",
"out",
")",
"\n",
"}"
] | // Unmarshal parses the CSV from the reader in the interface. | [
"Unmarshal",
"parses",
"the",
"CSV",
"from",
"the",
"reader",
"in",
"the",
"interface",
"."
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L160-L162 | train |
gocarina/gocsv | csv.go | UnmarshalWithoutHeaders | func UnmarshalWithoutHeaders(in io.Reader, out interface{}) error {
return readToWithoutHeaders(newDecoder(in), out)
} | go | func UnmarshalWithoutHeaders(in io.Reader, out interface{}) error {
return readToWithoutHeaders(newDecoder(in), out)
} | [
"func",
"UnmarshalWithoutHeaders",
"(",
"in",
"io",
".",
"Reader",
",",
"out",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"readToWithoutHeaders",
"(",
"newDecoder",
"(",
"in",
")",
",",
"out",
")",
"\n",
"}"
] | // UnmarshalWithoutHeaders parses the CSV from the reader in the interface. | [
"UnmarshalWithoutHeaders",
"parses",
"the",
"CSV",
"from",
"the",
"reader",
"in",
"the",
"interface",
"."
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L165-L167 | train |
gocarina/gocsv | csv.go | UnmarshalToChan | func UnmarshalToChan(in io.Reader, c interface{}) error {
if c == nil {
return fmt.Errorf("goscv: channel is %v", c)
}
return readEach(newDecoder(in), c)
} | go | func UnmarshalToChan(in io.Reader, c interface{}) error {
if c == nil {
return fmt.Errorf("goscv: channel is %v", c)
}
return readEach(newDecoder(in), c)
} | [
"func",
"UnmarshalToChan",
"(",
"in",
"io",
".",
"Reader",
",",
"c",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"c",
")",
"\n",
"}",
"\n",
"return",
"readEach",
"("... | // UnmarshalToChan parses the CSV from the reader and send each value in the chan c.
// The channel must have a concrete type. | [
"UnmarshalToChan",
"parses",
"the",
"CSV",
"from",
"the",
"reader",
"and",
"send",
"each",
"value",
"in",
"the",
"chan",
"c",
".",
"The",
"channel",
"must",
"have",
"a",
"concrete",
"type",
"."
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L186-L191 | train |
gocarina/gocsv | csv.go | UnmarshalDecoderToChan | func UnmarshalDecoderToChan(in SimpleDecoder, c interface{}) error {
if c == nil {
return fmt.Errorf("goscv: channel is %v", c)
}
return readEach(in, c)
} | go | func UnmarshalDecoderToChan(in SimpleDecoder, c interface{}) error {
if c == nil {
return fmt.Errorf("goscv: channel is %v", c)
}
return readEach(in, c)
} | [
"func",
"UnmarshalDecoderToChan",
"(",
"in",
"SimpleDecoder",
",",
"c",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"c",
")",
"\n",
"}",
"\n",
"return",
"readEach",
"(",... | // UnmarshalDecoderToChan parses the CSV from the decoder and send each value in the chan c.
// The channel must have a concrete type. | [
"UnmarshalDecoderToChan",
"parses",
"the",
"CSV",
"from",
"the",
"decoder",
"and",
"send",
"each",
"value",
"in",
"the",
"chan",
"c",
".",
"The",
"channel",
"must",
"have",
"a",
"concrete",
"type",
"."
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L195-L200 | train |
gocarina/gocsv | csv.go | UnmarshalStringToChan | func UnmarshalStringToChan(in string, c interface{}) error {
return UnmarshalToChan(strings.NewReader(in), c)
} | go | func UnmarshalStringToChan(in string, c interface{}) error {
return UnmarshalToChan(strings.NewReader(in), c)
} | [
"func",
"UnmarshalStringToChan",
"(",
"in",
"string",
",",
"c",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"UnmarshalToChan",
"(",
"strings",
".",
"NewReader",
"(",
"in",
")",
",",
"c",
")",
"\n",
"}"
] | // UnmarshalStringToChan parses the CSV from the string and send each value in the chan c.
// The channel must have a concrete type. | [
"UnmarshalStringToChan",
"parses",
"the",
"CSV",
"from",
"the",
"string",
"and",
"send",
"each",
"value",
"in",
"the",
"chan",
"c",
".",
"The",
"channel",
"must",
"have",
"a",
"concrete",
"type",
"."
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L204-L206 | train |
gocarina/gocsv | csv.go | UnmarshalBytesToChan | func UnmarshalBytesToChan(in []byte, c interface{}) error {
return UnmarshalToChan(bytes.NewReader(in), c)
} | go | func UnmarshalBytesToChan(in []byte, c interface{}) error {
return UnmarshalToChan(bytes.NewReader(in), c)
} | [
"func",
"UnmarshalBytesToChan",
"(",
"in",
"[",
"]",
"byte",
",",
"c",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"UnmarshalToChan",
"(",
"bytes",
".",
"NewReader",
"(",
"in",
")",
",",
"c",
")",
"\n",
"}"
] | // UnmarshalBytesToChan parses the CSV from the bytes and send each value in the chan c.
// The channel must have a concrete type. | [
"UnmarshalBytesToChan",
"parses",
"the",
"CSV",
"from",
"the",
"bytes",
"and",
"send",
"each",
"value",
"in",
"the",
"chan",
"c",
".",
"The",
"channel",
"must",
"have",
"a",
"concrete",
"type",
"."
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L210-L212 | train |
gocarina/gocsv | csv.go | CSVToMap | func CSVToMap(in io.Reader) (map[string]string, error) {
decoder := newDecoder(in)
header, err := decoder.getCSVRow()
if err != nil {
return nil, err
}
if len(header) != 2 {
return nil, fmt.Errorf("maps can only be created for csv of two columns")
}
m := make(map[string]string)
for {
line, err := decoder.getCSVRow()
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
m[line[0]] = line[1]
}
return m, nil
} | go | func CSVToMap(in io.Reader) (map[string]string, error) {
decoder := newDecoder(in)
header, err := decoder.getCSVRow()
if err != nil {
return nil, err
}
if len(header) != 2 {
return nil, fmt.Errorf("maps can only be created for csv of two columns")
}
m := make(map[string]string)
for {
line, err := decoder.getCSVRow()
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
m[line[0]] = line[1]
}
return m, nil
} | [
"func",
"CSVToMap",
"(",
"in",
"io",
".",
"Reader",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"decoder",
":=",
"newDecoder",
"(",
"in",
")",
"\n",
"header",
",",
"err",
":=",
"decoder",
".",
"getCSVRow",
"(",
")",
"\n",... | // CSVToMap creates a simple map from a CSV of 2 columns. | [
"CSVToMap",
"creates",
"a",
"simple",
"map",
"from",
"a",
"CSV",
"of",
"2",
"columns",
"."
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L283-L303 | train |
gocarina/gocsv | csv.go | CSVToMaps | func CSVToMaps(reader io.Reader) ([]map[string]string, error) {
r := csv.NewReader(reader)
rows := []map[string]string{}
var header []string
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
if header == nil {
header = record
} else {
dict := map[string]string{}
for i := range header {
dict[header[i]] = record[i]
}
rows = append(rows, dict)
}
}
return rows, nil
} | go | func CSVToMaps(reader io.Reader) ([]map[string]string, error) {
r := csv.NewReader(reader)
rows := []map[string]string{}
var header []string
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
if header == nil {
header = record
} else {
dict := map[string]string{}
for i := range header {
dict[header[i]] = record[i]
}
rows = append(rows, dict)
}
}
return rows, nil
} | [
"func",
"CSVToMaps",
"(",
"reader",
"io",
".",
"Reader",
")",
"(",
"[",
"]",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"r",
":=",
"csv",
".",
"NewReader",
"(",
"reader",
")",
"\n",
"rows",
":=",
"[",
"]",
"map",
"[",
"string",
... | // CSVToMaps takes a reader and returns an array of dictionaries, using the header row as the keys | [
"CSVToMaps",
"takes",
"a",
"reader",
"and",
"returns",
"an",
"array",
"of",
"dictionaries",
"using",
"the",
"header",
"row",
"as",
"the",
"keys"
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L306-L329 | train |
gocarina/gocsv | encode.go | ensureInType | func ensureInType(outType reflect.Type) error {
switch outType.Kind() {
case reflect.Slice:
fallthrough
case reflect.Array:
return nil
}
return fmt.Errorf("cannot use " + outType.String() + ", only slice or array supported")
} | go | func ensureInType(outType reflect.Type) error {
switch outType.Kind() {
case reflect.Slice:
fallthrough
case reflect.Array:
return nil
}
return fmt.Errorf("cannot use " + outType.String() + ", only slice or array supported")
} | [
"func",
"ensureInType",
"(",
"outType",
"reflect",
".",
"Type",
")",
"error",
"{",
"switch",
"outType",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Slice",
":",
"fallthrough",
"\n",
"case",
"reflect",
".",
"Array",
":",
"return",
"nil",
"\n",
... | // Check if the inType is an array or a slice | [
"Check",
"if",
"the",
"inType",
"is",
"an",
"array",
"or",
"a",
"slice"
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/encode.go#L114-L122 | train |
gocarina/gocsv | decode.go | maybeDoubleHeaderNames | func maybeDoubleHeaderNames(headers []string) error {
headerMap := make(map[string]bool, len(headers))
for _, v := range headers {
if _, ok := headerMap[v]; ok {
return fmt.Errorf("Repeated header name: %v", v)
}
headerMap[v] = true
}
return nil
} | go | func maybeDoubleHeaderNames(headers []string) error {
headerMap := make(map[string]bool, len(headers))
for _, v := range headers {
if _, ok := headerMap[v]; ok {
return fmt.Errorf("Repeated header name: %v", v)
}
headerMap[v] = true
}
return nil
} | [
"func",
"maybeDoubleHeaderNames",
"(",
"headers",
"[",
"]",
"string",
")",
"error",
"{",
"headerMap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
",",
"len",
"(",
"headers",
")",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"headers",
"{... | // Check that no header name is repeated twice | [
"Check",
"that",
"no",
"header",
"name",
"is",
"repeated",
"twice"
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/decode.go#L114-L123 | train |
gocarina/gocsv | decode.go | ensureOutType | func ensureOutType(outType reflect.Type) error {
switch outType.Kind() {
case reflect.Slice:
fallthrough
case reflect.Chan:
fallthrough
case reflect.Array:
return nil
}
return fmt.Errorf("cannot use " + outType.String() + ", only slice or array supported")
} | go | func ensureOutType(outType reflect.Type) error {
switch outType.Kind() {
case reflect.Slice:
fallthrough
case reflect.Chan:
fallthrough
case reflect.Array:
return nil
}
return fmt.Errorf("cannot use " + outType.String() + ", only slice or array supported")
} | [
"func",
"ensureOutType",
"(",
"outType",
"reflect",
".",
"Type",
")",
"error",
"{",
"switch",
"outType",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Slice",
":",
"fallthrough",
"\n",
"case",
"reflect",
".",
"Chan",
":",
"fallthrough",
"\n",
"cas... | // Check if the outType is an array or a slice | [
"Check",
"if",
"the",
"outType",
"is",
"an",
"array",
"or",
"a",
"slice"
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/decode.go#L304-L314 | train |
gocarina/gocsv | decode.go | ensureOutInnerType | func ensureOutInnerType(outInnerType reflect.Type) error {
switch outInnerType.Kind() {
case reflect.Struct:
return nil
}
return fmt.Errorf("cannot use " + outInnerType.String() + ", only struct supported")
} | go | func ensureOutInnerType(outInnerType reflect.Type) error {
switch outInnerType.Kind() {
case reflect.Struct:
return nil
}
return fmt.Errorf("cannot use " + outInnerType.String() + ", only struct supported")
} | [
"func",
"ensureOutInnerType",
"(",
"outInnerType",
"reflect",
".",
"Type",
")",
"error",
"{",
"switch",
"outInnerType",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Struct",
":",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"... | // Check if the outInnerType is of type struct | [
"Check",
"if",
"the",
"outInnerType",
"is",
"of",
"type",
"struct"
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/decode.go#L317-L323 | train |
gocarina/gocsv | unmarshaller.go | NewUnmarshaller | func NewUnmarshaller(reader *csv.Reader, out interface{}) (*Unmarshaller, error) {
headers, err := reader.Read()
if err != nil {
return nil, err
}
um := &Unmarshaller{reader: reader, outType: reflect.TypeOf(out)}
err = validate(um, out, headers)
if err != nil {
return nil, err
}
return um, nil
} | go | func NewUnmarshaller(reader *csv.Reader, out interface{}) (*Unmarshaller, error) {
headers, err := reader.Read()
if err != nil {
return nil, err
}
um := &Unmarshaller{reader: reader, outType: reflect.TypeOf(out)}
err = validate(um, out, headers)
if err != nil {
return nil, err
}
return um, nil
} | [
"func",
"NewUnmarshaller",
"(",
"reader",
"*",
"csv",
".",
"Reader",
",",
"out",
"interface",
"{",
"}",
")",
"(",
"*",
"Unmarshaller",
",",
"error",
")",
"{",
"headers",
",",
"err",
":=",
"reader",
".",
"Read",
"(",
")",
"\n",
"if",
"err",
"!=",
"n... | // NewUnmarshaller creates an unmarshaller from a csv.Reader and a struct. | [
"NewUnmarshaller",
"creates",
"an",
"unmarshaller",
"from",
"a",
"csv",
".",
"Reader",
"and",
"a",
"struct",
"."
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/unmarshaller.go#L21-L33 | train |
gocarina/gocsv | unmarshaller.go | validate | func validate(um *Unmarshaller, s interface{}, headers []string) error {
concreteType := reflect.TypeOf(s)
if concreteType.Kind() == reflect.Ptr {
concreteType = concreteType.Elem()
}
if err := ensureOutInnerType(concreteType); err != nil {
return err
}
structInfo := getStructInfo(concreteType) // Get struct info to get CSV annotations.
if len(structInfo.Fields) == 0 {
return errors.New("no csv struct tags found")
}
csvHeaders := make(map[int]string) // Map of columm index to header name
csvHeadersLabels := make(map[int]*fieldInfo, len(structInfo.Fields)) // Used to store the corresponding header <-> position in CSV
headerCount := map[string]int{}
for i, csvColumnHeader := range headers {
csvHeaders[i] = csvColumnHeader
curHeaderCount := headerCount[csvColumnHeader]
if fieldInfo := getCSVFieldPosition(csvColumnHeader, structInfo, curHeaderCount); fieldInfo != nil {
csvHeadersLabels[i] = fieldInfo
if ShouldAlignDuplicateHeadersWithStructFieldOrder {
curHeaderCount++
headerCount[csvColumnHeader] = curHeaderCount
}
}
}
if err := maybeDoubleHeaderNames(headers); err != nil {
return err
}
um.headerMap = csvHeaders
um.fieldInfoMap = csvHeadersLabels
um.MismatchedHeaders = mismatchHeaderFields(structInfo.Fields, headers)
um.MismatchedStructFields = mismatchStructFields(structInfo.Fields, headers)
return nil
} | go | func validate(um *Unmarshaller, s interface{}, headers []string) error {
concreteType := reflect.TypeOf(s)
if concreteType.Kind() == reflect.Ptr {
concreteType = concreteType.Elem()
}
if err := ensureOutInnerType(concreteType); err != nil {
return err
}
structInfo := getStructInfo(concreteType) // Get struct info to get CSV annotations.
if len(structInfo.Fields) == 0 {
return errors.New("no csv struct tags found")
}
csvHeaders := make(map[int]string) // Map of columm index to header name
csvHeadersLabels := make(map[int]*fieldInfo, len(structInfo.Fields)) // Used to store the corresponding header <-> position in CSV
headerCount := map[string]int{}
for i, csvColumnHeader := range headers {
csvHeaders[i] = csvColumnHeader
curHeaderCount := headerCount[csvColumnHeader]
if fieldInfo := getCSVFieldPosition(csvColumnHeader, structInfo, curHeaderCount); fieldInfo != nil {
csvHeadersLabels[i] = fieldInfo
if ShouldAlignDuplicateHeadersWithStructFieldOrder {
curHeaderCount++
headerCount[csvColumnHeader] = curHeaderCount
}
}
}
if err := maybeDoubleHeaderNames(headers); err != nil {
return err
}
um.headerMap = csvHeaders
um.fieldInfoMap = csvHeadersLabels
um.MismatchedHeaders = mismatchHeaderFields(structInfo.Fields, headers)
um.MismatchedStructFields = mismatchStructFields(structInfo.Fields, headers)
return nil
} | [
"func",
"validate",
"(",
"um",
"*",
"Unmarshaller",
",",
"s",
"interface",
"{",
"}",
",",
"headers",
"[",
"]",
"string",
")",
"error",
"{",
"concreteType",
":=",
"reflect",
".",
"TypeOf",
"(",
"s",
")",
"\n",
"if",
"concreteType",
".",
"Kind",
"(",
"... | // validate ensures that a struct was used to create the Unmarshaller, and validates
// CSV headers against the CSV tags in the struct. | [
"validate",
"ensures",
"that",
"a",
"struct",
"was",
"used",
"to",
"create",
"the",
"Unmarshaller",
"and",
"validates",
"CSV",
"headers",
"against",
"the",
"CSV",
"tags",
"in",
"the",
"struct",
"."
] | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/unmarshaller.go#L58-L93 | train |
gocarina/gocsv | unmarshaller.go | unmarshalRow | func (um *Unmarshaller) unmarshalRow(row []string, unmatched map[string]string) (interface{}, error) {
isPointer := false
concreteOutType := um.outType
if um.outType.Kind() == reflect.Ptr {
isPointer = true
concreteOutType = concreteOutType.Elem()
}
outValue := createNewOutInner(isPointer, concreteOutType)
for j, csvColumnContent := range row {
if fieldInfo, ok := um.fieldInfoMap[j]; ok {
if err := setInnerField(&outValue, isPointer, fieldInfo.IndexChain, csvColumnContent, fieldInfo.omitEmpty); err != nil { // Set field of struct
return nil, fmt.Errorf("cannot assign field at %v to %s through index chain %v: %v", j, outValue.Type(), fieldInfo.IndexChain, err)
}
} else if unmatched != nil {
unmatched[um.headerMap[j]] = csvColumnContent
}
}
return outValue.Interface(), nil
} | go | func (um *Unmarshaller) unmarshalRow(row []string, unmatched map[string]string) (interface{}, error) {
isPointer := false
concreteOutType := um.outType
if um.outType.Kind() == reflect.Ptr {
isPointer = true
concreteOutType = concreteOutType.Elem()
}
outValue := createNewOutInner(isPointer, concreteOutType)
for j, csvColumnContent := range row {
if fieldInfo, ok := um.fieldInfoMap[j]; ok {
if err := setInnerField(&outValue, isPointer, fieldInfo.IndexChain, csvColumnContent, fieldInfo.omitEmpty); err != nil { // Set field of struct
return nil, fmt.Errorf("cannot assign field at %v to %s through index chain %v: %v", j, outValue.Type(), fieldInfo.IndexChain, err)
}
} else if unmatched != nil {
unmatched[um.headerMap[j]] = csvColumnContent
}
}
return outValue.Interface(), nil
} | [
"func",
"(",
"um",
"*",
"Unmarshaller",
")",
"unmarshalRow",
"(",
"row",
"[",
"]",
"string",
",",
"unmatched",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"isPointer",
":=",
"false",
"\n",
"concreteOutT... | // unmarshalRow converts a CSV row to a struct, based on CSV struct tags.
// If unmatched is non nil, it is populated with any columns that don't map to a struct field | [
"unmarshalRow",
"converts",
"a",
"CSV",
"row",
"to",
"a",
"struct",
"based",
"on",
"CSV",
"struct",
"tags",
".",
"If",
"unmatched",
"is",
"non",
"nil",
"it",
"is",
"populated",
"with",
"any",
"columns",
"that",
"don",
"t",
"map",
"to",
"a",
"struct",
"... | 2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724 | https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/unmarshaller.go#L97-L115 | train |
golang/leveldb | db/db.go | close | func (m *mergingIter) close(i int) error {
t := m.iters[i]
if t == nil {
return nil
}
err := t.Close()
if m.err == nil {
m.err = err
}
m.iters[i] = nil
m.keys[i] = nil
return err
} | go | func (m *mergingIter) close(i int) error {
t := m.iters[i]
if t == nil {
return nil
}
err := t.Close()
if m.err == nil {
m.err = err
}
m.iters[i] = nil
m.keys[i] = nil
return err
} | [
"func",
"(",
"m",
"*",
"mergingIter",
")",
"close",
"(",
"i",
"int",
")",
"error",
"{",
"t",
":=",
"m",
".",
"iters",
"[",
"i",
"]",
"\n",
"if",
"t",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"err",
":=",
"t",
".",
"Close",
"(",
"... | // close records that the i'th input iterator is done. | [
"close",
"records",
"that",
"the",
"i",
"th",
"input",
"iterator",
"is",
"done",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/db/db.go#L223-L235 | train |
golang/leveldb | compaction.go | pickCompaction | func pickCompaction(vs *versionSet) (c *compaction) {
cur := vs.currentVersion()
// Pick a compaction based on size. If none exist, pick one based on seeks.
if cur.compactionScore >= 1 {
c = &compaction{
version: cur,
level: cur.compactionLevel,
}
// TODO: Pick the first file that comes after the compaction pointer for c.level.
c.inputs[0] = []fileMetadata{cur.files[c.level][0]}
} else if false {
// TODO: look for a compaction triggered by seeks.
} else {
return nil
}
// Files in level 0 may overlap each other, so pick up all overlapping ones.
if c.level == 0 {
smallest, largest := ikeyRange(vs.icmp, c.inputs[0], nil)
c.inputs[0] = cur.overlaps(0, vs.ucmp, smallest.ukey(), largest.ukey())
if len(c.inputs) == 0 {
panic("leveldb: empty compaction")
}
}
c.setupOtherInputs(vs)
return c
} | go | func pickCompaction(vs *versionSet) (c *compaction) {
cur := vs.currentVersion()
// Pick a compaction based on size. If none exist, pick one based on seeks.
if cur.compactionScore >= 1 {
c = &compaction{
version: cur,
level: cur.compactionLevel,
}
// TODO: Pick the first file that comes after the compaction pointer for c.level.
c.inputs[0] = []fileMetadata{cur.files[c.level][0]}
} else if false {
// TODO: look for a compaction triggered by seeks.
} else {
return nil
}
// Files in level 0 may overlap each other, so pick up all overlapping ones.
if c.level == 0 {
smallest, largest := ikeyRange(vs.icmp, c.inputs[0], nil)
c.inputs[0] = cur.overlaps(0, vs.ucmp, smallest.ukey(), largest.ukey())
if len(c.inputs) == 0 {
panic("leveldb: empty compaction")
}
}
c.setupOtherInputs(vs)
return c
} | [
"func",
"pickCompaction",
"(",
"vs",
"*",
"versionSet",
")",
"(",
"c",
"*",
"compaction",
")",
"{",
"cur",
":=",
"vs",
".",
"currentVersion",
"(",
")",
"\n\n",
"// Pick a compaction based on size. If none exist, pick one based on seeks.",
"if",
"cur",
".",
"compacti... | // pickCompaction picks the best compaction, if any, for vs' current version. | [
"pickCompaction",
"picks",
"the",
"best",
"compaction",
"if",
"any",
"for",
"vs",
"current",
"version",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/compaction.go#L43-L73 | train |
golang/leveldb | compaction.go | grow | func (c *compaction) grow(vs *versionSet, sm, la internalKey) bool {
if len(c.inputs[1]) == 0 {
return false
}
grow0 := c.version.overlaps(c.level, vs.ucmp, sm.ukey(), la.ukey())
if len(grow0) <= len(c.inputs[0]) {
return false
}
if totalSize(grow0)+totalSize(c.inputs[1]) >= expandedCompactionByteSizeLimit {
return false
}
sm1, la1 := ikeyRange(vs.icmp, grow0, nil)
grow1 := c.version.overlaps(c.level+1, vs.ucmp, sm1, la1)
if len(grow1) != len(c.inputs[1]) {
return false
}
c.inputs[0] = grow0
c.inputs[1] = grow1
return true
} | go | func (c *compaction) grow(vs *versionSet, sm, la internalKey) bool {
if len(c.inputs[1]) == 0 {
return false
}
grow0 := c.version.overlaps(c.level, vs.ucmp, sm.ukey(), la.ukey())
if len(grow0) <= len(c.inputs[0]) {
return false
}
if totalSize(grow0)+totalSize(c.inputs[1]) >= expandedCompactionByteSizeLimit {
return false
}
sm1, la1 := ikeyRange(vs.icmp, grow0, nil)
grow1 := c.version.overlaps(c.level+1, vs.ucmp, sm1, la1)
if len(grow1) != len(c.inputs[1]) {
return false
}
c.inputs[0] = grow0
c.inputs[1] = grow1
return true
} | [
"func",
"(",
"c",
"*",
"compaction",
")",
"grow",
"(",
"vs",
"*",
"versionSet",
",",
"sm",
",",
"la",
"internalKey",
")",
"bool",
"{",
"if",
"len",
"(",
"c",
".",
"inputs",
"[",
"1",
"]",
")",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",... | // grow grows the number of inputs at c.level without changing the number of
// c.level+1 files in the compaction, and returns whether the inputs grew. sm
// and la are the smallest and largest internalKeys in all of the inputs. | [
"grow",
"grows",
"the",
"number",
"of",
"inputs",
"at",
"c",
".",
"level",
"without",
"changing",
"the",
"number",
"of",
"c",
".",
"level",
"+",
"1",
"files",
"in",
"the",
"compaction",
"and",
"returns",
"whether",
"the",
"inputs",
"grew",
".",
"sm",
"... | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/compaction.go#L100-L119 | train |
golang/leveldb | compaction.go | maybeScheduleCompaction | func (d *DB) maybeScheduleCompaction() {
if d.compacting || d.closed {
return
}
// TODO: check for manual compactions.
if d.imm == nil {
v := d.versions.currentVersion()
// TODO: check v.fileToCompact.
if v.compactionScore < 1 {
// There is no work to be done.
return
}
}
d.compacting = true
go d.compact()
} | go | func (d *DB) maybeScheduleCompaction() {
if d.compacting || d.closed {
return
}
// TODO: check for manual compactions.
if d.imm == nil {
v := d.versions.currentVersion()
// TODO: check v.fileToCompact.
if v.compactionScore < 1 {
// There is no work to be done.
return
}
}
d.compacting = true
go d.compact()
} | [
"func",
"(",
"d",
"*",
"DB",
")",
"maybeScheduleCompaction",
"(",
")",
"{",
"if",
"d",
".",
"compacting",
"||",
"d",
".",
"closed",
"{",
"return",
"\n",
"}",
"\n",
"// TODO: check for manual compactions.",
"if",
"d",
".",
"imm",
"==",
"nil",
"{",
"v",
... | // maybeScheduleCompaction schedules a compaction if necessary.
//
// d.mu must be held when calling this. | [
"maybeScheduleCompaction",
"schedules",
"a",
"compaction",
"if",
"necessary",
".",
"d",
".",
"mu",
"must",
"be",
"held",
"when",
"calling",
"this",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/compaction.go#L144-L159 | train |
golang/leveldb | compaction.go | compact | func (d *DB) compact() {
d.mu.Lock()
defer d.mu.Unlock()
if err := d.compact1(); err != nil {
// TODO: count consecutive compaction errors and backoff.
}
d.compacting = false
// The previous compaction may have produced too many files in a
// level, so reschedule another compaction if needed.
d.maybeScheduleCompaction()
d.compactionCond.Broadcast()
} | go | func (d *DB) compact() {
d.mu.Lock()
defer d.mu.Unlock()
if err := d.compact1(); err != nil {
// TODO: count consecutive compaction errors and backoff.
}
d.compacting = false
// The previous compaction may have produced too many files in a
// level, so reschedule another compaction if needed.
d.maybeScheduleCompaction()
d.compactionCond.Broadcast()
} | [
"func",
"(",
"d",
"*",
"DB",
")",
"compact",
"(",
")",
"{",
"d",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"d",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"err",
":=",
"d",
".",
"compact1",
"(",
")",
";",
"err",
"!=",
"nil",
"... | // compact runs one compaction and maybe schedules another call to compact. | [
"compact",
"runs",
"one",
"compaction",
"and",
"maybe",
"schedules",
"another",
"call",
"to",
"compact",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/compaction.go#L162-L173 | train |
golang/leveldb | compaction.go | compact1 | func (d *DB) compact1() error {
if d.imm != nil {
return d.compactMemTable()
}
// TODO: support manual compactions.
c := pickCompaction(&d.versions)
if c == nil {
return nil
}
// Check for a trivial move of one table from one level to the next.
// We avoid such a move if there is lots of overlapping grandparent data.
// Otherwise, the move could create a parent file that will require
// a very expensive merge later on.
if len(c.inputs[0]) == 1 && len(c.inputs[1]) == 0 &&
totalSize(c.inputs[2]) <= maxGrandparentOverlapBytes {
meta := &c.inputs[0][0]
return d.versions.logAndApply(d.dirname, &versionEdit{
deletedFiles: map[deletedFileEntry]bool{
deletedFileEntry{level: c.level, fileNum: meta.fileNum}: true,
},
newFiles: []newFileEntry{
{level: c.level + 1, meta: *meta},
},
})
}
ve, pendingOutputs, err := d.compactDiskTables(c)
if err != nil {
return err
}
err = d.versions.logAndApply(d.dirname, ve)
for _, fileNum := range pendingOutputs {
delete(d.pendingOutputs, fileNum)
}
if err != nil {
return err
}
d.deleteObsoleteFiles()
return nil
} | go | func (d *DB) compact1() error {
if d.imm != nil {
return d.compactMemTable()
}
// TODO: support manual compactions.
c := pickCompaction(&d.versions)
if c == nil {
return nil
}
// Check for a trivial move of one table from one level to the next.
// We avoid such a move if there is lots of overlapping grandparent data.
// Otherwise, the move could create a parent file that will require
// a very expensive merge later on.
if len(c.inputs[0]) == 1 && len(c.inputs[1]) == 0 &&
totalSize(c.inputs[2]) <= maxGrandparentOverlapBytes {
meta := &c.inputs[0][0]
return d.versions.logAndApply(d.dirname, &versionEdit{
deletedFiles: map[deletedFileEntry]bool{
deletedFileEntry{level: c.level, fileNum: meta.fileNum}: true,
},
newFiles: []newFileEntry{
{level: c.level + 1, meta: *meta},
},
})
}
ve, pendingOutputs, err := d.compactDiskTables(c)
if err != nil {
return err
}
err = d.versions.logAndApply(d.dirname, ve)
for _, fileNum := range pendingOutputs {
delete(d.pendingOutputs, fileNum)
}
if err != nil {
return err
}
d.deleteObsoleteFiles()
return nil
} | [
"func",
"(",
"d",
"*",
"DB",
")",
"compact1",
"(",
")",
"error",
"{",
"if",
"d",
".",
"imm",
"!=",
"nil",
"{",
"return",
"d",
".",
"compactMemTable",
"(",
")",
"\n",
"}",
"\n\n",
"// TODO: support manual compactions.",
"c",
":=",
"pickCompaction",
"(",
... | // compact1 runs one compaction.
//
// d.mu must be held when calling this, but the mutex may be dropped and
// re-acquired during the course of this method. | [
"compact1",
"runs",
"one",
"compaction",
".",
"d",
".",
"mu",
"must",
"be",
"held",
"when",
"calling",
"this",
"but",
"the",
"mutex",
"may",
"be",
"dropped",
"and",
"re",
"-",
"acquired",
"during",
"the",
"course",
"of",
"this",
"method",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/compaction.go#L179-L222 | train |
golang/leveldb | compaction.go | compactMemTable | func (d *DB) compactMemTable() error {
meta, err := d.writeLevel0Table(d.opts.GetFileSystem(), d.imm)
if err != nil {
return err
}
err = d.versions.logAndApply(d.dirname, &versionEdit{
logNumber: d.logNumber,
newFiles: []newFileEntry{
{level: 0, meta: meta},
},
})
delete(d.pendingOutputs, meta.fileNum)
if err != nil {
return err
}
d.imm = nil
d.deleteObsoleteFiles()
return nil
} | go | func (d *DB) compactMemTable() error {
meta, err := d.writeLevel0Table(d.opts.GetFileSystem(), d.imm)
if err != nil {
return err
}
err = d.versions.logAndApply(d.dirname, &versionEdit{
logNumber: d.logNumber,
newFiles: []newFileEntry{
{level: 0, meta: meta},
},
})
delete(d.pendingOutputs, meta.fileNum)
if err != nil {
return err
}
d.imm = nil
d.deleteObsoleteFiles()
return nil
} | [
"func",
"(",
"d",
"*",
"DB",
")",
"compactMemTable",
"(",
")",
"error",
"{",
"meta",
",",
"err",
":=",
"d",
".",
"writeLevel0Table",
"(",
"d",
".",
"opts",
".",
"GetFileSystem",
"(",
")",
",",
"d",
".",
"imm",
")",
"\n",
"if",
"err",
"!=",
"nil",... | // compactMemTable runs a compaction that copies d.imm from memory to disk.
//
// d.mu must be held when calling this, but the mutex may be dropped and
// re-acquired during the course of this method. | [
"compactMemTable",
"runs",
"a",
"compaction",
"that",
"copies",
"d",
".",
"imm",
"from",
"memory",
"to",
"disk",
".",
"d",
".",
"mu",
"must",
"be",
"held",
"when",
"calling",
"this",
"but",
"the",
"mutex",
"may",
"be",
"dropped",
"and",
"re",
"-",
"acq... | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/compaction.go#L228-L246 | train |
golang/leveldb | compaction.go | compactionIterator | func compactionIterator(tc *tableCache, icmp db.Comparer, c *compaction) (cIter db.Iterator, retErr error) {
iters := make([]db.Iterator, 0, len(c.inputs[0])+1)
defer func() {
if retErr != nil {
for _, iter := range iters {
if iter != nil {
iter.Close()
}
}
}
}()
if c.level != 0 {
iter, err := newConcatenatingIterator(tc, c.inputs[0])
if err != nil {
return nil, err
}
iters = append(iters, iter)
} else {
for _, f := range c.inputs[0] {
iter, err := tc.find(f.fileNum, nil)
if err != nil {
return nil, fmt.Errorf("leveldb: could not open table %d: %v", f.fileNum, err)
}
iters = append(iters, iter)
}
}
iter, err := newConcatenatingIterator(tc, c.inputs[1])
if err != nil {
return nil, err
}
iters = append(iters, iter)
return db.NewMergingIterator(icmp, iters...), nil
} | go | func compactionIterator(tc *tableCache, icmp db.Comparer, c *compaction) (cIter db.Iterator, retErr error) {
iters := make([]db.Iterator, 0, len(c.inputs[0])+1)
defer func() {
if retErr != nil {
for _, iter := range iters {
if iter != nil {
iter.Close()
}
}
}
}()
if c.level != 0 {
iter, err := newConcatenatingIterator(tc, c.inputs[0])
if err != nil {
return nil, err
}
iters = append(iters, iter)
} else {
for _, f := range c.inputs[0] {
iter, err := tc.find(f.fileNum, nil)
if err != nil {
return nil, fmt.Errorf("leveldb: could not open table %d: %v", f.fileNum, err)
}
iters = append(iters, iter)
}
}
iter, err := newConcatenatingIterator(tc, c.inputs[1])
if err != nil {
return nil, err
}
iters = append(iters, iter)
return db.NewMergingIterator(icmp, iters...), nil
} | [
"func",
"compactionIterator",
"(",
"tc",
"*",
"tableCache",
",",
"icmp",
"db",
".",
"Comparer",
",",
"c",
"*",
"compaction",
")",
"(",
"cIter",
"db",
".",
"Iterator",
",",
"retErr",
"error",
")",
"{",
"iters",
":=",
"make",
"(",
"[",
"]",
"db",
".",
... | // compactionIterator returns an iterator over all the tables in a compaction. | [
"compactionIterator",
"returns",
"an",
"iterator",
"over",
"all",
"the",
"tables",
"in",
"a",
"compaction",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/compaction.go#L393-L427 | train |
golang/leveldb | compaction.go | newConcatenatingIterator | func newConcatenatingIterator(tc *tableCache, inputs []fileMetadata) (cIter db.Iterator, retErr error) {
iters := make([]db.Iterator, len(inputs))
defer func() {
if retErr != nil {
for _, iter := range iters {
if iter != nil {
iter.Close()
}
}
}
}()
for i, f := range inputs {
iter, err := tc.find(f.fileNum, nil)
if err != nil {
return nil, fmt.Errorf("leveldb: could not open table %d: %v", f.fileNum, err)
}
iters[i] = iter
}
return db.NewConcatenatingIterator(iters...), nil
} | go | func newConcatenatingIterator(tc *tableCache, inputs []fileMetadata) (cIter db.Iterator, retErr error) {
iters := make([]db.Iterator, len(inputs))
defer func() {
if retErr != nil {
for _, iter := range iters {
if iter != nil {
iter.Close()
}
}
}
}()
for i, f := range inputs {
iter, err := tc.find(f.fileNum, nil)
if err != nil {
return nil, fmt.Errorf("leveldb: could not open table %d: %v", f.fileNum, err)
}
iters[i] = iter
}
return db.NewConcatenatingIterator(iters...), nil
} | [
"func",
"newConcatenatingIterator",
"(",
"tc",
"*",
"tableCache",
",",
"inputs",
"[",
"]",
"fileMetadata",
")",
"(",
"cIter",
"db",
".",
"Iterator",
",",
"retErr",
"error",
")",
"{",
"iters",
":=",
"make",
"(",
"[",
"]",
"db",
".",
"Iterator",
",",
"le... | // newConcatenatingIterator returns a concatenating iterator over all of the
// input tables. | [
"newConcatenatingIterator",
"returns",
"a",
"concatenating",
"iterator",
"over",
"all",
"of",
"the",
"input",
"tables",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/compaction.go#L431-L451 | train |
golang/leveldb | table/reader.go | Set | func (r *Reader) Set(key, value []byte, o *db.WriteOptions) error {
return errors.New("leveldb/table: cannot Set into a read-only table")
} | go | func (r *Reader) Set(key, value []byte, o *db.WriteOptions) error {
return errors.New("leveldb/table: cannot Set into a read-only table")
} | [
"func",
"(",
"r",
"*",
"Reader",
")",
"Set",
"(",
"key",
",",
"value",
"[",
"]",
"byte",
",",
"o",
"*",
"db",
".",
"WriteOptions",
")",
"error",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // Set is provided to implement the DB interface, but returns an error, as a
// Reader cannot write to a table. | [
"Set",
"is",
"provided",
"to",
"implement",
"the",
"DB",
"interface",
"but",
"returns",
"an",
"error",
"as",
"a",
"Reader",
"cannot",
"write",
"to",
"a",
"table",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/table/reader.go#L350-L352 | train |
golang/leveldb | table/reader.go | Delete | func (r *Reader) Delete(key []byte, o *db.WriteOptions) error {
return errors.New("leveldb/table: cannot Delete from a read-only table")
} | go | func (r *Reader) Delete(key []byte, o *db.WriteOptions) error {
return errors.New("leveldb/table: cannot Delete from a read-only table")
} | [
"func",
"(",
"r",
"*",
"Reader",
")",
"Delete",
"(",
"key",
"[",
"]",
"byte",
",",
"o",
"*",
"db",
".",
"WriteOptions",
")",
"error",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // Delete is provided to implement the DB interface, but returns an error, as a
// Reader cannot write to a table. | [
"Delete",
"is",
"provided",
"to",
"implement",
"the",
"DB",
"interface",
"but",
"returns",
"an",
"error",
"as",
"a",
"Reader",
"cannot",
"write",
"to",
"a",
"table",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/table/reader.go#L356-L358 | train |
golang/leveldb | table/reader.go | readBlock | func (r *Reader) readBlock(bh blockHandle) (block, error) {
b := make([]byte, bh.length+blockTrailerLen)
if _, err := r.file.ReadAt(b, int64(bh.offset)); err != nil {
return nil, err
}
if r.verifyChecksums {
checksum0 := binary.LittleEndian.Uint32(b[bh.length+1:])
checksum1 := crc.New(b[:bh.length+1]).Value()
if checksum0 != checksum1 {
return nil, errors.New("leveldb/table: invalid table (checksum mismatch)")
}
}
switch b[bh.length] {
case noCompressionBlockType:
return b[:bh.length], nil
case snappyCompressionBlockType:
b, err := snappy.Decode(nil, b[:bh.length])
if err != nil {
return nil, err
}
return b, nil
}
return nil, fmt.Errorf("leveldb/table: unknown block compression: %d", b[bh.length])
} | go | func (r *Reader) readBlock(bh blockHandle) (block, error) {
b := make([]byte, bh.length+blockTrailerLen)
if _, err := r.file.ReadAt(b, int64(bh.offset)); err != nil {
return nil, err
}
if r.verifyChecksums {
checksum0 := binary.LittleEndian.Uint32(b[bh.length+1:])
checksum1 := crc.New(b[:bh.length+1]).Value()
if checksum0 != checksum1 {
return nil, errors.New("leveldb/table: invalid table (checksum mismatch)")
}
}
switch b[bh.length] {
case noCompressionBlockType:
return b[:bh.length], nil
case snappyCompressionBlockType:
b, err := snappy.Decode(nil, b[:bh.length])
if err != nil {
return nil, err
}
return b, nil
}
return nil, fmt.Errorf("leveldb/table: unknown block compression: %d", b[bh.length])
} | [
"func",
"(",
"r",
"*",
"Reader",
")",
"readBlock",
"(",
"bh",
"blockHandle",
")",
"(",
"block",
",",
"error",
")",
"{",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"bh",
".",
"length",
"+",
"blockTrailerLen",
")",
"\n",
"if",
"_",
",",
"err",
... | // readBlock reads and decompresses a block from disk into memory. | [
"readBlock",
"reads",
"and",
"decompresses",
"a",
"block",
"from",
"disk",
"into",
"memory",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/table/reader.go#L382-L405 | train |
golang/leveldb | table/reader.go | NewReader | func NewReader(f db.File, o *db.Options) *Reader {
r := &Reader{
file: f,
comparer: o.GetComparer(),
verifyChecksums: o.GetVerifyChecksums(),
}
if f == nil {
r.err = errors.New("leveldb/table: nil file")
return r
}
stat, err := f.Stat()
if err != nil {
r.err = fmt.Errorf("leveldb/table: invalid table (could not stat file): %v", err)
return r
}
var footer [footerLen]byte
if stat.Size() < int64(len(footer)) {
r.err = errors.New("leveldb/table: invalid table (file size is too small)")
return r
}
_, err = f.ReadAt(footer[:], stat.Size()-int64(len(footer)))
if err != nil && err != io.EOF {
r.err = fmt.Errorf("leveldb/table: invalid table (could not read footer): %v", err)
return r
}
if string(footer[footerLen-len(magic):footerLen]) != magic {
r.err = errors.New("leveldb/table: invalid table (bad magic number)")
return r
}
// Read the metaindex.
metaindexBH, n := decodeBlockHandle(footer[:])
if n == 0 {
r.err = errors.New("leveldb/table: invalid table (bad metaindex block handle)")
return r
}
if err := r.readMetaindex(metaindexBH, o); err != nil {
r.err = err
return r
}
// Read the index into memory.
indexBH, n := decodeBlockHandle(footer[n:])
if n == 0 {
r.err = errors.New("leveldb/table: invalid table (bad index block handle)")
return r
}
r.index, r.err = r.readBlock(indexBH)
return r
} | go | func NewReader(f db.File, o *db.Options) *Reader {
r := &Reader{
file: f,
comparer: o.GetComparer(),
verifyChecksums: o.GetVerifyChecksums(),
}
if f == nil {
r.err = errors.New("leveldb/table: nil file")
return r
}
stat, err := f.Stat()
if err != nil {
r.err = fmt.Errorf("leveldb/table: invalid table (could not stat file): %v", err)
return r
}
var footer [footerLen]byte
if stat.Size() < int64(len(footer)) {
r.err = errors.New("leveldb/table: invalid table (file size is too small)")
return r
}
_, err = f.ReadAt(footer[:], stat.Size()-int64(len(footer)))
if err != nil && err != io.EOF {
r.err = fmt.Errorf("leveldb/table: invalid table (could not read footer): %v", err)
return r
}
if string(footer[footerLen-len(magic):footerLen]) != magic {
r.err = errors.New("leveldb/table: invalid table (bad magic number)")
return r
}
// Read the metaindex.
metaindexBH, n := decodeBlockHandle(footer[:])
if n == 0 {
r.err = errors.New("leveldb/table: invalid table (bad metaindex block handle)")
return r
}
if err := r.readMetaindex(metaindexBH, o); err != nil {
r.err = err
return r
}
// Read the index into memory.
indexBH, n := decodeBlockHandle(footer[n:])
if n == 0 {
r.err = errors.New("leveldb/table: invalid table (bad index block handle)")
return r
}
r.index, r.err = r.readBlock(indexBH)
return r
} | [
"func",
"NewReader",
"(",
"f",
"db",
".",
"File",
",",
"o",
"*",
"db",
".",
"Options",
")",
"*",
"Reader",
"{",
"r",
":=",
"&",
"Reader",
"{",
"file",
":",
"f",
",",
"comparer",
":",
"o",
".",
"GetComparer",
"(",
")",
",",
"verifyChecksums",
":",... | // NewReader returns a new table reader for the file. Closing the reader will
// close the file. | [
"NewReader",
"returns",
"a",
"new",
"table",
"reader",
"for",
"the",
"file",
".",
"Closing",
"the",
"reader",
"will",
"close",
"the",
"file",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/table/reader.go#L457-L506 | train |
golang/leveldb | bloom/bloom.go | MayContain | func (f Filter) MayContain(key []byte) bool {
if len(f) < 2 {
return false
}
k := f[len(f)-1]
if k > 30 {
// This is reserved for potentially new encodings for short Bloom filters.
// Consider it a match.
return true
}
nBits := uint32(8 * (len(f) - 1))
h := hash(key)
delta := h>>17 | h<<15
for j := uint8(0); j < k; j++ {
bitPos := h % nBits
if f[bitPos/8]&(1<<(bitPos%8)) == 0 {
return false
}
h += delta
}
return true
} | go | func (f Filter) MayContain(key []byte) bool {
if len(f) < 2 {
return false
}
k := f[len(f)-1]
if k > 30 {
// This is reserved for potentially new encodings for short Bloom filters.
// Consider it a match.
return true
}
nBits := uint32(8 * (len(f) - 1))
h := hash(key)
delta := h>>17 | h<<15
for j := uint8(0); j < k; j++ {
bitPos := h % nBits
if f[bitPos/8]&(1<<(bitPos%8)) == 0 {
return false
}
h += delta
}
return true
} | [
"func",
"(",
"f",
"Filter",
")",
"MayContain",
"(",
"key",
"[",
"]",
"byte",
")",
"bool",
"{",
"if",
"len",
"(",
"f",
")",
"<",
"2",
"{",
"return",
"false",
"\n",
"}",
"\n",
"k",
":=",
"f",
"[",
"len",
"(",
"f",
")",
"-",
"1",
"]",
"\n",
... | // MayContain returns whether the filter may contain given key. False positives
// are possible, where it returns true for keys not in the original set. | [
"MayContain",
"returns",
"whether",
"the",
"filter",
"may",
"contain",
"given",
"key",
".",
"False",
"positives",
"are",
"possible",
"where",
"it",
"returns",
"true",
"for",
"keys",
"not",
"in",
"the",
"original",
"set",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/bloom/bloom.go#L13-L34 | train |
golang/leveldb | bloom/bloom.go | hash | func hash(b []byte) uint32 {
const (
seed = 0xbc9f1d34
m = 0xc6a4a793
)
h := uint32(seed) ^ uint32(len(b)*m)
for ; len(b) >= 4; b = b[4:] {
h += uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
h *= m
h ^= h >> 16
}
switch len(b) {
case 3:
h += uint32(b[2]) << 16
fallthrough
case 2:
h += uint32(b[1]) << 8
fallthrough
case 1:
h += uint32(b[0])
h *= m
h ^= h >> 24
}
return h
} | go | func hash(b []byte) uint32 {
const (
seed = 0xbc9f1d34
m = 0xc6a4a793
)
h := uint32(seed) ^ uint32(len(b)*m)
for ; len(b) >= 4; b = b[4:] {
h += uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
h *= m
h ^= h >> 16
}
switch len(b) {
case 3:
h += uint32(b[2]) << 16
fallthrough
case 2:
h += uint32(b[1]) << 8
fallthrough
case 1:
h += uint32(b[0])
h *= m
h ^= h >> 24
}
return h
} | [
"func",
"hash",
"(",
"b",
"[",
"]",
"byte",
")",
"uint32",
"{",
"const",
"(",
"seed",
"=",
"0xbc9f1d34",
"\n",
"m",
"=",
"0xc6a4a793",
"\n",
")",
"\n",
"h",
":=",
"uint32",
"(",
"seed",
")",
"^",
"uint32",
"(",
"len",
"(",
"b",
")",
"*",
"m",
... | // hash implements a hashing algorithm similar to the Murmur hash. | [
"hash",
"implements",
"a",
"hashing",
"algorithm",
"similar",
"to",
"the",
"Murmur",
"hash",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/bloom/bloom.go#L106-L130 | train |
golang/leveldb | bloom/bloom.go | AppendFilter | func (p FilterPolicy) AppendFilter(dst []byte, keys [][]byte) []byte {
return appendFilter(dst, keys, int(p))
} | go | func (p FilterPolicy) AppendFilter(dst []byte, keys [][]byte) []byte {
return appendFilter(dst, keys, int(p))
} | [
"func",
"(",
"p",
"FilterPolicy",
")",
"AppendFilter",
"(",
"dst",
"[",
"]",
"byte",
",",
"keys",
"[",
"]",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"return",
"appendFilter",
"(",
"dst",
",",
"keys",
",",
"int",
"(",
"p",
")",
")",
"\n",
"... | // AppendFilter implements the db.FilterPolicy interface. | [
"AppendFilter",
"implements",
"the",
"db",
".",
"FilterPolicy",
"interface",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/bloom/bloom.go#L151-L153 | train |
golang/leveldb | bloom/bloom.go | MayContain | func (p FilterPolicy) MayContain(filter, key []byte) bool {
return Filter(filter).MayContain(key)
} | go | func (p FilterPolicy) MayContain(filter, key []byte) bool {
return Filter(filter).MayContain(key)
} | [
"func",
"(",
"p",
"FilterPolicy",
")",
"MayContain",
"(",
"filter",
",",
"key",
"[",
"]",
"byte",
")",
"bool",
"{",
"return",
"Filter",
"(",
"filter",
")",
".",
"MayContain",
"(",
"key",
")",
"\n",
"}"
] | // MayContain implements the db.FilterPolicy interface. | [
"MayContain",
"implements",
"the",
"db",
".",
"FilterPolicy",
"interface",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/bloom/bloom.go#L156-L158 | train |
golang/leveldb | table_cache.go | releaseNode | func (c *tableCache) releaseNode(n *tableCacheNode) {
delete(c.nodes, n.fileNum)
n.next.prev = n.prev
n.prev.next = n.next
n.refCount--
if n.refCount == 0 {
go n.release()
}
} | go | func (c *tableCache) releaseNode(n *tableCacheNode) {
delete(c.nodes, n.fileNum)
n.next.prev = n.prev
n.prev.next = n.next
n.refCount--
if n.refCount == 0 {
go n.release()
}
} | [
"func",
"(",
"c",
"*",
"tableCache",
")",
"releaseNode",
"(",
"n",
"*",
"tableCacheNode",
")",
"{",
"delete",
"(",
"c",
".",
"nodes",
",",
"n",
".",
"fileNum",
")",
"\n",
"n",
".",
"next",
".",
"prev",
"=",
"n",
".",
"prev",
"\n",
"n",
".",
"pr... | // releaseNode releases a node from the tableCache.
//
// c.mu must be held when calling this. | [
"releaseNode",
"releases",
"a",
"node",
"from",
"the",
"tableCache",
".",
"c",
".",
"mu",
"must",
"be",
"held",
"when",
"calling",
"this",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/table_cache.go#L66-L74 | train |
golang/leveldb | table_cache.go | findNode | func (c *tableCache) findNode(fileNum uint64) *tableCacheNode {
c.mu.Lock()
defer c.mu.Unlock()
n := c.nodes[fileNum]
if n == nil {
n = &tableCacheNode{
fileNum: fileNum,
refCount: 1,
result: make(chan tableReaderOrError, 1),
}
c.nodes[fileNum] = n
if len(c.nodes) > c.size {
// Release the tail node.
c.releaseNode(c.dummy.prev)
}
go n.load(c)
} else {
// Remove n from the doubly-linked list.
n.next.prev = n.prev
n.prev.next = n.next
}
// Insert n at the front of the doubly-linked list.
n.next = c.dummy.next
n.prev = &c.dummy
n.next.prev = n
n.prev.next = n
// The caller is responsible for decrementing the refCount.
n.refCount++
return n
} | go | func (c *tableCache) findNode(fileNum uint64) *tableCacheNode {
c.mu.Lock()
defer c.mu.Unlock()
n := c.nodes[fileNum]
if n == nil {
n = &tableCacheNode{
fileNum: fileNum,
refCount: 1,
result: make(chan tableReaderOrError, 1),
}
c.nodes[fileNum] = n
if len(c.nodes) > c.size {
// Release the tail node.
c.releaseNode(c.dummy.prev)
}
go n.load(c)
} else {
// Remove n from the doubly-linked list.
n.next.prev = n.prev
n.prev.next = n.next
}
// Insert n at the front of the doubly-linked list.
n.next = c.dummy.next
n.prev = &c.dummy
n.next.prev = n
n.prev.next = n
// The caller is responsible for decrementing the refCount.
n.refCount++
return n
} | [
"func",
"(",
"c",
"*",
"tableCache",
")",
"findNode",
"(",
"fileNum",
"uint64",
")",
"*",
"tableCacheNode",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"n",
":=",
"c",
".",
"nodes",
... | // findNode returns the node for the table with the given file number, creating
// that node if it didn't already exist. The caller is responsible for
// decrementing the returned node's refCount. | [
"findNode",
"returns",
"the",
"node",
"for",
"the",
"table",
"with",
"the",
"given",
"file",
"number",
"creating",
"that",
"node",
"if",
"it",
"didn",
"t",
"already",
"exist",
".",
"The",
"caller",
"is",
"responsible",
"for",
"decrementing",
"the",
"returned... | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/table_cache.go#L79-L109 | train |
golang/leveldb | version.go | totalSize | func totalSize(f []fileMetadata) (size uint64) {
for _, x := range f {
size += x.size
}
return size
} | go | func totalSize(f []fileMetadata) (size uint64) {
for _, x := range f {
size += x.size
}
return size
} | [
"func",
"totalSize",
"(",
"f",
"[",
"]",
"fileMetadata",
")",
"(",
"size",
"uint64",
")",
"{",
"for",
"_",
",",
"x",
":=",
"range",
"f",
"{",
"size",
"+=",
"x",
".",
"size",
"\n",
"}",
"\n",
"return",
"size",
"\n",
"}"
] | // totalSize returns the total size of all the files in f. | [
"totalSize",
"returns",
"the",
"total",
"size",
"of",
"all",
"the",
"files",
"in",
"f",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/version.go#L26-L31 | train |
golang/leveldb | version.go | ikeyRange | func ikeyRange(icmp db.Comparer, f0, f1 []fileMetadata) (smallest, largest internalKey) {
first := true
for _, f := range [2][]fileMetadata{f0, f1} {
for _, meta := range f {
if first {
first = false
smallest, largest = meta.smallest, meta.largest
continue
}
if icmp.Compare(meta.smallest, smallest) < 0 {
smallest = meta.smallest
}
if icmp.Compare(meta.largest, largest) > 0 {
largest = meta.largest
}
}
}
return smallest, largest
} | go | func ikeyRange(icmp db.Comparer, f0, f1 []fileMetadata) (smallest, largest internalKey) {
first := true
for _, f := range [2][]fileMetadata{f0, f1} {
for _, meta := range f {
if first {
first = false
smallest, largest = meta.smallest, meta.largest
continue
}
if icmp.Compare(meta.smallest, smallest) < 0 {
smallest = meta.smallest
}
if icmp.Compare(meta.largest, largest) > 0 {
largest = meta.largest
}
}
}
return smallest, largest
} | [
"func",
"ikeyRange",
"(",
"icmp",
"db",
".",
"Comparer",
",",
"f0",
",",
"f1",
"[",
"]",
"fileMetadata",
")",
"(",
"smallest",
",",
"largest",
"internalKey",
")",
"{",
"first",
":=",
"true",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"[",
"2",
"]",... | // ikeyRange returns the minimum smallest and maximum largest internalKey for
// all the fileMetadata in f0 and f1. | [
"ikeyRange",
"returns",
"the",
"minimum",
"smallest",
"and",
"maximum",
"largest",
"internalKey",
"for",
"all",
"the",
"fileMetadata",
"in",
"f0",
"and",
"f1",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/version.go#L35-L53 | train |
golang/leveldb | version.go | updateCompactionScore | func (v *version) updateCompactionScore() {
// We treat level-0 specially by bounding the number of files instead of
// number of bytes for two reasons:
//
// (1) With larger write-buffer sizes, it is nice not to do too many
// level-0 compactions.
//
// (2) The files in level-0 are merged on every read and therefore we
// wish to avoid too many files when the individual file size is small
// (perhaps because of a small write-buffer setting, or very high
// compression ratios, or lots of overwrites/deletions).
v.compactionScore = float64(len(v.files[0])) / l0CompactionTrigger
v.compactionLevel = 0
maxBytes := float64(10 * 1024 * 1024)
for level := 1; level < numLevels-1; level++ {
score := float64(totalSize(v.files[level])) / maxBytes
if score > v.compactionScore {
v.compactionScore = score
v.compactionLevel = level
}
maxBytes *= 10
}
} | go | func (v *version) updateCompactionScore() {
// We treat level-0 specially by bounding the number of files instead of
// number of bytes for two reasons:
//
// (1) With larger write-buffer sizes, it is nice not to do too many
// level-0 compactions.
//
// (2) The files in level-0 are merged on every read and therefore we
// wish to avoid too many files when the individual file size is small
// (perhaps because of a small write-buffer setting, or very high
// compression ratios, or lots of overwrites/deletions).
v.compactionScore = float64(len(v.files[0])) / l0CompactionTrigger
v.compactionLevel = 0
maxBytes := float64(10 * 1024 * 1024)
for level := 1; level < numLevels-1; level++ {
score := float64(totalSize(v.files[level])) / maxBytes
if score > v.compactionScore {
v.compactionScore = score
v.compactionLevel = level
}
maxBytes *= 10
}
} | [
"func",
"(",
"v",
"*",
"version",
")",
"updateCompactionScore",
"(",
")",
"{",
"// We treat level-0 specially by bounding the number of files instead of",
"// number of bytes for two reasons:",
"//",
"// (1) With larger write-buffer sizes, it is nice not to do too many",
"// level-0 comp... | // updateCompactionScore updates v's compaction score and level. | [
"updateCompactionScore",
"updates",
"v",
"s",
"compaction",
"score",
"and",
"level",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/version.go#L108-L131 | train |
golang/leveldb | version.go | get | func (v *version) get(ikey internalKey, tiFinder tableIkeyFinder, ucmp db.Comparer, ro *db.ReadOptions) ([]byte, error) {
ukey := ikey.ukey()
// Iterate through v's tables, calling internalGet if the table's bounds
// might contain ikey. Due to the order in which we search the tables, and
// the internalKeyComparer's ordering within a table, we stop after the
// first conclusive result.
// Search the level 0 files in decreasing fileNum order,
// which is also decreasing sequence number order.
icmp := internalKeyComparer{ucmp}
for i := len(v.files[0]) - 1; i >= 0; i-- {
f := v.files[0][i]
// We compare user keys on the low end, as we do not want to reject a table
// whose smallest internal key may have the same user key and a lower sequence
// number. An internalKeyComparer sorts increasing by user key but then
// descending by sequence number.
if ucmp.Compare(ukey, f.smallest.ukey()) < 0 {
continue
}
// We compare internal keys on the high end. It gives a tighter bound than
// comparing user keys.
if icmp.Compare(ikey, f.largest) > 0 {
continue
}
iter, err := tiFinder.find(f.fileNum, ikey)
if err != nil {
return nil, fmt.Errorf("leveldb: could not open table %d: %v", f.fileNum, err)
}
value, conclusive, err := internalGet(iter, ucmp, ukey)
if conclusive {
return value, err
}
}
// Search the remaining levels.
for level := 1; level < len(v.files); level++ {
n := len(v.files[level])
if n == 0 {
continue
}
// Find the earliest file at that level whose largest key is >= ikey.
index := sort.Search(n, func(i int) bool {
return icmp.Compare(v.files[level][i].largest, ikey) >= 0
})
if index == n {
continue
}
f := v.files[level][index]
if ucmp.Compare(ukey, f.smallest.ukey()) < 0 {
continue
}
iter, err := tiFinder.find(f.fileNum, ikey)
if err != nil {
return nil, fmt.Errorf("leveldb: could not open table %d: %v", f.fileNum, err)
}
value, conclusive, err := internalGet(iter, ucmp, ukey)
if conclusive {
return value, err
}
}
return nil, db.ErrNotFound
} | go | func (v *version) get(ikey internalKey, tiFinder tableIkeyFinder, ucmp db.Comparer, ro *db.ReadOptions) ([]byte, error) {
ukey := ikey.ukey()
// Iterate through v's tables, calling internalGet if the table's bounds
// might contain ikey. Due to the order in which we search the tables, and
// the internalKeyComparer's ordering within a table, we stop after the
// first conclusive result.
// Search the level 0 files in decreasing fileNum order,
// which is also decreasing sequence number order.
icmp := internalKeyComparer{ucmp}
for i := len(v.files[0]) - 1; i >= 0; i-- {
f := v.files[0][i]
// We compare user keys on the low end, as we do not want to reject a table
// whose smallest internal key may have the same user key and a lower sequence
// number. An internalKeyComparer sorts increasing by user key but then
// descending by sequence number.
if ucmp.Compare(ukey, f.smallest.ukey()) < 0 {
continue
}
// We compare internal keys on the high end. It gives a tighter bound than
// comparing user keys.
if icmp.Compare(ikey, f.largest) > 0 {
continue
}
iter, err := tiFinder.find(f.fileNum, ikey)
if err != nil {
return nil, fmt.Errorf("leveldb: could not open table %d: %v", f.fileNum, err)
}
value, conclusive, err := internalGet(iter, ucmp, ukey)
if conclusive {
return value, err
}
}
// Search the remaining levels.
for level := 1; level < len(v.files); level++ {
n := len(v.files[level])
if n == 0 {
continue
}
// Find the earliest file at that level whose largest key is >= ikey.
index := sort.Search(n, func(i int) bool {
return icmp.Compare(v.files[level][i].largest, ikey) >= 0
})
if index == n {
continue
}
f := v.files[level][index]
if ucmp.Compare(ukey, f.smallest.ukey()) < 0 {
continue
}
iter, err := tiFinder.find(f.fileNum, ikey)
if err != nil {
return nil, fmt.Errorf("leveldb: could not open table %d: %v", f.fileNum, err)
}
value, conclusive, err := internalGet(iter, ucmp, ukey)
if conclusive {
return value, err
}
}
return nil, db.ErrNotFound
} | [
"func",
"(",
"v",
"*",
"version",
")",
"get",
"(",
"ikey",
"internalKey",
",",
"tiFinder",
"tableIkeyFinder",
",",
"ucmp",
"db",
".",
"Comparer",
",",
"ro",
"*",
"db",
".",
"ReadOptions",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"ukey",
... | // get looks up the internal key ikey0 in v's tables such that ikey and ikey0
// have the same user key, and ikey0's sequence number is the highest such
// sequence number that is less than or equal to ikey's sequence number.
//
// If ikey0's kind is set, the value for that previous set action is returned.
// If ikey0's kind is delete, the db.ErrNotFound error is returned.
// If there is no such ikey0, the db.ErrNotFound error is returned. | [
"get",
"looks",
"up",
"the",
"internal",
"key",
"ikey0",
"in",
"v",
"s",
"tables",
"such",
"that",
"ikey",
"and",
"ikey0",
"have",
"the",
"same",
"user",
"key",
"and",
"ikey0",
"s",
"sequence",
"number",
"is",
"the",
"highest",
"such",
"sequence",
"numbe... | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/version.go#L219-L280 | train |
golang/leveldb | ikey.go | valid | func (k internalKey) valid() bool {
i := len(k) - 8
return i >= 0 && internalKeyKind(k[i]) <= internalKeyKindMax
} | go | func (k internalKey) valid() bool {
i := len(k) - 8
return i >= 0 && internalKeyKind(k[i]) <= internalKeyKindMax
} | [
"func",
"(",
"k",
"internalKey",
")",
"valid",
"(",
")",
"bool",
"{",
"i",
":=",
"len",
"(",
"k",
")",
"-",
"8",
"\n",
"return",
"i",
">=",
"0",
"&&",
"internalKeyKind",
"(",
"k",
"[",
"i",
"]",
")",
"<=",
"internalKeyKindMax",
"\n",
"}"
] | // valid returns whether k is a valid internal key. | [
"valid",
"returns",
"whether",
"k",
"is",
"a",
"valid",
"internal",
"key",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/ikey.go#L69-L72 | train |
golang/leveldb | ikey.go | seqNum | func (k internalKey) seqNum() uint64 {
i := len(k) - 7
n := uint64(k[i+0])
n |= uint64(k[i+1]) << 8
n |= uint64(k[i+2]) << 16
n |= uint64(k[i+3]) << 24
n |= uint64(k[i+4]) << 32
n |= uint64(k[i+5]) << 40
n |= uint64(k[i+6]) << 48
return n
} | go | func (k internalKey) seqNum() uint64 {
i := len(k) - 7
n := uint64(k[i+0])
n |= uint64(k[i+1]) << 8
n |= uint64(k[i+2]) << 16
n |= uint64(k[i+3]) << 24
n |= uint64(k[i+4]) << 32
n |= uint64(k[i+5]) << 40
n |= uint64(k[i+6]) << 48
return n
} | [
"func",
"(",
"k",
"internalKey",
")",
"seqNum",
"(",
")",
"uint64",
"{",
"i",
":=",
"len",
"(",
"k",
")",
"-",
"7",
"\n",
"n",
":=",
"uint64",
"(",
"k",
"[",
"i",
"+",
"0",
"]",
")",
"\n",
"n",
"|=",
"uint64",
"(",
"k",
"[",
"i",
"+",
"1"... | // seqNum returns the sequence number of an internal key.
// seqNum may panic if k is not valid. | [
"seqNum",
"returns",
"the",
"sequence",
"number",
"of",
"an",
"internal",
"key",
".",
"seqNum",
"may",
"panic",
"if",
"k",
"is",
"not",
"valid",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/ikey.go#L88-L98 | train |
golang/leveldb | ikey.go | clone | func (k internalKey) clone() internalKey {
x := make(internalKey, len(k))
copy(x, k)
return x
} | go | func (k internalKey) clone() internalKey {
x := make(internalKey, len(k))
copy(x, k)
return x
} | [
"func",
"(",
"k",
"internalKey",
")",
"clone",
"(",
")",
"internalKey",
"{",
"x",
":=",
"make",
"(",
"internalKey",
",",
"len",
"(",
"k",
")",
")",
"\n",
"copy",
"(",
"x",
",",
"k",
")",
"\n",
"return",
"x",
"\n",
"}"
] | // clone returns an internalKey that has the same contents but is backed by a
// different array. | [
"clone",
"returns",
"an",
"internalKey",
"that",
"has",
"the",
"same",
"contents",
"but",
"is",
"backed",
"by",
"a",
"different",
"array",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/ikey.go#L102-L106 | train |
golang/leveldb | record/record.go | Next | func (r *Reader) Next() (io.Reader, error) {
r.seq++
if r.err != nil {
return nil, r.err
}
r.i = r.j
r.err = r.nextChunk(true)
if r.err != nil {
return nil, r.err
}
r.started = true
return singleReader{r, r.seq}, nil
} | go | func (r *Reader) Next() (io.Reader, error) {
r.seq++
if r.err != nil {
return nil, r.err
}
r.i = r.j
r.err = r.nextChunk(true)
if r.err != nil {
return nil, r.err
}
r.started = true
return singleReader{r, r.seq}, nil
} | [
"func",
"(",
"r",
"*",
"Reader",
")",
"Next",
"(",
")",
"(",
"io",
".",
"Reader",
",",
"error",
")",
"{",
"r",
".",
"seq",
"++",
"\n",
"if",
"r",
".",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"r",
".",
"err",
"\n",
"}",
"\n",
"r",
"... | // Next returns a reader for the next record. It returns io.EOF if there are no
// more records. The reader returned becomes stale after the next Next call,
// and should no longer be used. | [
"Next",
"returns",
"a",
"reader",
"for",
"the",
"next",
"record",
".",
"It",
"returns",
"io",
".",
"EOF",
"if",
"there",
"are",
"no",
"more",
"records",
".",
"The",
"reader",
"returned",
"becomes",
"stale",
"after",
"the",
"next",
"Next",
"call",
"and",
... | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/record/record.go#L213-L225 | train |
golang/leveldb | record/record.go | Recover | func (r *Reader) Recover() {
if r.err == nil {
return
}
r.recovering = true
r.err = nil
// Discard the rest of the current block.
r.i, r.j, r.last = r.n, r.n, false
// Invalidate any outstanding singleReader.
r.seq++
return
} | go | func (r *Reader) Recover() {
if r.err == nil {
return
}
r.recovering = true
r.err = nil
// Discard the rest of the current block.
r.i, r.j, r.last = r.n, r.n, false
// Invalidate any outstanding singleReader.
r.seq++
return
} | [
"func",
"(",
"r",
"*",
"Reader",
")",
"Recover",
"(",
")",
"{",
"if",
"r",
".",
"err",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"r",
".",
"recovering",
"=",
"true",
"\n",
"r",
".",
"err",
"=",
"nil",
"\n",
"// Discard the rest of the current bloc... | // Recover clears any errors read so far, so that calling Next will start
// reading from the next good 32KiB block. If there are no such blocks, Next
// will return io.EOF. Recover also marks the current reader, the one most
// recently returned by Next, as stale. If Recover is called without any
// prior error, then Recover is a no-op. | [
"Recover",
"clears",
"any",
"errors",
"read",
"so",
"far",
"so",
"that",
"calling",
"Next",
"will",
"start",
"reading",
"from",
"the",
"next",
"good",
"32KiB",
"block",
".",
"If",
"there",
"are",
"no",
"such",
"blocks",
"Next",
"will",
"return",
"io",
".... | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/record/record.go#L232-L243 | train |
golang/leveldb | record/record.go | SeekRecord | func (r *Reader) SeekRecord(offset int64) error {
r.seq++
if r.err != nil {
return r.err
}
s, ok := r.r.(io.Seeker)
if !ok {
return ErrNotAnIOSeeker
}
// Only seek to an exact block offset.
c := int(offset & blockSizeMask)
if _, r.err = s.Seek(offset&^blockSizeMask, io.SeekStart); r.err != nil {
return r.err
}
// Clear the state of the internal reader.
r.i, r.j, r.n = 0, 0, 0
r.started, r.recovering, r.last = false, false, false
if r.err = r.nextChunk(false); r.err != nil {
return r.err
}
// Now skip to the offset requested within the block. A subsequent
// call to Next will return the block at the requested offset.
r.i, r.j = c, c
return nil
} | go | func (r *Reader) SeekRecord(offset int64) error {
r.seq++
if r.err != nil {
return r.err
}
s, ok := r.r.(io.Seeker)
if !ok {
return ErrNotAnIOSeeker
}
// Only seek to an exact block offset.
c := int(offset & blockSizeMask)
if _, r.err = s.Seek(offset&^blockSizeMask, io.SeekStart); r.err != nil {
return r.err
}
// Clear the state of the internal reader.
r.i, r.j, r.n = 0, 0, 0
r.started, r.recovering, r.last = false, false, false
if r.err = r.nextChunk(false); r.err != nil {
return r.err
}
// Now skip to the offset requested within the block. A subsequent
// call to Next will return the block at the requested offset.
r.i, r.j = c, c
return nil
} | [
"func",
"(",
"r",
"*",
"Reader",
")",
"SeekRecord",
"(",
"offset",
"int64",
")",
"error",
"{",
"r",
".",
"seq",
"++",
"\n",
"if",
"r",
".",
"err",
"!=",
"nil",
"{",
"return",
"r",
".",
"err",
"\n",
"}",
"\n\n",
"s",
",",
"ok",
":=",
"r",
".",... | // SeekRecord seeks in the underlying io.Reader such that calling r.Next
// returns the record whose first chunk header starts at the provided offset.
// Its behavior is undefined if the argument given is not such an offset, as
// the bytes at that offset may coincidentally appear to be a valid header.
//
// It returns ErrNotAnIOSeeker if the underlying io.Reader does not implement
// io.Seeker.
//
// SeekRecord will fail and return an error if the Reader previously
// encountered an error, including io.EOF. Such errors can be cleared by
// calling Recover. Calling SeekRecord after Recover will make calling Next
// return the record at the given offset, instead of the record at the next
// good 32KiB block as Recover normally would. Calling SeekRecord before
// Recover has no effect on Recover's semantics other than changing the
// starting point for determining the next good 32KiB block.
//
// The offset is always relative to the start of the underlying io.Reader, so
// negative values will result in an error as per io.Seeker. | [
"SeekRecord",
"seeks",
"in",
"the",
"underlying",
"io",
".",
"Reader",
"such",
"that",
"calling",
"r",
".",
"Next",
"returns",
"the",
"record",
"whose",
"first",
"chunk",
"header",
"starts",
"at",
"the",
"provided",
"offset",
".",
"Its",
"behavior",
"is",
... | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/record/record.go#L263-L292 | train |
golang/leveldb | record/record.go | Next | func (w *Writer) Next() (io.Writer, error) {
w.seq++
if w.err != nil {
return nil, w.err
}
if w.pending {
w.fillHeader(true)
}
w.i = w.j
w.j = w.j + headerSize
// Check if there is room in the block for the header.
if w.j > blockSize {
// Fill in the rest of the block with zeroes.
for k := w.i; k < blockSize; k++ {
w.buf[k] = 0
}
w.writeBlock()
if w.err != nil {
return nil, w.err
}
}
w.lastRecordOffset = w.baseOffset + w.blockNumber*blockSize + int64(w.i)
w.first = true
w.pending = true
return singleWriter{w, w.seq}, nil
} | go | func (w *Writer) Next() (io.Writer, error) {
w.seq++
if w.err != nil {
return nil, w.err
}
if w.pending {
w.fillHeader(true)
}
w.i = w.j
w.j = w.j + headerSize
// Check if there is room in the block for the header.
if w.j > blockSize {
// Fill in the rest of the block with zeroes.
for k := w.i; k < blockSize; k++ {
w.buf[k] = 0
}
w.writeBlock()
if w.err != nil {
return nil, w.err
}
}
w.lastRecordOffset = w.baseOffset + w.blockNumber*blockSize + int64(w.i)
w.first = true
w.pending = true
return singleWriter{w, w.seq}, nil
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"Next",
"(",
")",
"(",
"io",
".",
"Writer",
",",
"error",
")",
"{",
"w",
".",
"seq",
"++",
"\n",
"if",
"w",
".",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"w",
".",
"err",
"\n",
"}",
"\n",
"if",
... | // Next returns a writer for the next record. The writer returned becomes stale
// after the next Close, Flush or Next call, and should no longer be used. | [
"Next",
"returns",
"a",
"writer",
"for",
"the",
"next",
"record",
".",
"The",
"writer",
"returned",
"becomes",
"stale",
"after",
"the",
"next",
"Close",
"Flush",
"or",
"Next",
"call",
"and",
"should",
"no",
"longer",
"be",
"used",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/record/record.go#L447-L472 | train |
golang/leveldb | record/record.go | LastRecordOffset | func (w *Writer) LastRecordOffset() (int64, error) {
if w.err != nil {
return 0, w.err
}
if w.lastRecordOffset < 0 {
return 0, ErrNoLastRecord
}
return w.lastRecordOffset, nil
} | go | func (w *Writer) LastRecordOffset() (int64, error) {
if w.err != nil {
return 0, w.err
}
if w.lastRecordOffset < 0 {
return 0, ErrNoLastRecord
}
return w.lastRecordOffset, nil
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"LastRecordOffset",
"(",
")",
"(",
"int64",
",",
"error",
")",
"{",
"if",
"w",
".",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"w",
".",
"err",
"\n",
"}",
"\n",
"if",
"w",
".",
"lastRecordOffset",
"<",
"0... | // LastRecordOffset returns the offset in the underlying io.Writer of the last
// record so far - the one created by the most recent Next call. It is the
// offset of the first chunk header, suitable to pass to Reader.SeekRecord.
//
// If that io.Writer also implements io.Seeker, the return value is an absolute
// offset, in the sense of io.SeekStart, regardless of whether the io.Writer
// was initially at the zero position when passed to NewWriter. Otherwise, the
// return value is a relative offset, being the number of bytes written between
// the NewWriter call and any records written prior to the last record.
//
// If there is no last record, i.e. nothing was written, LastRecordOffset will
// return ErrNoLastRecord. | [
"LastRecordOffset",
"returns",
"the",
"offset",
"in",
"the",
"underlying",
"io",
".",
"Writer",
"of",
"the",
"last",
"record",
"so",
"far",
"-",
"the",
"one",
"created",
"by",
"the",
"most",
"recent",
"Next",
"call",
".",
"It",
"is",
"the",
"offset",
"of... | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/record/record.go#L486-L494 | train |
golang/leveldb | table/writer.go | Get | func (w *Writer) Get(key []byte, o *db.ReadOptions) ([]byte, error) {
return nil, errors.New("leveldb/table: cannot Get from a write-only table")
} | go | func (w *Writer) Get(key []byte, o *db.ReadOptions) ([]byte, error) {
return nil, errors.New("leveldb/table: cannot Get from a write-only table")
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"Get",
"(",
"key",
"[",
"]",
"byte",
",",
"o",
"*",
"db",
".",
"ReadOptions",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
... | // Get is provided to implement the DB interface, but returns an error, as a
// Writer cannot read from a table. | [
"Get",
"is",
"provided",
"to",
"implement",
"the",
"DB",
"interface",
"but",
"returns",
"an",
"error",
"as",
"a",
"Writer",
"cannot",
"read",
"from",
"a",
"table",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/table/writer.go#L170-L172 | train |
golang/leveldb | table/writer.go | Find | func (w *Writer) Find(key []byte, o *db.ReadOptions) db.Iterator {
return &tableIter{
err: errors.New("leveldb/table: cannot Find from a write-only table"),
}
} | go | func (w *Writer) Find(key []byte, o *db.ReadOptions) db.Iterator {
return &tableIter{
err: errors.New("leveldb/table: cannot Find from a write-only table"),
}
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"Find",
"(",
"key",
"[",
"]",
"byte",
",",
"o",
"*",
"db",
".",
"ReadOptions",
")",
"db",
".",
"Iterator",
"{",
"return",
"&",
"tableIter",
"{",
"err",
":",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
",",
... | // Find is provided to implement the DB interface, but returns an error, as a
// Writer cannot read from a table. | [
"Find",
"is",
"provided",
"to",
"implement",
"the",
"DB",
"interface",
"but",
"returns",
"an",
"error",
"as",
"a",
"Writer",
"cannot",
"read",
"from",
"a",
"table",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/table/writer.go#L182-L186 | train |
golang/leveldb | table/writer.go | flushPendingBH | func (w *Writer) flushPendingBH(key []byte) {
if w.pendingBH.length == 0 {
// A valid blockHandle must be non-zero.
// In particular, it must have a non-zero length.
return
}
n0 := len(w.indexKeys)
w.indexKeys = w.cmp.AppendSeparator(w.indexKeys, w.prevKey, key)
n1 := len(w.indexKeys)
w.indexEntries = append(w.indexEntries, indexEntry{w.pendingBH, n1 - n0})
w.pendingBH = blockHandle{}
} | go | func (w *Writer) flushPendingBH(key []byte) {
if w.pendingBH.length == 0 {
// A valid blockHandle must be non-zero.
// In particular, it must have a non-zero length.
return
}
n0 := len(w.indexKeys)
w.indexKeys = w.cmp.AppendSeparator(w.indexKeys, w.prevKey, key)
n1 := len(w.indexKeys)
w.indexEntries = append(w.indexEntries, indexEntry{w.pendingBH, n1 - n0})
w.pendingBH = blockHandle{}
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"flushPendingBH",
"(",
"key",
"[",
"]",
"byte",
")",
"{",
"if",
"w",
".",
"pendingBH",
".",
"length",
"==",
"0",
"{",
"// A valid blockHandle must be non-zero.",
"// In particular, it must have a non-zero length.",
"return",
"... | // flushPendingBH adds any pending block handle to the index entries. | [
"flushPendingBH",
"adds",
"any",
"pending",
"block",
"handle",
"to",
"the",
"index",
"entries",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/table/writer.go#L216-L227 | train |
golang/leveldb | table/writer.go | finishBlock | func (w *Writer) finishBlock() (blockHandle, error) {
// Write the restart points to the buffer.
if w.nEntries == 0 {
// Every block must have at least one restart point.
w.restarts = w.restarts[:1]
w.restarts[0] = 0
}
tmp4 := w.tmp[:4]
for _, x := range w.restarts {
binary.LittleEndian.PutUint32(tmp4, x)
w.buf = append(w.buf, tmp4...)
}
binary.LittleEndian.PutUint32(tmp4, uint32(len(w.restarts)))
w.buf = append(w.buf, tmp4...)
// Compress the buffer, discarding the result if the improvement
// isn't at least 12.5%.
b := w.buf
blockType := byte(noCompressionBlockType)
if w.compression == db.SnappyCompression {
compressed := snappy.Encode(w.compressedBuf, b)
w.compressedBuf = compressed[:cap(compressed)]
if len(compressed) < len(b)-len(b)/8 {
blockType = snappyCompressionBlockType
b = compressed
}
}
bh, err := w.writeRawBlock(b, blockType)
// Calculate filters.
if w.filter.policy != nil {
w.filter.finishBlock(w.offset)
}
// Reset the per-block state.
w.buf = w.buf[:0]
w.nEntries = 0
w.restarts = w.restarts[:0]
return bh, err
} | go | func (w *Writer) finishBlock() (blockHandle, error) {
// Write the restart points to the buffer.
if w.nEntries == 0 {
// Every block must have at least one restart point.
w.restarts = w.restarts[:1]
w.restarts[0] = 0
}
tmp4 := w.tmp[:4]
for _, x := range w.restarts {
binary.LittleEndian.PutUint32(tmp4, x)
w.buf = append(w.buf, tmp4...)
}
binary.LittleEndian.PutUint32(tmp4, uint32(len(w.restarts)))
w.buf = append(w.buf, tmp4...)
// Compress the buffer, discarding the result if the improvement
// isn't at least 12.5%.
b := w.buf
blockType := byte(noCompressionBlockType)
if w.compression == db.SnappyCompression {
compressed := snappy.Encode(w.compressedBuf, b)
w.compressedBuf = compressed[:cap(compressed)]
if len(compressed) < len(b)-len(b)/8 {
blockType = snappyCompressionBlockType
b = compressed
}
}
bh, err := w.writeRawBlock(b, blockType)
// Calculate filters.
if w.filter.policy != nil {
w.filter.finishBlock(w.offset)
}
// Reset the per-block state.
w.buf = w.buf[:0]
w.nEntries = 0
w.restarts = w.restarts[:0]
return bh, err
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"finishBlock",
"(",
")",
"(",
"blockHandle",
",",
"error",
")",
"{",
"// Write the restart points to the buffer.",
"if",
"w",
".",
"nEntries",
"==",
"0",
"{",
"// Every block must have at least one restart point.",
"w",
".",
"... | // finishBlock finishes the current block and returns its block handle, which is
// its offset and length in the table. | [
"finishBlock",
"finishes",
"the",
"current",
"block",
"and",
"returns",
"its",
"block",
"handle",
"which",
"is",
"its",
"offset",
"and",
"length",
"in",
"the",
"table",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/table/writer.go#L249-L289 | train |
golang/leveldb | table/writer.go | NewWriter | func NewWriter(f db.File, o *db.Options) *Writer {
w := &Writer{
closer: f,
blockRestartInterval: o.GetBlockRestartInterval(),
blockSize: o.GetBlockSize(),
cmp: o.GetComparer(),
compression: o.GetCompression(),
filter: filterWriter{
policy: o.GetFilterPolicy(),
},
prevKey: make([]byte, 0, 256),
restarts: make([]uint32, 0, 256),
}
if f == nil {
w.err = errors.New("leveldb/table: nil file")
return w
}
// If f does not have a Flush method, do our own buffering.
type flusher interface {
Flush() error
}
if _, ok := f.(flusher); ok {
w.writer = f
} else {
w.bufWriter = bufio.NewWriter(f)
w.writer = w.bufWriter
}
return w
} | go | func NewWriter(f db.File, o *db.Options) *Writer {
w := &Writer{
closer: f,
blockRestartInterval: o.GetBlockRestartInterval(),
blockSize: o.GetBlockSize(),
cmp: o.GetComparer(),
compression: o.GetCompression(),
filter: filterWriter{
policy: o.GetFilterPolicy(),
},
prevKey: make([]byte, 0, 256),
restarts: make([]uint32, 0, 256),
}
if f == nil {
w.err = errors.New("leveldb/table: nil file")
return w
}
// If f does not have a Flush method, do our own buffering.
type flusher interface {
Flush() error
}
if _, ok := f.(flusher); ok {
w.writer = f
} else {
w.bufWriter = bufio.NewWriter(f)
w.writer = w.bufWriter
}
return w
} | [
"func",
"NewWriter",
"(",
"f",
"db",
".",
"File",
",",
"o",
"*",
"db",
".",
"Options",
")",
"*",
"Writer",
"{",
"w",
":=",
"&",
"Writer",
"{",
"closer",
":",
"f",
",",
"blockRestartInterval",
":",
"o",
".",
"GetBlockRestartInterval",
"(",
")",
",",
... | // NewWriter returns a new table writer for the file. Closing the writer will
// close the file. | [
"NewWriter",
"returns",
"a",
"new",
"table",
"writer",
"for",
"the",
"file",
".",
"Closing",
"the",
"writer",
"will",
"close",
"the",
"file",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/table/writer.go#L409-L437 | train |
golang/leveldb | memdb/memdb.go | ApproximateMemoryUsage | func (m *MemDB) ApproximateMemoryUsage() int {
m.mutex.RLock()
defer m.mutex.RUnlock()
return len(m.kvData)
} | go | func (m *MemDB) ApproximateMemoryUsage() int {
m.mutex.RLock()
defer m.mutex.RUnlock()
return len(m.kvData)
} | [
"func",
"(",
"m",
"*",
"MemDB",
")",
"ApproximateMemoryUsage",
"(",
")",
"int",
"{",
"m",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"m",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"len",
"(",
"m",
".",
"kvData",
")",
"\n",... | // ApproximateMemoryUsage returns the approximate memory usage of the MemDB. | [
"ApproximateMemoryUsage",
"returns",
"the",
"approximate",
"memory",
"usage",
"of",
"the",
"MemDB",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/memdb/memdb.go#L223-L227 | train |
golang/leveldb | memdb/memdb.go | New | func New(o *db.Options) *MemDB {
return &MemDB{
height: 1,
cmp: o.GetComparer(),
kvData: make([]byte, 0, 4096),
// The first maxHeight values of nodeData are the next nodes after the
// head node at each possible height. Their initial value is zeroNode.
nodeData: make([]int, maxHeight, 256),
}
} | go | func New(o *db.Options) *MemDB {
return &MemDB{
height: 1,
cmp: o.GetComparer(),
kvData: make([]byte, 0, 4096),
// The first maxHeight values of nodeData are the next nodes after the
// head node at each possible height. Their initial value is zeroNode.
nodeData: make([]int, maxHeight, 256),
}
} | [
"func",
"New",
"(",
"o",
"*",
"db",
".",
"Options",
")",
"*",
"MemDB",
"{",
"return",
"&",
"MemDB",
"{",
"height",
":",
"1",
",",
"cmp",
":",
"o",
".",
"GetComparer",
"(",
")",
",",
"kvData",
":",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",... | // New returns a new MemDB. | [
"New",
"returns",
"a",
"new",
"MemDB",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/memdb/memdb.go#L237-L246 | train |
golang/leveldb | version_set.go | createManifest | func (vs *versionSet) createManifest(dirname string) (err error) {
var (
filename = dbFilename(dirname, fileTypeManifest, vs.manifestFileNumber)
manifestFile db.File
manifest *record.Writer
)
defer func() {
if manifest != nil {
manifest.Close()
}
if manifestFile != nil {
manifestFile.Close()
}
if err != nil {
vs.fs.Remove(filename)
}
}()
manifestFile, err = vs.fs.Create(filename)
if err != nil {
return err
}
manifest = record.NewWriter(manifestFile)
snapshot := versionEdit{
comparatorName: vs.ucmp.Name(),
}
// TODO: save compaction pointers.
for level, fileMetadata := range vs.currentVersion().files {
for _, meta := range fileMetadata {
snapshot.newFiles = append(snapshot.newFiles, newFileEntry{
level: level,
meta: meta,
})
}
}
w, err1 := manifest.Next()
if err1 != nil {
return err1
}
err1 = snapshot.encode(w)
if err1 != nil {
return err1
}
vs.manifest, manifest = manifest, nil
vs.manifestFile, manifestFile = manifestFile, nil
return nil
} | go | func (vs *versionSet) createManifest(dirname string) (err error) {
var (
filename = dbFilename(dirname, fileTypeManifest, vs.manifestFileNumber)
manifestFile db.File
manifest *record.Writer
)
defer func() {
if manifest != nil {
manifest.Close()
}
if manifestFile != nil {
manifestFile.Close()
}
if err != nil {
vs.fs.Remove(filename)
}
}()
manifestFile, err = vs.fs.Create(filename)
if err != nil {
return err
}
manifest = record.NewWriter(manifestFile)
snapshot := versionEdit{
comparatorName: vs.ucmp.Name(),
}
// TODO: save compaction pointers.
for level, fileMetadata := range vs.currentVersion().files {
for _, meta := range fileMetadata {
snapshot.newFiles = append(snapshot.newFiles, newFileEntry{
level: level,
meta: meta,
})
}
}
w, err1 := manifest.Next()
if err1 != nil {
return err1
}
err1 = snapshot.encode(w)
if err1 != nil {
return err1
}
vs.manifest, manifest = manifest, nil
vs.manifestFile, manifestFile = manifestFile, nil
return nil
} | [
"func",
"(",
"vs",
"*",
"versionSet",
")",
"createManifest",
"(",
"dirname",
"string",
")",
"(",
"err",
"error",
")",
"{",
"var",
"(",
"filename",
"=",
"dbFilename",
"(",
"dirname",
",",
"fileTypeManifest",
",",
"vs",
".",
"manifestFileNumber",
")",
"\n",
... | // createManifest creates a manifest file that contains a snapshot of vs. | [
"createManifest",
"creates",
"a",
"manifest",
"file",
"that",
"contains",
"a",
"snapshot",
"of",
"vs",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/version_set.go#L193-L241 | train |
golang/leveldb | leveldb.go | replayLogFile | func (d *DB) replayLogFile(ve *versionEdit, fs db.FileSystem, filename string) (maxSeqNum uint64, err error) {
file, err := fs.Open(filename)
if err != nil {
return 0, err
}
defer file.Close()
var (
mem *memdb.MemDB
batchBuf = new(bytes.Buffer)
ikey = make(internalKey, 512)
rr = record.NewReader(file)
)
for {
r, err := rr.Next()
if err == io.EOF {
break
}
if err != nil {
return 0, err
}
_, err = io.Copy(batchBuf, r)
if err != nil {
return 0, err
}
if batchBuf.Len() < batchHeaderLen {
return 0, fmt.Errorf("leveldb: corrupt log file %q", filename)
}
b := Batch{batchBuf.Bytes()}
seqNum := b.seqNum()
seqNum1 := seqNum + uint64(b.count())
if maxSeqNum < seqNum1 {
maxSeqNum = seqNum1
}
if mem == nil {
mem = memdb.New(&d.icmpOpts)
}
t := b.iter()
for ; seqNum != seqNum1; seqNum++ {
kind, ukey, value, ok := t.next()
if !ok {
return 0, fmt.Errorf("leveldb: corrupt log file %q", filename)
}
// Convert seqNum, kind and key into an internalKey, and add that ikey/value
// pair to mem.
//
// TODO: instead of copying to an intermediate buffer (ikey), is it worth
// adding a SetTwoPartKey(db.TwoPartKey{key0, key1}, value, opts) method to
// memdb.MemDB? What effect does that have on the db.Comparer interface?
//
// The C++ LevelDB code does not need an intermediate copy because its memdb
// implementation is a private implementation detail, and copies each internal
// key component from the Batch format straight to the skiplist buffer.
//
// Go's LevelDB considers the memdb functionality to be useful in its own
// right, and so leveldb/memdb is a separate package that is usable without
// having to import the top-level leveldb package. That extra abstraction
// means that we need to copy to an intermediate buffer here, to reconstruct
// the complete internal key to pass to the memdb.
ikey = makeInternalKey(ikey, ukey, kind, seqNum)
mem.Set(ikey, value, nil)
}
if len(t) != 0 {
return 0, fmt.Errorf("leveldb: corrupt log file %q", filename)
}
// TODO: if mem is large enough, write it to a level-0 table and set mem = nil.
batchBuf.Reset()
}
if mem != nil && !mem.Empty() {
meta, err := d.writeLevel0Table(fs, mem)
if err != nil {
return 0, err
}
ve.newFiles = append(ve.newFiles, newFileEntry{level: 0, meta: meta})
// Strictly speaking, it's too early to delete meta.fileNum from d.pendingOutputs,
// but we are replaying the log file, which happens before Open returns, so there
// is no possibility of deleteObsoleteFiles being called concurrently here.
delete(d.pendingOutputs, meta.fileNum)
}
return maxSeqNum, nil
} | go | func (d *DB) replayLogFile(ve *versionEdit, fs db.FileSystem, filename string) (maxSeqNum uint64, err error) {
file, err := fs.Open(filename)
if err != nil {
return 0, err
}
defer file.Close()
var (
mem *memdb.MemDB
batchBuf = new(bytes.Buffer)
ikey = make(internalKey, 512)
rr = record.NewReader(file)
)
for {
r, err := rr.Next()
if err == io.EOF {
break
}
if err != nil {
return 0, err
}
_, err = io.Copy(batchBuf, r)
if err != nil {
return 0, err
}
if batchBuf.Len() < batchHeaderLen {
return 0, fmt.Errorf("leveldb: corrupt log file %q", filename)
}
b := Batch{batchBuf.Bytes()}
seqNum := b.seqNum()
seqNum1 := seqNum + uint64(b.count())
if maxSeqNum < seqNum1 {
maxSeqNum = seqNum1
}
if mem == nil {
mem = memdb.New(&d.icmpOpts)
}
t := b.iter()
for ; seqNum != seqNum1; seqNum++ {
kind, ukey, value, ok := t.next()
if !ok {
return 0, fmt.Errorf("leveldb: corrupt log file %q", filename)
}
// Convert seqNum, kind and key into an internalKey, and add that ikey/value
// pair to mem.
//
// TODO: instead of copying to an intermediate buffer (ikey), is it worth
// adding a SetTwoPartKey(db.TwoPartKey{key0, key1}, value, opts) method to
// memdb.MemDB? What effect does that have on the db.Comparer interface?
//
// The C++ LevelDB code does not need an intermediate copy because its memdb
// implementation is a private implementation detail, and copies each internal
// key component from the Batch format straight to the skiplist buffer.
//
// Go's LevelDB considers the memdb functionality to be useful in its own
// right, and so leveldb/memdb is a separate package that is usable without
// having to import the top-level leveldb package. That extra abstraction
// means that we need to copy to an intermediate buffer here, to reconstruct
// the complete internal key to pass to the memdb.
ikey = makeInternalKey(ikey, ukey, kind, seqNum)
mem.Set(ikey, value, nil)
}
if len(t) != 0 {
return 0, fmt.Errorf("leveldb: corrupt log file %q", filename)
}
// TODO: if mem is large enough, write it to a level-0 table and set mem = nil.
batchBuf.Reset()
}
if mem != nil && !mem.Empty() {
meta, err := d.writeLevel0Table(fs, mem)
if err != nil {
return 0, err
}
ve.newFiles = append(ve.newFiles, newFileEntry{level: 0, meta: meta})
// Strictly speaking, it's too early to delete meta.fileNum from d.pendingOutputs,
// but we are replaying the log file, which happens before Open returns, so there
// is no possibility of deleteObsoleteFiles being called concurrently here.
delete(d.pendingOutputs, meta.fileNum)
}
return maxSeqNum, nil
} | [
"func",
"(",
"d",
"*",
"DB",
")",
"replayLogFile",
"(",
"ve",
"*",
"versionEdit",
",",
"fs",
"db",
".",
"FileSystem",
",",
"filename",
"string",
")",
"(",
"maxSeqNum",
"uint64",
",",
"err",
"error",
")",
"{",
"file",
",",
"err",
":=",
"fs",
".",
"O... | // replayLogFile replays the edits in the named log file.
//
// d.mu must be held when calling this, but the mutex may be dropped and
// re-acquired during the course of this method. | [
"replayLogFile",
"replays",
"the",
"edits",
"in",
"the",
"named",
"log",
"file",
".",
"d",
".",
"mu",
"must",
"be",
"held",
"when",
"calling",
"this",
"but",
"the",
"mutex",
"may",
"be",
"dropped",
"and",
"re",
"-",
"acquired",
"during",
"the",
"course",... | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/leveldb.go#L358-L445 | train |
golang/leveldb | leveldb.go | makeRoomForWrite | func (d *DB) makeRoomForWrite(force bool) error {
allowDelay := !force
for {
// TODO: check any previous sticky error, if the paranoid option is set.
if allowDelay && len(d.versions.currentVersion().files[0]) > l0SlowdownWritesTrigger {
// We are getting close to hitting a hard limit on the number of
// L0 files. Rather than delaying a single write by several
// seconds when we hit the hard limit, start delaying each
// individual write by 1ms to reduce latency variance.
d.mu.Unlock()
time.Sleep(1 * time.Millisecond)
d.mu.Lock()
allowDelay = false
// TODO: how do we ensure we are still 'at the front of the writer queue'?
continue
}
if !force && d.mem.ApproximateMemoryUsage() <= d.opts.GetWriteBufferSize() {
// There is room in the current memtable.
break
}
if d.imm != nil {
// We have filled up the current memtable, but the previous
// one is still being compacted, so we wait.
d.compactionCond.Wait()
continue
}
if len(d.versions.currentVersion().files[0]) > l0StopWritesTrigger {
// There are too many level-0 files.
d.compactionCond.Wait()
continue
}
// Attempt to switch to a new memtable and trigger compaction of old
// TODO: drop and re-acquire d.mu around the I/O.
newLogNumber := d.versions.nextFileNum()
newLogFile, err := d.opts.GetFileSystem().Create(dbFilename(d.dirname, fileTypeLog, newLogNumber))
if err != nil {
return err
}
newLog := record.NewWriter(newLogFile)
if err := d.log.Close(); err != nil {
newLogFile.Close()
return err
}
if err := d.logFile.Close(); err != nil {
newLog.Close()
newLogFile.Close()
return err
}
d.logNumber, d.logFile, d.log = newLogNumber, newLogFile, newLog
d.imm, d.mem = d.mem, memdb.New(&d.icmpOpts)
force = false
d.maybeScheduleCompaction()
}
return nil
} | go | func (d *DB) makeRoomForWrite(force bool) error {
allowDelay := !force
for {
// TODO: check any previous sticky error, if the paranoid option is set.
if allowDelay && len(d.versions.currentVersion().files[0]) > l0SlowdownWritesTrigger {
// We are getting close to hitting a hard limit on the number of
// L0 files. Rather than delaying a single write by several
// seconds when we hit the hard limit, start delaying each
// individual write by 1ms to reduce latency variance.
d.mu.Unlock()
time.Sleep(1 * time.Millisecond)
d.mu.Lock()
allowDelay = false
// TODO: how do we ensure we are still 'at the front of the writer queue'?
continue
}
if !force && d.mem.ApproximateMemoryUsage() <= d.opts.GetWriteBufferSize() {
// There is room in the current memtable.
break
}
if d.imm != nil {
// We have filled up the current memtable, but the previous
// one is still being compacted, so we wait.
d.compactionCond.Wait()
continue
}
if len(d.versions.currentVersion().files[0]) > l0StopWritesTrigger {
// There are too many level-0 files.
d.compactionCond.Wait()
continue
}
// Attempt to switch to a new memtable and trigger compaction of old
// TODO: drop and re-acquire d.mu around the I/O.
newLogNumber := d.versions.nextFileNum()
newLogFile, err := d.opts.GetFileSystem().Create(dbFilename(d.dirname, fileTypeLog, newLogNumber))
if err != nil {
return err
}
newLog := record.NewWriter(newLogFile)
if err := d.log.Close(); err != nil {
newLogFile.Close()
return err
}
if err := d.logFile.Close(); err != nil {
newLog.Close()
newLogFile.Close()
return err
}
d.logNumber, d.logFile, d.log = newLogNumber, newLogFile, newLog
d.imm, d.mem = d.mem, memdb.New(&d.icmpOpts)
force = false
d.maybeScheduleCompaction()
}
return nil
} | [
"func",
"(",
"d",
"*",
"DB",
")",
"makeRoomForWrite",
"(",
"force",
"bool",
")",
"error",
"{",
"allowDelay",
":=",
"!",
"force",
"\n",
"for",
"{",
"// TODO: check any previous sticky error, if the paranoid option is set.",
"if",
"allowDelay",
"&&",
"len",
"(",
"d"... | // makeRoomForWrite ensures that there is room in d.mem for the next write.
//
// d.mu must be held when calling this, but the mutex may be dropped and
// re-acquired during the course of this method. | [
"makeRoomForWrite",
"ensures",
"that",
"there",
"is",
"room",
"in",
"d",
".",
"mem",
"for",
"the",
"next",
"write",
".",
"d",
".",
"mu",
"must",
"be",
"held",
"when",
"calling",
"this",
"but",
"the",
"mutex",
"may",
"be",
"dropped",
"and",
"re",
"-",
... | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/leveldb.go#L564-L623 | train |
golang/leveldb | leveldb.go | deleteObsoleteFiles | func (d *DB) deleteObsoleteFiles() {
liveFileNums := map[uint64]struct{}{}
for fileNum := range d.pendingOutputs {
liveFileNums[fileNum] = struct{}{}
}
d.versions.addLiveFileNums(liveFileNums)
logNumber := d.versions.logNumber
manifestFileNumber := d.versions.manifestFileNumber
// Release the d.mu lock while doing I/O.
// Note the unusual order: Unlock and then Lock.
d.mu.Unlock()
defer d.mu.Lock()
fs := d.opts.GetFileSystem()
list, err := fs.List(d.dirname)
if err != nil {
// Ignore any filesystem errors.
return
}
for _, filename := range list {
fileType, fileNum, ok := parseDBFilename(filename)
if !ok {
return
}
keep := true
switch fileType {
case fileTypeLog:
// TODO: also look at prevLogNumber?
keep = fileNum >= logNumber
case fileTypeManifest:
keep = fileNum >= manifestFileNumber
case fileTypeTable, fileTypeOldFashionedTable:
_, keep = liveFileNums[fileNum]
}
if keep {
continue
}
if fileType == fileTypeTable {
d.tableCache.evict(fileNum)
}
// Ignore any file system errors.
fs.Remove(filepath.Join(d.dirname, filename))
}
} | go | func (d *DB) deleteObsoleteFiles() {
liveFileNums := map[uint64]struct{}{}
for fileNum := range d.pendingOutputs {
liveFileNums[fileNum] = struct{}{}
}
d.versions.addLiveFileNums(liveFileNums)
logNumber := d.versions.logNumber
manifestFileNumber := d.versions.manifestFileNumber
// Release the d.mu lock while doing I/O.
// Note the unusual order: Unlock and then Lock.
d.mu.Unlock()
defer d.mu.Lock()
fs := d.opts.GetFileSystem()
list, err := fs.List(d.dirname)
if err != nil {
// Ignore any filesystem errors.
return
}
for _, filename := range list {
fileType, fileNum, ok := parseDBFilename(filename)
if !ok {
return
}
keep := true
switch fileType {
case fileTypeLog:
// TODO: also look at prevLogNumber?
keep = fileNum >= logNumber
case fileTypeManifest:
keep = fileNum >= manifestFileNumber
case fileTypeTable, fileTypeOldFashionedTable:
_, keep = liveFileNums[fileNum]
}
if keep {
continue
}
if fileType == fileTypeTable {
d.tableCache.evict(fileNum)
}
// Ignore any file system errors.
fs.Remove(filepath.Join(d.dirname, filename))
}
} | [
"func",
"(",
"d",
"*",
"DB",
")",
"deleteObsoleteFiles",
"(",
")",
"{",
"liveFileNums",
":=",
"map",
"[",
"uint64",
"]",
"struct",
"{",
"}",
"{",
"}",
"\n",
"for",
"fileNum",
":=",
"range",
"d",
".",
"pendingOutputs",
"{",
"liveFileNums",
"[",
"fileNum... | // deleteObsoleteFiles deletes those files that are no longer needed.
//
// d.mu must be held when calling this, but the mutex may be dropped and
// re-acquired during the course of this method. | [
"deleteObsoleteFiles",
"deletes",
"those",
"files",
"that",
"are",
"no",
"longer",
"needed",
".",
"d",
".",
"mu",
"must",
"be",
"held",
"when",
"calling",
"this",
"but",
"the",
"mutex",
"may",
"be",
"dropped",
"and",
"re",
"-",
"acquired",
"during",
"the",... | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/leveldb.go#L629-L673 | train |
golang/leveldb | memfs/memfs.go | New | func New() db.FileSystem {
return &fileSystem{
root: &node{
children: make(map[string]*node),
isDir: true,
},
}
} | go | func New() db.FileSystem {
return &fileSystem{
root: &node{
children: make(map[string]*node),
isDir: true,
},
}
} | [
"func",
"New",
"(",
")",
"db",
".",
"FileSystem",
"{",
"return",
"&",
"fileSystem",
"{",
"root",
":",
"&",
"node",
"{",
"children",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"node",
")",
",",
"isDir",
":",
"true",
",",
"}",
",",
"}",
"\... | // New returns a new memory-backed db.FileSystem implementation. | [
"New",
"returns",
"a",
"new",
"memory",
"-",
"backed",
"db",
".",
"FileSystem",
"implementation",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/memfs/memfs.go#L34-L41 | train |
golang/leveldb | version_edit.go | apply | func (b *bulkVersionEdit) apply(base *version, icmp db.Comparer) (*version, error) {
v := new(version)
for level := range v.files {
combined := [2][]fileMetadata{
nil,
b.added[level],
}
if base != nil {
combined[0] = base.files[level]
}
n := len(combined[0]) + len(combined[1])
if n == 0 {
continue
}
v.files[level] = make([]fileMetadata, 0, n)
dmap := b.deleted[level]
for _, ff := range combined {
for _, f := range ff {
if dmap != nil && dmap[f.fileNum] {
continue
}
v.files[level] = append(v.files[level], f)
}
}
// TODO: base.files[level] is already sorted. Instead of appending
// b.addFiles[level] to the end and sorting afterwards, it might be more
// efficient to sort b.addFiles[level] and then merge the two sorted slices.
if level == 0 {
sort.Sort(byFileNum(v.files[level]))
} else {
sort.Sort(bySmallest{v.files[level], icmp})
}
}
if err := v.checkOrdering(icmp); err != nil {
return nil, fmt.Errorf("leveldb: internal error: %v", err)
}
v.updateCompactionScore()
return v, nil
} | go | func (b *bulkVersionEdit) apply(base *version, icmp db.Comparer) (*version, error) {
v := new(version)
for level := range v.files {
combined := [2][]fileMetadata{
nil,
b.added[level],
}
if base != nil {
combined[0] = base.files[level]
}
n := len(combined[0]) + len(combined[1])
if n == 0 {
continue
}
v.files[level] = make([]fileMetadata, 0, n)
dmap := b.deleted[level]
for _, ff := range combined {
for _, f := range ff {
if dmap != nil && dmap[f.fileNum] {
continue
}
v.files[level] = append(v.files[level], f)
}
}
// TODO: base.files[level] is already sorted. Instead of appending
// b.addFiles[level] to the end and sorting afterwards, it might be more
// efficient to sort b.addFiles[level] and then merge the two sorted slices.
if level == 0 {
sort.Sort(byFileNum(v.files[level]))
} else {
sort.Sort(bySmallest{v.files[level], icmp})
}
}
if err := v.checkOrdering(icmp); err != nil {
return nil, fmt.Errorf("leveldb: internal error: %v", err)
}
v.updateCompactionScore()
return v, nil
} | [
"func",
"(",
"b",
"*",
"bulkVersionEdit",
")",
"apply",
"(",
"base",
"*",
"version",
",",
"icmp",
"db",
".",
"Comparer",
")",
"(",
"*",
"version",
",",
"error",
")",
"{",
"v",
":=",
"new",
"(",
"version",
")",
"\n",
"for",
"level",
":=",
"range",
... | // apply applies the delta b to a base version to produce a new version. The
// new version is consistent with respect to the internal key comparer icmp.
//
// base may be nil, which is equivalent to a pointer to a zero version. | [
"apply",
"applies",
"the",
"delta",
"b",
"to",
"a",
"base",
"version",
"to",
"produce",
"a",
"new",
"version",
".",
"The",
"new",
"version",
"is",
"consistent",
"with",
"respect",
"to",
"the",
"internal",
"key",
"comparer",
"icmp",
".",
"base",
"may",
"b... | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/version_edit.go#L324-L364 | train |
golang/leveldb | batch.go | Set | func (b *Batch) Set(key, value []byte) {
if len(b.data) == 0 {
b.init(len(key) + len(value) + 2*binary.MaxVarintLen64 + batchHeaderLen)
}
if b.increment() {
b.data = append(b.data, byte(internalKeyKindSet))
b.appendStr(key)
b.appendStr(value)
}
} | go | func (b *Batch) Set(key, value []byte) {
if len(b.data) == 0 {
b.init(len(key) + len(value) + 2*binary.MaxVarintLen64 + batchHeaderLen)
}
if b.increment() {
b.data = append(b.data, byte(internalKeyKindSet))
b.appendStr(key)
b.appendStr(value)
}
} | [
"func",
"(",
"b",
"*",
"Batch",
")",
"Set",
"(",
"key",
",",
"value",
"[",
"]",
"byte",
")",
"{",
"if",
"len",
"(",
"b",
".",
"data",
")",
"==",
"0",
"{",
"b",
".",
"init",
"(",
"len",
"(",
"key",
")",
"+",
"len",
"(",
"value",
")",
"+",
... | // Set adds an action to the batch that sets the key to map to the value. | [
"Set",
"adds",
"an",
"action",
"to",
"the",
"batch",
"that",
"sets",
"the",
"key",
"to",
"map",
"to",
"the",
"value",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/batch.go#L31-L40 | train |
golang/leveldb | batch.go | Delete | func (b *Batch) Delete(key []byte) {
if len(b.data) == 0 {
b.init(len(key) + binary.MaxVarintLen64 + batchHeaderLen)
}
if b.increment() {
b.data = append(b.data, byte(internalKeyKindDelete))
b.appendStr(key)
}
} | go | func (b *Batch) Delete(key []byte) {
if len(b.data) == 0 {
b.init(len(key) + binary.MaxVarintLen64 + batchHeaderLen)
}
if b.increment() {
b.data = append(b.data, byte(internalKeyKindDelete))
b.appendStr(key)
}
} | [
"func",
"(",
"b",
"*",
"Batch",
")",
"Delete",
"(",
"key",
"[",
"]",
"byte",
")",
"{",
"if",
"len",
"(",
"b",
".",
"data",
")",
"==",
"0",
"{",
"b",
".",
"init",
"(",
"len",
"(",
"key",
")",
"+",
"binary",
".",
"MaxVarintLen64",
"+",
"batchHe... | // Delete adds an action to the batch that deletes the entry for key. | [
"Delete",
"adds",
"an",
"action",
"to",
"the",
"batch",
"that",
"deletes",
"the",
"entry",
"for",
"key",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/batch.go#L43-L51 | train |
golang/leveldb | batch.go | next | func (t *batchIter) next() (kind internalKeyKind, ukey []byte, value []byte, ok bool) {
p := *t
if len(p) == 0 {
return 0, nil, nil, false
}
kind, *t = internalKeyKind(p[0]), p[1:]
if kind > internalKeyKindMax {
return 0, nil, nil, false
}
ukey, ok = t.nextStr()
if !ok {
return 0, nil, nil, false
}
if kind != internalKeyKindDelete {
value, ok = t.nextStr()
if !ok {
return 0, nil, nil, false
}
}
return kind, ukey, value, true
} | go | func (t *batchIter) next() (kind internalKeyKind, ukey []byte, value []byte, ok bool) {
p := *t
if len(p) == 0 {
return 0, nil, nil, false
}
kind, *t = internalKeyKind(p[0]), p[1:]
if kind > internalKeyKindMax {
return 0, nil, nil, false
}
ukey, ok = t.nextStr()
if !ok {
return 0, nil, nil, false
}
if kind != internalKeyKindDelete {
value, ok = t.nextStr()
if !ok {
return 0, nil, nil, false
}
}
return kind, ukey, value, true
} | [
"func",
"(",
"t",
"*",
"batchIter",
")",
"next",
"(",
")",
"(",
"kind",
"internalKeyKind",
",",
"ukey",
"[",
"]",
"byte",
",",
"value",
"[",
"]",
"byte",
",",
"ok",
"bool",
")",
"{",
"p",
":=",
"*",
"t",
"\n",
"if",
"len",
"(",
"p",
")",
"=="... | // next returns the next operation in this batch.
// The final return value is false if the batch is corrupt. | [
"next",
"returns",
"the",
"next",
"operation",
"in",
"this",
"batch",
".",
"The",
"final",
"return",
"value",
"is",
"false",
"if",
"the",
"batch",
"is",
"corrupt",
"."
] | 259d9253d71996b7778a3efb4144fe4892342b18 | https://github.com/golang/leveldb/blob/259d9253d71996b7778a3efb4144fe4892342b18/batch.go#L116-L136 | train |
chzyer/readline | rawreader_windows.go | Read | func (r *RawReader) Read(buf []byte) (int, error) {
ir := new(_INPUT_RECORD)
var read int
var err error
next:
err = kernel.ReadConsoleInputW(stdin,
uintptr(unsafe.Pointer(ir)),
1,
uintptr(unsafe.Pointer(&read)),
)
if err != nil {
return 0, err
}
if ir.EventType != EVENT_KEY {
goto next
}
ker := (*_KEY_EVENT_RECORD)(unsafe.Pointer(&ir.Event[0]))
if ker.bKeyDown == 0 { // keyup
if r.ctrlKey || r.altKey {
switch ker.wVirtualKeyCode {
case VK_RCONTROL, VK_LCONTROL:
r.ctrlKey = false
case VK_MENU: //alt
r.altKey = false
}
}
goto next
}
if ker.unicodeChar == 0 {
var target rune
switch ker.wVirtualKeyCode {
case VK_RCONTROL, VK_LCONTROL:
r.ctrlKey = true
case VK_MENU: //alt
r.altKey = true
case VK_LEFT:
target = CharBackward
case VK_RIGHT:
target = CharForward
case VK_UP:
target = CharPrev
case VK_DOWN:
target = CharNext
}
if target != 0 {
return r.write(buf, target)
}
goto next
}
char := rune(ker.unicodeChar)
if r.ctrlKey {
switch char {
case 'A':
char = CharLineStart
case 'E':
char = CharLineEnd
case 'R':
char = CharBckSearch
case 'S':
char = CharFwdSearch
}
} else if r.altKey {
switch char {
case VK_BACK:
char = CharBackspace
}
return r.writeEsc(buf, char)
}
return r.write(buf, char)
} | go | func (r *RawReader) Read(buf []byte) (int, error) {
ir := new(_INPUT_RECORD)
var read int
var err error
next:
err = kernel.ReadConsoleInputW(stdin,
uintptr(unsafe.Pointer(ir)),
1,
uintptr(unsafe.Pointer(&read)),
)
if err != nil {
return 0, err
}
if ir.EventType != EVENT_KEY {
goto next
}
ker := (*_KEY_EVENT_RECORD)(unsafe.Pointer(&ir.Event[0]))
if ker.bKeyDown == 0 { // keyup
if r.ctrlKey || r.altKey {
switch ker.wVirtualKeyCode {
case VK_RCONTROL, VK_LCONTROL:
r.ctrlKey = false
case VK_MENU: //alt
r.altKey = false
}
}
goto next
}
if ker.unicodeChar == 0 {
var target rune
switch ker.wVirtualKeyCode {
case VK_RCONTROL, VK_LCONTROL:
r.ctrlKey = true
case VK_MENU: //alt
r.altKey = true
case VK_LEFT:
target = CharBackward
case VK_RIGHT:
target = CharForward
case VK_UP:
target = CharPrev
case VK_DOWN:
target = CharNext
}
if target != 0 {
return r.write(buf, target)
}
goto next
}
char := rune(ker.unicodeChar)
if r.ctrlKey {
switch char {
case 'A':
char = CharLineStart
case 'E':
char = CharLineEnd
case 'R':
char = CharBckSearch
case 'S':
char = CharFwdSearch
}
} else if r.altKey {
switch char {
case VK_BACK:
char = CharBackspace
}
return r.writeEsc(buf, char)
}
return r.write(buf, char)
} | [
"func",
"(",
"r",
"*",
"RawReader",
")",
"Read",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"ir",
":=",
"new",
"(",
"_INPUT_RECORD",
")",
"\n",
"var",
"read",
"int",
"\n",
"var",
"err",
"error",
"\n",
"next",
":",
"e... | // only process one action in one read | [
"only",
"process",
"one",
"action",
"in",
"one",
"read"
] | 2972be24d48e78746da79ba8e24e8b488c9880de | https://github.com/chzyer/readline/blob/2972be24d48e78746da79ba8e24e8b488c9880de/rawreader_windows.go#L40-L110 | train |
chzyer/readline | example/readline-pass-strength/readline-pass-strength.go | Colorize | func Colorize(msg string, color int) string {
return ColorEscape(color) + msg + ColorResetEscape
} | go | func Colorize(msg string, color int) string {
return ColorEscape(color) + msg + ColorResetEscape
} | [
"func",
"Colorize",
"(",
"msg",
"string",
",",
"color",
"int",
")",
"string",
"{",
"return",
"ColorEscape",
"(",
"color",
")",
"+",
"msg",
"+",
"ColorResetEscape",
"\n",
"}"
] | // Colorize the msg using ANSI color escapes | [
"Colorize",
"the",
"msg",
"using",
"ANSI",
"color",
"escapes"
] | 2972be24d48e78746da79ba8e24e8b488c9880de | https://github.com/chzyer/readline/blob/2972be24d48e78746da79ba8e24e8b488c9880de/example/readline-pass-strength/readline-pass-strength.go#L47-L49 | train |
chzyer/readline | history.go | historyUpdatePath | func (o *opHistory) historyUpdatePath(path string) {
o.fdLock.Lock()
defer o.fdLock.Unlock()
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
return
}
o.fd = f
r := bufio.NewReader(o.fd)
total := 0
for ; ; total++ {
line, err := r.ReadString('\n')
if err != nil {
break
}
// ignore the empty line
line = strings.TrimSpace(line)
if len(line) == 0 {
continue
}
o.Push([]rune(line))
o.Compact()
}
if total > o.cfg.HistoryLimit {
o.rewriteLocked()
}
o.historyVer++
o.Push(nil)
return
} | go | func (o *opHistory) historyUpdatePath(path string) {
o.fdLock.Lock()
defer o.fdLock.Unlock()
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
return
}
o.fd = f
r := bufio.NewReader(o.fd)
total := 0
for ; ; total++ {
line, err := r.ReadString('\n')
if err != nil {
break
}
// ignore the empty line
line = strings.TrimSpace(line)
if len(line) == 0 {
continue
}
o.Push([]rune(line))
o.Compact()
}
if total > o.cfg.HistoryLimit {
o.rewriteLocked()
}
o.historyVer++
o.Push(nil)
return
} | [
"func",
"(",
"o",
"*",
"opHistory",
")",
"historyUpdatePath",
"(",
"path",
"string",
")",
"{",
"o",
".",
"fdLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"o",
".",
"fdLock",
".",
"Unlock",
"(",
")",
"\n",
"f",
",",
"err",
":=",
"os",
".",
"OpenFil... | // only called by newOpHistory | [
"only",
"called",
"by",
"newOpHistory"
] | 2972be24d48e78746da79ba8e24e8b488c9880de | https://github.com/chzyer/readline/blob/2972be24d48e78746da79ba8e24e8b488c9880de/history.go#L66-L95 | train |
chzyer/readline | utils_unix.go | SuspendMe | func SuspendMe() {
p, _ := os.FindProcess(os.Getppid())
p.Signal(syscall.SIGTSTP)
p, _ = os.FindProcess(os.Getpid())
p.Signal(syscall.SIGTSTP)
} | go | func SuspendMe() {
p, _ := os.FindProcess(os.Getppid())
p.Signal(syscall.SIGTSTP)
p, _ = os.FindProcess(os.Getpid())
p.Signal(syscall.SIGTSTP)
} | [
"func",
"SuspendMe",
"(",
")",
"{",
"p",
",",
"_",
":=",
"os",
".",
"FindProcess",
"(",
"os",
".",
"Getppid",
"(",
")",
")",
"\n",
"p",
".",
"Signal",
"(",
"syscall",
".",
"SIGTSTP",
")",
"\n",
"p",
",",
"_",
"=",
"os",
".",
"FindProcess",
"(",... | // SuspendMe use to send suspend signal to myself, when we in the raw mode.
// For OSX it need to send to parent's pid
// For Linux it need to send to myself | [
"SuspendMe",
"use",
"to",
"send",
"suspend",
"signal",
"to",
"myself",
"when",
"we",
"in",
"the",
"raw",
"mode",
".",
"For",
"OSX",
"it",
"need",
"to",
"send",
"to",
"parent",
"s",
"pid",
"For",
"Linux",
"it",
"need",
"to",
"send",
"to",
"myself"
] | 2972be24d48e78746da79ba8e24e8b488c9880de | https://github.com/chzyer/readline/blob/2972be24d48e78746da79ba8e24e8b488c9880de/utils_unix.go#L23-L28 | train |
chzyer/readline | example/readline-demo/readline-demo.go | listFiles | func listFiles(path string) func(string) []string {
return func(line string) []string {
names := make([]string, 0)
files, _ := ioutil.ReadDir(path)
for _, f := range files {
names = append(names, f.Name())
}
return names
}
} | go | func listFiles(path string) func(string) []string {
return func(line string) []string {
names := make([]string, 0)
files, _ := ioutil.ReadDir(path)
for _, f := range files {
names = append(names, f.Name())
}
return names
}
} | [
"func",
"listFiles",
"(",
"path",
"string",
")",
"func",
"(",
"string",
")",
"[",
"]",
"string",
"{",
"return",
"func",
"(",
"line",
"string",
")",
"[",
"]",
"string",
"{",
"names",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"fil... | // Function constructor - constructs new function for listing given directory | [
"Function",
"constructor",
"-",
"constructs",
"new",
"function",
"for",
"listing",
"given",
"directory"
] | 2972be24d48e78746da79ba8e24e8b488c9880de | https://github.com/chzyer/readline/blob/2972be24d48e78746da79ba8e24e8b488c9880de/example/readline-demo/readline-demo.go#L21-L30 | train |
chzyer/readline | terminal.go | SleepToResume | func (t *Terminal) SleepToResume() {
if !atomic.CompareAndSwapInt32(&t.sleeping, 0, 1) {
return
}
defer atomic.StoreInt32(&t.sleeping, 0)
t.ExitRawMode()
ch := WaitForResume()
SuspendMe()
<-ch
t.EnterRawMode()
} | go | func (t *Terminal) SleepToResume() {
if !atomic.CompareAndSwapInt32(&t.sleeping, 0, 1) {
return
}
defer atomic.StoreInt32(&t.sleeping, 0)
t.ExitRawMode()
ch := WaitForResume()
SuspendMe()
<-ch
t.EnterRawMode()
} | [
"func",
"(",
"t",
"*",
"Terminal",
")",
"SleepToResume",
"(",
")",
"{",
"if",
"!",
"atomic",
".",
"CompareAndSwapInt32",
"(",
"&",
"t",
".",
"sleeping",
",",
"0",
",",
"1",
")",
"{",
"return",
"\n",
"}",
"\n",
"defer",
"atomic",
".",
"StoreInt32",
... | // SleepToResume will sleep myself, and return only if I'm resumed. | [
"SleepToResume",
"will",
"sleep",
"myself",
"and",
"return",
"only",
"if",
"I",
"m",
"resumed",
"."
] | 2972be24d48e78746da79ba8e24e8b488c9880de | https://github.com/chzyer/readline/blob/2972be24d48e78746da79ba8e24e8b488c9880de/terminal.go#L43-L54 | train |
chzyer/readline | operation.go | SaveHistory | func (o *Operation) SaveHistory(content string) error {
return o.history.New([]rune(content))
} | go | func (o *Operation) SaveHistory(content string) error {
return o.history.New([]rune(content))
} | [
"func",
"(",
"o",
"*",
"Operation",
")",
"SaveHistory",
"(",
"content",
"string",
")",
"error",
"{",
"return",
"o",
".",
"history",
".",
"New",
"(",
"[",
"]",
"rune",
"(",
"content",
")",
")",
"\n",
"}"
] | // if err is not nil, it just mean it fail to write to file
// other things goes fine. | [
"if",
"err",
"is",
"not",
"nil",
"it",
"just",
"mean",
"it",
"fail",
"to",
"write",
"to",
"file",
"other",
"things",
"goes",
"fine",
"."
] | 2972be24d48e78746da79ba8e24e8b488c9880de | https://github.com/chzyer/readline/blob/2972be24d48e78746da79ba8e24e8b488c9880de/operation.go#L493-L495 | train |
chzyer/readline | std.go | getInstance | func getInstance() *Instance {
stdOnce.Do(func() {
std, _ = NewEx(&Config{
DisableAutoSaveHistory: true,
})
})
return std
} | go | func getInstance() *Instance {
stdOnce.Do(func() {
std, _ = NewEx(&Config{
DisableAutoSaveHistory: true,
})
})
return std
} | [
"func",
"getInstance",
"(",
")",
"*",
"Instance",
"{",
"stdOnce",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"std",
",",
"_",
"=",
"NewEx",
"(",
"&",
"Config",
"{",
"DisableAutoSaveHistory",
":",
"true",
",",
"}",
")",
"\n",
"}",
")",
"\n",
"return",
... | // global instance will not submit history automatic | [
"global",
"instance",
"will",
"not",
"submit",
"history",
"automatic"
] | 2972be24d48e78746da79ba8e24e8b488c9880de | https://github.com/chzyer/readline/blob/2972be24d48e78746da79ba8e24e8b488c9880de/std.go#L22-L29 | train |
chzyer/readline | std.go | SetHistoryPath | func SetHistoryPath(fp string) {
ins := getInstance()
cfg := ins.Config.Clone()
cfg.HistoryFile = fp
ins.SetConfig(cfg)
} | go | func SetHistoryPath(fp string) {
ins := getInstance()
cfg := ins.Config.Clone()
cfg.HistoryFile = fp
ins.SetConfig(cfg)
} | [
"func",
"SetHistoryPath",
"(",
"fp",
"string",
")",
"{",
"ins",
":=",
"getInstance",
"(",
")",
"\n",
"cfg",
":=",
"ins",
".",
"Config",
".",
"Clone",
"(",
")",
"\n",
"cfg",
".",
"HistoryFile",
"=",
"fp",
"\n",
"ins",
".",
"SetConfig",
"(",
"cfg",
"... | // let readline load history from filepath
// and try to persist history into disk
// set fp to "" to prevent readline persisting history to disk
// so the `AddHistory` will return nil error forever. | [
"let",
"readline",
"load",
"history",
"from",
"filepath",
"and",
"try",
"to",
"persist",
"history",
"into",
"disk",
"set",
"fp",
"to",
"to",
"prevent",
"readline",
"persisting",
"history",
"to",
"disk",
"so",
"the",
"AddHistory",
"will",
"return",
"nil",
"er... | 2972be24d48e78746da79ba8e24e8b488c9880de | https://github.com/chzyer/readline/blob/2972be24d48e78746da79ba8e24e8b488c9880de/std.go#L35-L40 | train |
chzyer/readline | std.go | SetAutoComplete | func SetAutoComplete(completer AutoCompleter) {
ins := getInstance()
cfg := ins.Config.Clone()
cfg.AutoComplete = completer
ins.SetConfig(cfg)
} | go | func SetAutoComplete(completer AutoCompleter) {
ins := getInstance()
cfg := ins.Config.Clone()
cfg.AutoComplete = completer
ins.SetConfig(cfg)
} | [
"func",
"SetAutoComplete",
"(",
"completer",
"AutoCompleter",
")",
"{",
"ins",
":=",
"getInstance",
"(",
")",
"\n",
"cfg",
":=",
"ins",
".",
"Config",
".",
"Clone",
"(",
")",
"\n",
"cfg",
".",
"AutoComplete",
"=",
"completer",
"\n",
"ins",
".",
"SetConfi... | // set auto completer to global instance | [
"set",
"auto",
"completer",
"to",
"global",
"instance"
] | 2972be24d48e78746da79ba8e24e8b488c9880de | https://github.com/chzyer/readline/blob/2972be24d48e78746da79ba8e24e8b488c9880de/std.go#L43-L48 | train |
chzyer/readline | std.go | Line | func Line(prompt string) (string, error) {
ins := getInstance()
ins.SetPrompt(prompt)
return ins.Readline()
} | go | func Line(prompt string) (string, error) {
ins := getInstance()
ins.SetPrompt(prompt)
return ins.Readline()
} | [
"func",
"Line",
"(",
"prompt",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"ins",
":=",
"getInstance",
"(",
")",
"\n",
"ins",
".",
"SetPrompt",
"(",
"prompt",
")",
"\n",
"return",
"ins",
".",
"Readline",
"(",
")",
"\n",
"}"
] | // readline with global configs | [
"readline",
"with",
"global",
"configs"
] | 2972be24d48e78746da79ba8e24e8b488c9880de | https://github.com/chzyer/readline/blob/2972be24d48e78746da79ba8e24e8b488c9880de/std.go#L63-L67 | train |
chzyer/readline | std.go | NewFillableStdin | func NewFillableStdin(stdin io.Reader) (io.ReadCloser, io.Writer) {
r, w := io.Pipe()
s := &FillableStdin{
stdinBuffer: r,
stdin: stdin,
}
s.ioloop()
return s, w
} | go | func NewFillableStdin(stdin io.Reader) (io.ReadCloser, io.Writer) {
r, w := io.Pipe()
s := &FillableStdin{
stdinBuffer: r,
stdin: stdin,
}
s.ioloop()
return s, w
} | [
"func",
"NewFillableStdin",
"(",
"stdin",
"io",
".",
"Reader",
")",
"(",
"io",
".",
"ReadCloser",
",",
"io",
".",
"Writer",
")",
"{",
"r",
",",
"w",
":=",
"io",
".",
"Pipe",
"(",
")",
"\n",
"s",
":=",
"&",
"FillableStdin",
"{",
"stdinBuffer",
":",
... | // NewFillableStdin gives you FillableStdin | [
"NewFillableStdin",
"gives",
"you",
"FillableStdin"
] | 2972be24d48e78746da79ba8e24e8b488c9880de | https://github.com/chzyer/readline/blob/2972be24d48e78746da79ba8e24e8b488c9880de/std.go#L146-L154 | train |
chzyer/readline | std.go | Read | func (s *FillableStdin) Read(p []byte) (n int, err error) {
s.Lock()
i := len(s.buf)
if len(p) < i {
i = len(p)
}
if i > 0 {
n := copy(p, s.buf)
s.buf = s.buf[:0]
cerr := s.bufErr
s.bufErr = nil
s.Unlock()
return n, cerr
}
s.Unlock()
n, err = s.stdin.Read(p)
return n, err
} | go | func (s *FillableStdin) Read(p []byte) (n int, err error) {
s.Lock()
i := len(s.buf)
if len(p) < i {
i = len(p)
}
if i > 0 {
n := copy(p, s.buf)
s.buf = s.buf[:0]
cerr := s.bufErr
s.bufErr = nil
s.Unlock()
return n, cerr
}
s.Unlock()
n, err = s.stdin.Read(p)
return n, err
} | [
"func",
"(",
"s",
"*",
"FillableStdin",
")",
"Read",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"s",
".",
"Lock",
"(",
")",
"\n",
"i",
":=",
"len",
"(",
"s",
".",
"buf",
")",
"\n",
"if",
"len",
"(",
"... | // Read will read from the local buffer and if no data, read from stdin | [
"Read",
"will",
"read",
"from",
"the",
"local",
"buffer",
"and",
"if",
"no",
"data",
"read",
"from",
"stdin"
] | 2972be24d48e78746da79ba8e24e8b488c9880de | https://github.com/chzyer/readline/blob/2972be24d48e78746da79ba8e24e8b488c9880de/std.go#L175-L192 | train |
chzyer/readline | runes.go | IndexAll | func (rs Runes) IndexAll(r, sub []rune) int {
return rs.IndexAllEx(r, sub, false)
} | go | func (rs Runes) IndexAll(r, sub []rune) int {
return rs.IndexAllEx(r, sub, false)
} | [
"func",
"(",
"rs",
"Runes",
")",
"IndexAll",
"(",
"r",
",",
"sub",
"[",
"]",
"rune",
")",
"int",
"{",
"return",
"rs",
".",
"IndexAllEx",
"(",
"r",
",",
"sub",
",",
"false",
")",
"\n",
"}"
] | // Search in runes from front to end | [
"Search",
"in",
"runes",
"from",
"front",
"to",
"end"
] | 2972be24d48e78746da79ba8e24e8b488c9880de | https://github.com/chzyer/readline/blob/2972be24d48e78746da79ba8e24e8b488c9880de/runes.go#L84-L86 | train |
chzyer/readline | utils.go | WaitForResume | func WaitForResume() chan struct{} {
ch := make(chan struct{})
var wg sync.WaitGroup
wg.Add(1)
go func() {
ticker := time.NewTicker(10 * time.Millisecond)
t := time.Now()
wg.Done()
for {
now := <-ticker.C
if now.Sub(t) > 100*time.Millisecond {
break
}
t = now
}
ticker.Stop()
ch <- struct{}{}
}()
wg.Wait()
return ch
} | go | func WaitForResume() chan struct{} {
ch := make(chan struct{})
var wg sync.WaitGroup
wg.Add(1)
go func() {
ticker := time.NewTicker(10 * time.Millisecond)
t := time.Now()
wg.Done()
for {
now := <-ticker.C
if now.Sub(t) > 100*time.Millisecond {
break
}
t = now
}
ticker.Stop()
ch <- struct{}{}
}()
wg.Wait()
return ch
} | [
"func",
"WaitForResume",
"(",
")",
"chan",
"struct",
"{",
"}",
"{",
"ch",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",... | // WaitForResume need to call before current process got suspend.
// It will run a ticker until a long duration is occurs,
// which means this process is resumed. | [
"WaitForResume",
"need",
"to",
"call",
"before",
"current",
"process",
"got",
"suspend",
".",
"It",
"will",
"run",
"a",
"ticker",
"until",
"a",
"long",
"duration",
"is",
"occurs",
"which",
"means",
"this",
"process",
"is",
"resumed",
"."
] | 2972be24d48e78746da79ba8e24e8b488c9880de | https://github.com/chzyer/readline/blob/2972be24d48e78746da79ba8e24e8b488c9880de/utils.go#L59-L79 | train |
chzyer/readline | utils.go | escapeExKey | func escapeExKey(key *escapeKeyPair) rune {
var r rune
switch key.typ {
case 'D':
r = CharBackward
case 'C':
r = CharForward
case 'A':
r = CharPrev
case 'B':
r = CharNext
case 'H':
r = CharLineStart
case 'F':
r = CharLineEnd
case '~':
if key.attr == "3" {
r = CharDelete
}
default:
}
return r
} | go | func escapeExKey(key *escapeKeyPair) rune {
var r rune
switch key.typ {
case 'D':
r = CharBackward
case 'C':
r = CharForward
case 'A':
r = CharPrev
case 'B':
r = CharNext
case 'H':
r = CharLineStart
case 'F':
r = CharLineEnd
case '~':
if key.attr == "3" {
r = CharDelete
}
default:
}
return r
} | [
"func",
"escapeExKey",
"(",
"key",
"*",
"escapeKeyPair",
")",
"rune",
"{",
"var",
"r",
"rune",
"\n",
"switch",
"key",
".",
"typ",
"{",
"case",
"'D'",
":",
"r",
"=",
"CharBackward",
"\n",
"case",
"'C'",
":",
"r",
"=",
"CharForward",
"\n",
"case",
"'A'... | // translate Esc[X | [
"translate",
"Esc",
"[",
"X"
] | 2972be24d48e78746da79ba8e24e8b488c9880de | https://github.com/chzyer/readline/blob/2972be24d48e78746da79ba8e24e8b488c9880de/utils.go#L100-L122 | train |
chzyer/readline | utils.go | escapeKey | func escapeKey(r rune, reader *bufio.Reader) rune {
switch r {
case 'b':
r = MetaBackward
case 'f':
r = MetaForward
case 'd':
r = MetaDelete
case CharTranspose:
r = MetaTranspose
case CharBackspace:
r = MetaBackspace
case 'O':
d, _, _ := reader.ReadRune()
switch d {
case 'H':
r = CharLineStart
case 'F':
r = CharLineEnd
default:
reader.UnreadRune()
}
case CharEsc:
}
return r
} | go | func escapeKey(r rune, reader *bufio.Reader) rune {
switch r {
case 'b':
r = MetaBackward
case 'f':
r = MetaForward
case 'd':
r = MetaDelete
case CharTranspose:
r = MetaTranspose
case CharBackspace:
r = MetaBackspace
case 'O':
d, _, _ := reader.ReadRune()
switch d {
case 'H':
r = CharLineStart
case 'F':
r = CharLineEnd
default:
reader.UnreadRune()
}
case CharEsc:
}
return r
} | [
"func",
"escapeKey",
"(",
"r",
"rune",
",",
"reader",
"*",
"bufio",
".",
"Reader",
")",
"rune",
"{",
"switch",
"r",
"{",
"case",
"'b'",
":",
"r",
"=",
"MetaBackward",
"\n",
"case",
"'f'",
":",
"r",
"=",
"MetaForward",
"\n",
"case",
"'d'",
":",
"r",... | // translate EscX to Meta+X | [
"translate",
"EscX",
"to",
"Meta",
"+",
"X"
] | 2972be24d48e78746da79ba8e24e8b488c9880de | https://github.com/chzyer/readline/blob/2972be24d48e78746da79ba8e24e8b488c9880de/utils.go#L163-L189 | train |
chzyer/readline | utils.go | LineCount | func LineCount(screenWidth, w int) int {
r := w / screenWidth
if w%screenWidth != 0 {
r++
}
return r
} | go | func LineCount(screenWidth, w int) int {
r := w / screenWidth
if w%screenWidth != 0 {
r++
}
return r
} | [
"func",
"LineCount",
"(",
"screenWidth",
",",
"w",
"int",
")",
"int",
"{",
"r",
":=",
"w",
"/",
"screenWidth",
"\n",
"if",
"w",
"%",
"screenWidth",
"!=",
"0",
"{",
"r",
"++",
"\n",
"}",
"\n",
"return",
"r",
"\n",
"}"
] | // calculate how many lines for N character | [
"calculate",
"how",
"many",
"lines",
"for",
"N",
"character"
] | 2972be24d48e78746da79ba8e24e8b488c9880de | https://github.com/chzyer/readline/blob/2972be24d48e78746da79ba8e24e8b488c9880de/utils.go#L210-L216 | train |
chzyer/readline | utils.go | Debug | func Debug(o ...interface{}) {
f, _ := os.OpenFile("debug.tmp", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
fmt.Fprintln(f, o...)
f.Close()
} | go | func Debug(o ...interface{}) {
f, _ := os.OpenFile("debug.tmp", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
fmt.Fprintln(f, o...)
f.Close()
} | [
"func",
"Debug",
"(",
"o",
"...",
"interface",
"{",
"}",
")",
"{",
"f",
",",
"_",
":=",
"os",
".",
"OpenFile",
"(",
"\"",
"\"",
",",
"os",
".",
"O_RDWR",
"|",
"os",
".",
"O_CREATE",
"|",
"os",
".",
"O_APPEND",
",",
"0666",
")",
"\n",
"fmt",
"... | // append log info to another file | [
"append",
"log",
"info",
"to",
"another",
"file"
] | 2972be24d48e78746da79ba8e24e8b488c9880de | https://github.com/chzyer/readline/blob/2972be24d48e78746da79ba8e24e8b488c9880de/utils.go#L273-L277 | train |
hoisie/web | web.go | SetCookie | func (ctx *Context) SetCookie(cookie *http.Cookie) {
ctx.SetHeader("Set-Cookie", cookie.String(), false)
} | go | func (ctx *Context) SetCookie(cookie *http.Cookie) {
ctx.SetHeader("Set-Cookie", cookie.String(), false)
} | [
"func",
"(",
"ctx",
"*",
"Context",
")",
"SetCookie",
"(",
"cookie",
"*",
"http",
".",
"Cookie",
")",
"{",
"ctx",
".",
"SetHeader",
"(",
"\"",
"\"",
",",
"cookie",
".",
"String",
"(",
")",
",",
"false",
")",
"\n",
"}"
] | // SetCookie adds a cookie header to the response. | [
"SetCookie",
"adds",
"a",
"cookie",
"header",
"to",
"the",
"response",
"."
] | a498c022b2c0babab2bf9c0400754190b24c8c39 | https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/web.go#L108-L110 | train |
hoisie/web | web.go | Process | func Process(c http.ResponseWriter, req *http.Request) {
mainServer.Process(c, req)
} | go | func Process(c http.ResponseWriter, req *http.Request) {
mainServer.Process(c, req)
} | [
"func",
"Process",
"(",
"c",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"mainServer",
".",
"Process",
"(",
"c",
",",
"req",
")",
"\n",
"}"
] | // Process invokes the main server's routing system. | [
"Process",
"invokes",
"the",
"main",
"server",
"s",
"routing",
"system",
"."
] | a498c022b2c0babab2bf9c0400754190b24c8c39 | https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/web.go#L136-L138 | train |
hoisie/web | web.go | RunTLS | func RunTLS(addr string, config *tls.Config) {
mainServer.RunTLS(addr, config)
} | go | func RunTLS(addr string, config *tls.Config) {
mainServer.RunTLS(addr, config)
} | [
"func",
"RunTLS",
"(",
"addr",
"string",
",",
"config",
"*",
"tls",
".",
"Config",
")",
"{",
"mainServer",
".",
"RunTLS",
"(",
"addr",
",",
"config",
")",
"\n",
"}"
] | // RunTLS starts the web application and serves HTTPS requests for the main server. | [
"RunTLS",
"starts",
"the",
"web",
"application",
"and",
"serves",
"HTTPS",
"requests",
"for",
"the",
"main",
"server",
"."
] | a498c022b2c0babab2bf9c0400754190b24c8c39 | https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/web.go#L146-L148 | train |
hoisie/web | web.go | Match | func Match(method string, route string, handler interface{}) {
mainServer.addRoute(route, method, handler)
} | go | func Match(method string, route string, handler interface{}) {
mainServer.addRoute(route, method, handler)
} | [
"func",
"Match",
"(",
"method",
"string",
",",
"route",
"string",
",",
"handler",
"interface",
"{",
"}",
")",
"{",
"mainServer",
".",
"addRoute",
"(",
"route",
",",
"method",
",",
"handler",
")",
"\n",
"}"
] | // Match adds a handler for an arbitrary http method in the main server. | [
"Match",
"adds",
"a",
"handler",
"for",
"an",
"arbitrary",
"http",
"method",
"in",
"the",
"main",
"server",
"."
] | a498c022b2c0babab2bf9c0400754190b24c8c39 | https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/web.go#L186-L188 | train |
hoisie/web | server.go | ServeHTTP | func (s *Server) ServeHTTP(c http.ResponseWriter, req *http.Request) {
s.Process(c, req)
} | go | func (s *Server) ServeHTTP(c http.ResponseWriter, req *http.Request) {
s.Process(c, req)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"ServeHTTP",
"(",
"c",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"s",
".",
"Process",
"(",
"c",
",",
"req",
")",
"\n",
"}"
] | // ServeHTTP is the interface method for Go's http server package | [
"ServeHTTP",
"is",
"the",
"interface",
"method",
"for",
"Go",
"s",
"http",
"server",
"package"
] | a498c022b2c0babab2bf9c0400754190b24c8c39 | https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/server.go#L97-L99 | 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.