repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqltypes/sqltypes.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqltypes/sqltypes.go#L125-L168
go
train
// UnmarshalBinary helps implement BinaryUnmarshaler interface for Value.
func (v *Value) UnmarshalBinary(data []byte) error
// UnmarshalBinary helps implement BinaryUnmarshaler interface for Value. func (v *Value) UnmarshalBinary(data []byte) error
{ reader := bytes.NewReader(data) b, err := reader.ReadByte() if err != nil { return err } typ := ValueType(b) if typ == NullType { *v = Value{} return nil } length, err := binary.ReadUvarint(reader) if err != nil { return err } raw := make([]byte, length) n, err := reader.Read(raw) if err != nil { return err } if uint64(n) != length { return errors.Newf("Not enough bytes to read Value") } switch typ { case NumericType: *v = Value{Numeric(raw)} case FractionalType: *v = Value{Fractional(raw)} case StringType: *v = Value{String{raw, false}} case UTF8StringType: *v = Value{String{raw, true}} default: return errors.Newf("Unknown type %d", int(typ)) } return nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqltypes/sqltypes.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqltypes/sqltypes.go#L268-L292
go
train
// ConverAssignRowNullable is the same as ConvertAssignRow except that it allows // nil as a value for the row or any of the row values. In thoses cases, the // corresponding values are ignored.
func ConvertAssignRowNullable(row []Value, dest ...interface{}) error
// ConverAssignRowNullable is the same as ConvertAssignRow except that it allows // nil as a value for the row or any of the row values. In thoses cases, the // corresponding values are ignored. func ConvertAssignRowNullable(row []Value, dest ...interface{}) error
{ if len(row) != len(dest) { return errors.Newf( "# of row entries %d does not match # of destinations %d", len(row), len(dest)) } if row == nil { return nil } for i := 0; i < len(row); i++ { if row[i].IsNull() { continue } err := ConvertAssign(row[i], dest[i]) if err != nil { return err } } return nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqltypes/sqltypes.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqltypes/sqltypes.go#L301-L317
go
train
// ConvertAssignRow copies a row of values in the list of destinations. An // error is returned if any one of the row's element coping is done between // incompatible value and dest types. The list of destinations must contain // pointers. // Note that for anything else than *[]byte the value is copied, however if // the destination is of type *[]byte it will point the same []byte array as // the source (no copying).
func ConvertAssignRow(row []Value, dest ...interface{}) error
// ConvertAssignRow copies a row of values in the list of destinations. An // error is returned if any one of the row's element coping is done between // incompatible value and dest types. The list of destinations must contain // pointers. // Note that for anything else than *[]byte the value is copied, however if // the destination is of type *[]byte it will point the same []byte array as // the source (no copying). func ConvertAssignRow(row []Value, dest ...interface{}) error
{ if len(row) != len(dest) { return errors.Newf( "# of row entries %d does not match # of destinations %d", len(row), len(dest)) } for i := 0; i < len(row); i++ { err := ConvertAssign(row[i], dest[i]) if err != nil { return err } } return nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqltypes/sqltypes.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqltypes/sqltypes.go#L324-L417
go
train
// ConvertAssign copies to the '*dest' the value in 'src'. An error is returned // if the coping is done between incompatible Value and dest types. 'dest' must be // a pointer type. // Note that for anything else than *[]byte the value is copied, however if 'dest' // is of type *[]byte it will point to same []byte array as 'src.Raw()' (no copying).
func ConvertAssign(src Value, dest interface{}) error
// ConvertAssign copies to the '*dest' the value in 'src'. An error is returned // if the coping is done between incompatible Value and dest types. 'dest' must be // a pointer type. // Note that for anything else than *[]byte the value is copied, however if 'dest' // is of type *[]byte it will point to same []byte array as 'src.Raw()' (no copying). func ConvertAssign(src Value, dest interface{}) error
{ // TODO(zviad): reflecting might be too slow so common cases // can probably be handled without reflections var s String var n Numeric var f Fractional var ok bool var err error if src.Inner == nil { return errors.Newf("source is null") } switch d := dest.(type) { case *string: if s, ok = src.Inner.(String); !ok { return errors.Newf("source: '%v' is not String", src) } *d = string(s.raw()) return nil case *[]byte: if s, ok = src.Inner.(String); !ok { return errors.Newf("source: '%v' is not String", src) } *d = s.raw() return nil // TODO(zviad): figure out how to do this without reflections // because I think reflections are slow? //case *int, *int8, *int16, *int32, *int64: // if n, ok := src.Inner.(Numeric); !ok { // return errors.Newf("source: %v is not Numeric", src) // } // if i64, err := strconv.ParseInt(string(n.raw()), 10, 64); err != nil { // return err // } // *d = i64 // return nil } dpv := reflect.ValueOf(dest) if dpv.Kind() != reflect.Ptr { return errors.Newf("destination not a pointer") } if dpv.IsNil() { return errors.Newf("destination pointer is Nil") } dv := reflect.Indirect(dpv) switch dv.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if n, ok = src.Inner.(Numeric); !ok { return errors.Newf("source: '%v' is not Numeric", src) } var i64 int64 if i64, err = strconv.ParseInt(string(n.raw()), 10, dv.Type().Bits()); err != nil { return err } dv.SetInt(i64) return nil case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: if n, ok = src.Inner.(Numeric); !ok { return errors.Newf("source: '%v' is not Numeric", src) } var u64 uint64 if u64, err = strconv.ParseUint(string(n.raw()), 10, dv.Type().Bits()); err != nil { return err } dv.SetUint(u64) return nil case reflect.Float32, reflect.Float64: if f, ok = src.Inner.(Fractional); !ok { return errors.Newf("source: '%v' is not Fractional", src) } var f64 float64 if f64, err = strconv.ParseFloat(string(f.raw()), dv.Type().Bits()); err != nil { return err } dv.SetFloat(f64) return nil case reflect.Bool: // treat bool as true if non-zero integer if n, ok = src.Inner.(Numeric); !ok { return errors.Newf("source: '%v' is not Numeric", src) } var i64 int64 if i64, err = strconv.ParseInt(string(n.raw()), 10, 64); err != nil { return err } dv.SetBool(i64 != 0) return nil } return errors.Newf("unsupported destination type: %v", dest) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqltypes/sqltypes.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqltypes/sqltypes.go#L420-L430
go
train
// ConvertAssign, but with support for default values
func ConvertAssignDefault(src Value, dest interface{}, defaultValue interface{}) error
// ConvertAssign, but with support for default values func ConvertAssignDefault(src Value, dest interface{}, defaultValue interface{}) error
{ if src.IsNull() { // This is not the most efficient way of doing things, but it's certainly cleaner v, err := BuildValue(defaultValue) if err != nil { return err } return ConvertAssign(v, dest) } return ConvertAssign(src, dest) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqltypes/sqltypes.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqltypes/sqltypes.go#L435-L450
go
train
// BuildNumeric builds a Numeric type that represents any whole number. // It normalizes the representation to ensure 1:1 mapping between the // number and its representation.
func BuildNumeric(val string) (n Value, err error)
// BuildNumeric builds a Numeric type that represents any whole number. // It normalizes the representation to ensure 1:1 mapping between the // number and its representation. func BuildNumeric(val string) (n Value, err error)
{ if val[0] == '-' || val[0] == '+' { signed, err := strconv.ParseInt(val, 0, 64) if err != nil { return Value{}, err } n = Value{Numeric(strconv.AppendInt(nil, signed, 10))} } else { unsigned, err := strconv.ParseUint(val, 0, 64) if err != nil { return Value{}, err } n = Value{Numeric(strconv.AppendUint(nil, unsigned, 10))} } return n, nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqltypes/sqltypes.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqltypes/sqltypes.go#L555-L558
go
train
// Helper function for converting a uint64 to a string suitable for SQL.
func Uint64EncodeSql(b encoding2.BinaryWriter, num uint64)
// Helper function for converting a uint64 to a string suitable for SQL. func Uint64EncodeSql(b encoding2.BinaryWriter, num uint64)
{ numVal, _ := BuildValue(num) numVal.EncodeSql(b) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
hash2/consistent_hash.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/hash2/consistent_hash.go#L11-L32
go
train
// A simplified implementation of 32-bit murmur hash 3, which only accepts // uint32 value as data, and uses 12345 as the seed. // // See https://code.google.com/p/smhasher/wiki/MurmurHash3 for details.
func simpleMurmur32(val uint32) uint32
// A simplified implementation of 32-bit murmur hash 3, which only accepts // uint32 value as data, and uses 12345 as the seed. // // See https://code.google.com/p/smhasher/wiki/MurmurHash3 for details. func simpleMurmur32(val uint32) uint32
{ // body k := val * 0xcc9e2d51 // k = val * c1 k = (k << 15) | (k >> 17) // k = rotl32(h, 15) k *= 0x1b873593 // k *= c2 h := 12345 ^ k // seed ^ k h = (h << 13) | (h >> 19) // k = rotl32(h, 13) h = h*5 + 0xe6546b64 // finalize (NOTE: there's no tail) h = h ^ 4 // fmix32 h ^= h >> 16 h *= 0x85ebca6b h ^= h >> 13 h *= 0xc2b2ae35 h ^= h >> 16 return h }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
hash2/consistent_hash.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/hash2/consistent_hash.go#L67-L111
go
train
// ConsistentHash is a space efficient permutation-based consistent hashing function. This // implementation supports up to a maximum of (1 << 16 - 1), 65535, number // of shards. // // Implementation details: // // Unlike the standard ring-based algorithm (e.g., as described in dynamo db), // this algorithm relays on shard permutations to determine the key's shard // mapping. The idea is as follow: // 1. Assume there exist a set of shard ids, S, which contains every possible // shard ids in the universe (in this case 0 .. 65535). // 2. Now suppose, A (a subset of S), is the set of available shard ids, and we // want to find the shard mapping for key, K // 3. Use K as the pseudorandom generator's seed, and generate a random // permutation of S using variable-base permutation encoding (see // http://stackoverflow.com/questions/1506078/fast-permutation-number-permutation-mapping-algorithms // for additional details) // 4. Ignore all shard ids in the permutation that are not in set A // 5. Finally, use the first shard id as K's shard mapping. // // NOTE: Because each key generates a different permutation, the data // distribution is generally more uniform than the standard algorithm (The // standard algorithm works around this issue by adding more points to the // ring, which unfortunately uses even more memory). // // Complexity: this algorithm is O(1) in theory (because the max shard id is // known), but O(n) in practice. // // Example: // 1. Assume S = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, and A = {0, 1, 2, 3, 4}. // 2. Now suppose K = 31415 and perm(S, K) = (3, 1, 9, 4, 7, 5, 8, 2, 0, 6). // 3. After ignoring S - A, the remaining ids are (3, 1, 4, 2, 0) // 4. Therefore, the key belongs to shard 3.
func ConsistentHash(key uint64, numShards uint16) uint16
// ConsistentHash is a space efficient permutation-based consistent hashing function. This // implementation supports up to a maximum of (1 << 16 - 1), 65535, number // of shards. // // Implementation details: // // Unlike the standard ring-based algorithm (e.g., as described in dynamo db), // this algorithm relays on shard permutations to determine the key's shard // mapping. The idea is as follow: // 1. Assume there exist a set of shard ids, S, which contains every possible // shard ids in the universe (in this case 0 .. 65535). // 2. Now suppose, A (a subset of S), is the set of available shard ids, and we // want to find the shard mapping for key, K // 3. Use K as the pseudorandom generator's seed, and generate a random // permutation of S using variable-base permutation encoding (see // http://stackoverflow.com/questions/1506078/fast-permutation-number-permutation-mapping-algorithms // for additional details) // 4. Ignore all shard ids in the permutation that are not in set A // 5. Finally, use the first shard id as K's shard mapping. // // NOTE: Because each key generates a different permutation, the data // distribution is generally more uniform than the standard algorithm (The // standard algorithm works around this issue by adding more points to the // ring, which unfortunately uses even more memory). // // Complexity: this algorithm is O(1) in theory (because the max shard id is // known), but O(n) in practice. // // Example: // 1. Assume S = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, and A = {0, 1, 2, 3, 4}. // 2. Now suppose K = 31415 and perm(S, K) = (3, 1, 9, 4, 7, 5, 8, 2, 0, 6). // 3. After ignoring S - A, the remaining ids are (3, 1, 4, 2, 0) // 4. Therefore, the key belongs to shard 3. func ConsistentHash(key uint64, numShards uint16) uint16
{ if numShards < 2 { return 0 } hash := uint32(key) ^ uint32(key>>32) var lowestPositionShard uint16 = 0 var minPosition uint16 = maxNumShards selectLowestPositionShard := func(shard, pos uint16) { pos %= maxNumShards - shard if pos < minPosition { lowestPositionShard = shard minPosition = pos } } numBlocks := numShards >> 1 for i := uint16(0); i < numBlocks; i++ { // Each hash can generate 2 permutation positions. Implementation // note: we can replace murmur hash with any other pseudorandom // generator, as long as it's sufficiently "random". hash = simpleMurmur32(hash) shard := i << 1 selectLowestPositionShard(shard, uint16(hash)) if minPosition == 0 { return lowestPositionShard } selectLowestPositionShard(shard+1, uint16(hash>>16)) if minPosition == 0 { return lowestPositionShard } } if (numShards & 0x1) == 1 { hash = simpleMurmur32(hash) selectLowestPositionShard(numShards-1, uint16(hash)) } return lowestPositionShard }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
container/bitvector/bitvector.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/container/bitvector/bitvector.go#L16-L21
go
train
// NewBitVector creates and initializes a new bit vector with length // elements, using data as its initial contents.
func NewBitVector(data []byte, length int) *BitVector
// NewBitVector creates and initializes a new bit vector with length // elements, using data as its initial contents. func NewBitVector(data []byte, length int) *BitVector
{ return &BitVector{ data: data, length: length, } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
container/bitvector/bitvector.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/container/bitvector/bitvector.go#L38-L47
go
train
// This function shifts a byte slice one bit lower (less significant). // bit (either 1 or 0) contains the bit to put in the most significant // position of the last byte in the slice. // This returns the bit that was shifted off of the last byte.
func shiftLower(bit byte, b []byte) byte
// This function shifts a byte slice one bit lower (less significant). // bit (either 1 or 0) contains the bit to put in the most significant // position of the last byte in the slice. // This returns the bit that was shifted off of the last byte. func shiftLower(bit byte, b []byte) byte
{ bit = bit << 7 for i := len(b) - 1; i >= 0; i-- { newByte := b[i] >> 1 newByte |= bit bit = (b[i] & 1) << 7 b[i] = newByte } return bit >> 7 }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
container/bitvector/bitvector.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/container/bitvector/bitvector.go#L53-L61
go
train
// This function shifts a byte slice one bit higher (more significant). // bit (either 1 or 0) contains the bit to put in the least significant // position of the first byte in the slice. // This returns the bit that was shifted off the last byte.
func shiftHigher(bit byte, b []byte) byte
// This function shifts a byte slice one bit higher (more significant). // bit (either 1 or 0) contains the bit to put in the least significant // position of the first byte in the slice. // This returns the bit that was shifted off the last byte. func shiftHigher(bit byte, b []byte) byte
{ for i := 0; i < len(b); i++ { newByte := b[i] << 1 newByte |= bit bit = (b[i] & 0x80) >> 7 b[i] = newByte } return bit }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
container/bitvector/bitvector.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/container/bitvector/bitvector.go#L64-L68
go
train
// Returns the minimum number of bytes needed for storing the bit vector.
func (vector *BitVector) bytesLength() int
// Returns the minimum number of bytes needed for storing the bit vector. func (vector *BitVector) bytesLength() int
{ lastBitIndex := vector.length - 1 lastByteIndex := lastBitIndex >> 3 return lastByteIndex + 1 }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
container/bitvector/bitvector.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/container/bitvector/bitvector.go#L71-L75
go
train
// Panics if the given index is not within the bounds of the bit vector.
func (vector *BitVector) indexAssert(i int)
// Panics if the given index is not within the bounds of the bit vector. func (vector *BitVector) indexAssert(i int)
{ if i < 0 || i >= vector.length { panic("Attempted to access element outside buffer") } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
container/bitvector/bitvector.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/container/bitvector/bitvector.go#L78-L99
go
train
// Append adds a bit to the end of a bit vector.
func (vector *BitVector) Append(bit byte)
// Append adds a bit to the end of a bit vector. func (vector *BitVector) Append(bit byte)
{ index := uint32(vector.length) vector.length++ if vector.bytesLength() > len(vector.data) { vector.data = append(vector.data, 0) } byteIndex := index >> 3 byteOffset := index % 8 oldByte := vector.data[byteIndex] var newByte byte if bit == 1 { newByte = oldByte | 1<<byteOffset } else { // Set all bits except the byteOffset mask := byte(^(1 << byteOffset)) newByte = oldByte & mask } vector.data[byteIndex] = newByte }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
container/bitvector/bitvector.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/container/bitvector/bitvector.go#L103-L110
go
train
// Element returns the bit in the ith index of the bit vector. // Returned value is either 1 or 0.
func (vector *BitVector) Element(i int) byte
// Element returns the bit in the ith index of the bit vector. // Returned value is either 1 or 0. func (vector *BitVector) Element(i int) byte
{ vector.indexAssert(i) byteIndex := i >> 3 byteOffset := uint32(i % 8) b := vector.data[byteIndex] // Check the offset bit return (b >> byteOffset) & 1 }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
container/bitvector/bitvector.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/container/bitvector/bitvector.go#L114-L131
go
train
// Set changes the bit in the ith index of the bit vector to the value specified in // bit.
func (vector *BitVector) Set(bit byte, index int)
// Set changes the bit in the ith index of the bit vector to the value specified in // bit. func (vector *BitVector) Set(bit byte, index int)
{ vector.indexAssert(index) byteIndex := uint32(index >> 3) byteOffset := uint32(index % 8) oldByte := vector.data[byteIndex] var newByte byte if bit == 1 { // turn on the byteOffset'th bit newByte = oldByte | 1<<byteOffset } else { // turn off the byteOffset'th bit removeMask := byte(^(1 << byteOffset)) newByte = oldByte & removeMask } vector.data[byteIndex] = newByte }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
container/bitvector/bitvector.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/container/bitvector/bitvector.go#L136-L167
go
train
// Insert inserts bit into the supplied index of the bit vector. All // bits in positions greater than or equal to index before the call will // be shifted up by one.
func (vector *BitVector) Insert(bit byte, index int)
// Insert inserts bit into the supplied index of the bit vector. All // bits in positions greater than or equal to index before the call will // be shifted up by one. func (vector *BitVector) Insert(bit byte, index int)
{ vector.indexAssert(index) vector.length++ // Append an additional byte if necessary. if vector.bytesLength() > len(vector.data) { vector.data = append(vector.data, 0) } byteIndex := uint32(index >> 3) byteOffset := uint32(index % 8) var bitToInsert byte if bit == 1 { bitToInsert = 1 << byteOffset } oldByte := vector.data[byteIndex] // This bit will need to be shifted into the next byte leftoverBit := (oldByte & 0x80) >> 7 // Make masks to pull off the bits below and above byteOffset // This mask has the byteOffset lowest bits set. bottomMask := byte((1 << byteOffset) - 1) // This mask has the 8 - byteOffset top bits set. topMask := ^bottomMask top := (oldByte & topMask) << 1 newByte := bitToInsert | (oldByte & bottomMask) | top vector.data[byteIndex] = newByte // Shift the rest of the bytes in the slice one higher, append // the leftoverBit obtained above. shiftHigher(leftoverBit, vector.data[byteIndex+1:]) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
container/bitvector/bitvector.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/container/bitvector/bitvector.go#L172-L206
go
train
// Delete removes the bit in the supplied index of the bit vector. All // bits in positions greater than or equal to index before the call will // be shifted down by one.
func (vector *BitVector) Delete(index int)
// Delete removes the bit in the supplied index of the bit vector. All // bits in positions greater than or equal to index before the call will // be shifted down by one. func (vector *BitVector) Delete(index int)
{ vector.indexAssert(index) vector.length-- byteIndex := uint32(index >> 3) byteOffset := uint32(index % 8) oldByte := vector.data[byteIndex] // Shift all the bytes above the byte we're modifying, return the // leftover bit to include in the byte we're modifying. bit := shiftLower(0, vector.data[byteIndex+1:]) // Modify oldByte. // At a high level, we want to select the bits above byteOffset, // and shift them down by one, removing the bit at byteOffset. // This selects the bottom bits bottomMask := byte((1 << byteOffset) - 1) // This selects the top (8 - byteOffset - 1) bits topMask := byte(^((1 << (byteOffset + 1)) - 1)) // newTop is the top bits, shifted down one, combined with the leftover bit from shifting // the other bytes. newTop := (oldByte&topMask)>>1 | (bit << 7) // newByte takes the bottom bits and combines with the new top. newByte := (bottomMask & oldByte) | newTop vector.data[byteIndex] = newByte // The desired length is the byte index of the last element plus one, // where the byte index of the last element is the bit index of the last // element divided by 8. byteLength := vector.bytesLength() if byteLength < len(vector.data) { vector.data = vector.data[:byteLength] } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L23-L25
go
train
// Less reports whether the element with // index i should sort before the element with index j in the UintSlice.
func (s UintSlice) Less(i, j int) bool
// Less reports whether the element with // index i should sort before the element with index j in the UintSlice. func (s UintSlice) Less(i, j int) bool
{ return s[i] < s[j] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L28-L30
go
train
// Swap swaps the positions of the elements indices i and j of the UintSlice.
func (s UintSlice) Swap(i, j int)
// Swap swaps the positions of the elements indices i and j of the UintSlice. func (s UintSlice) Swap(i, j int)
{ s[i], s[j] = s[j], s[i] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L89-L91
go
train
// Less reports whether the element with // index i should sort before the element with index j in the Uint32Slice.
func (s Uint32Slice) Less(i, j int) bool
// Less reports whether the element with // index i should sort before the element with index j in the Uint32Slice. func (s Uint32Slice) Less(i, j int) bool
{ return s[i] < s[j] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L94-L96
go
train
// Swap swaps the positions of the elements indices i and j of the Uint32Slice.
func (s Uint32Slice) Swap(i, j int)
// Swap swaps the positions of the elements indices i and j of the Uint32Slice. func (s Uint32Slice) Swap(i, j int)
{ s[i], s[j] = s[j], s[i] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L122-L124
go
train
// Less reports whether the element with // index i should sort before the element with index j in the Uint16Slice.
func (s Uint16Slice) Less(i, j int) bool
// Less reports whether the element with // index i should sort before the element with index j in the Uint16Slice. func (s Uint16Slice) Less(i, j int) bool
{ return s[i] < s[j] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L127-L129
go
train
// Swap swaps the positions of the elements indices i and j of the Uint16Slice.
func (s Uint16Slice) Swap(i, j int)
// Swap swaps the positions of the elements indices i and j of the Uint16Slice. func (s Uint16Slice) Swap(i, j int)
{ s[i], s[j] = s[j], s[i] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L155-L157
go
train
// Less reports whether the element with // index i should sort before the element with index j in the Uint8Slice.
func (s Uint8Slice) Less(i, j int) bool
// Less reports whether the element with // index i should sort before the element with index j in the Uint8Slice. func (s Uint8Slice) Less(i, j int) bool
{ return s[i] < s[j] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L160-L162
go
train
// Swap swaps the positions of the elements indices i and j of the Uint8Slice
func (s Uint8Slice) Swap(i, j int)
// Swap swaps the positions of the elements indices i and j of the Uint8Slice func (s Uint8Slice) Swap(i, j int)
{ s[i], s[j] = s[j], s[i] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L221-L223
go
train
// Less reports whether the element with // index i should sort before the element with index j in the Int32Slice.
func (s Int32Slice) Less(i, j int) bool
// Less reports whether the element with // index i should sort before the element with index j in the Int32Slice. func (s Int32Slice) Less(i, j int) bool
{ return s[i] < s[j] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L226-L228
go
train
// Swap swaps the positions of the elements indices i and j of the Int32Slice
func (s Int32Slice) Swap(i, j int)
// Swap swaps the positions of the elements indices i and j of the Int32Slice func (s Int32Slice) Swap(i, j int)
{ s[i], s[j] = s[j], s[i] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L254-L256
go
train
// Less reports whether the element with // index i should sort before the element with index j in the Int16Slice.
func (s Int16Slice) Less(i, j int) bool
// Less reports whether the element with // index i should sort before the element with index j in the Int16Slice. func (s Int16Slice) Less(i, j int) bool
{ return s[i] < s[j] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L259-L261
go
train
// Swap swaps the positions of the elements indices i and j of the Int16Slice.
func (s Int16Slice) Swap(i, j int)
// Swap swaps the positions of the elements indices i and j of the Int16Slice. func (s Int16Slice) Swap(i, j int)
{ s[i], s[j] = s[j], s[i] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L287-L289
go
train
// Less reports whether the element with // index i should sort before the element with index j in the Int8Slice.
func (s Int8Slice) Less(i, j int) bool
// Less reports whether the element with // index i should sort before the element with index j in the Int8Slice. func (s Int8Slice) Less(i, j int) bool
{ return s[i] < s[j] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L292-L294
go
train
// Swap swaps the positions of the elements indices i and j of the Int8Slice.
func (s Int8Slice) Swap(i, j int)
// Swap swaps the positions of the elements indices i and j of the Int8Slice. func (s Int8Slice) Swap(i, j int)
{ s[i], s[j] = s[j], s[i] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L320-L322
go
train
// Less reports whether the element with // index i should sort before the element with index j in the Float32Slice.
func (s Float32Slice) Less(i, j int) bool
// Less reports whether the element with // index i should sort before the element with index j in the Float32Slice. func (s Float32Slice) Less(i, j int) bool
{ return s[i] < s[j] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L325-L327
go
train
// Swap swaps the positions of the elements indices i and j of the Float32Slice.
func (s Float32Slice) Swap(i, j int)
// Swap swaps the positions of the elements indices i and j of the Float32Slice. func (s Float32Slice) Swap(i, j int)
{ s[i], s[j] = s[j], s[i] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L353-L355
go
train
// Less reports whether the element with // index i should sort before the element with index j in the Float64Slice.
func (s Float64Slice) Less(i, j int) bool
// Less reports whether the element with // index i should sort before the element with index j in the Float64Slice. func (s Float64Slice) Less(i, j int) bool
{ return s[i] < s[j] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L358-L360
go
train
// Swap swaps the positions of the elements indices i and j of the Float64Slice.
func (s Float64Slice) Swap(i, j int)
// Swap swaps the positions of the elements indices i and j of the Float64Slice. func (s Float64Slice) Swap(i, j int)
{ s[i], s[j] = s[j], s[i] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L391-L393
go
train
// Swap swaps the positions of the elements indices i and j of the ByteArraySlice.
func (s ByteArraySlice) Swap(i, j int)
// Swap swaps the positions of the elements indices i and j of the ByteArraySlice. func (s ByteArraySlice) Swap(i, j int)
{ s[i], s[j] = s[j], s[i] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L419-L421
go
train
// Less reports whether the element with // index i should sort before the element with index j in the TimeSlice.
func (s TimeSlice) Less(i, j int) bool
// Less reports whether the element with // index i should sort before the element with index j in the TimeSlice. func (s TimeSlice) Less(i, j int) bool
{ return s[i].Before(s[j]) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sort2/sort.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sort2/sort.go#L424-L426
go
train
// Swap swaps the positions of the elements indices i and j of the TimeSlice.
func (s TimeSlice) Swap(i, j int)
// Swap swaps the positions of the elements indices i and j of the TimeSlice. func (s TimeSlice) Swap(i, j int)
{ s[i], s[j] = s[j], s[i] }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/binlog/log_stream_event_reader.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/log_stream_event_reader.go#L53-L83
go
train
// This returns an EventReader which read and parses events from a (bin /relay) // log stream composed of multiple log files. If no parser is available for // the event, or if an error occurs during parsing, then the reader will // return the original event along with the error. NOTE: this reader will // transparently switch log files on rotate events (relay log wrapper events // are not returned). When the reader fails to open a log file, it will return // a *FailedToOpenFileError; it is safe to retry reading, assuming the filename // is valid. When the reader encounters an invalid rotate event, it will // return both the rotate event and an *InvalidRotationError.
func NewLogStreamV4EventReader( logDirectory string, logPrefix string, startingLogFileNum uint, isRelayLog bool, logger Logger) EventReader
// This returns an EventReader which read and parses events from a (bin /relay) // log stream composed of multiple log files. If no parser is available for // the event, or if an error occurs during parsing, then the reader will // return the original event along with the error. NOTE: this reader will // transparently switch log files on rotate events (relay log wrapper events // are not returned). When the reader fails to open a log file, it will return // a *FailedToOpenFileError; it is safe to retry reading, assuming the filename // is valid. When the reader encounters an invalid rotate event, it will // return both the rotate event and an *InvalidRotationError. func NewLogStreamV4EventReader( logDirectory string, logPrefix string, startingLogFileNum uint, isRelayLog bool, logger Logger) EventReader
{ openLogReader := func( dir string, file string, parsers V4EventParserMap) ( EventReader, error) { filePath := path.Join(dir, file) logFile, err := os.Open(filePath) if err != nil { return nil, err } return NewLogFileV4EventReader(logFile, filePath, parsers, logger), nil } return NewLogStreamV4EventReaderWithLogFileReaderCreator( logDirectory, logPrefix, startingLogFileNum, isRelayLog, logger, openLogReader) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
hash2/checksum.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/hash2/checksum.go#L20-L23
go
train
// This returns true iff the data matches the provided checksum.
func ValidateMd5Checksum(data []byte, sum []byte) bool
// This returns true iff the data matches the provided checksum. func ValidateMd5Checksum(data []byte, sum []byte) bool
{ ourSum := ComputeMd5Checksum(data) return bytes.Equal(ourSum, sum) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
executor/executor.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/executor/executor.go#L340-L345
go
train
// For testing
func (p *WorkPoolExecutor) getWorkers() []*worker
// For testing func (p *WorkPoolExecutor) getWorkers() []*worker
{ p.mutex.Lock() defer p.mutex.Unlock() return p.workers }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
executor/executor.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/executor/executor.go#L357-L362
go
train
// For testing
func (w *worker) getShouldStop() bool
// For testing func (w *worker) getShouldStop() bool
{ w.pool.mutex.Lock() defer w.pool.mutex.Unlock() return w.shouldStop }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/base_connection_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/base_connection_pool.go#L38-L70
go
train
// This returns a connection pool where all connections are connected // to the same (network, address)
func newBaseConnectionPool( options ConnectionOptions, createPool func(rp.Options) rp.ResourcePool) ConnectionPool
// This returns a connection pool where all connections are connected // to the same (network, address) func newBaseConnectionPool( options ConnectionOptions, createPool func(rp.Options) rp.ResourcePool) ConnectionPool
{ dial := options.Dial if dial == nil { dial = defaultDialFunc } openFunc := func(loc string) (interface{}, error) { network, address := parseResourceLocation(loc) return dial(network, address) } closeFunc := func(handle interface{}) error { return handle.(net.Conn).Close() } poolOptions := rp.Options{ MaxActiveHandles: options.MaxActiveConnections, MaxIdleHandles: options.MaxIdleConnections, MaxIdleTime: options.MaxIdleTime, OpenMaxConcurrency: options.DialMaxConcurrency, Open: openFunc, Close: closeFunc, NowFunc: options.NowFunc, } return &connectionPoolImpl{ options: options, pool: createPool(poolOptions), } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/base_connection_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/base_connection_pool.go#L82-L88
go
train
// This returns a connection pool that manages multiple (network, address) // entries. The connections to each (network, address) entry acts // independently. For example ("tcp", "localhost:11211") could act as memcache // shard 0 and ("tcp", "localhost:11212") could act as memcache shard 1.
func NewMultiConnectionPool(options ConnectionOptions) ConnectionPool
// This returns a connection pool that manages multiple (network, address) // entries. The connections to each (network, address) entry acts // independently. For example ("tcp", "localhost:11211") could act as memcache // shard 0 and ("tcp", "localhost:11212") could act as memcache shard 1. func NewMultiConnectionPool(options ConnectionOptions) ConnectionPool
{ return newBaseConnectionPool( options, func(poolOptions rp.Options) rp.ResourcePool { return rp.NewMultiResourcePool(poolOptions, nil) }) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/base_connection_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/base_connection_pool.go#L108-L110
go
train
// BaseConnectionPool can only register a single (network, address) entry. // Register should be call before any Get calls.
func (p *connectionPoolImpl) Register(network string, address string) error
// BaseConnectionPool can only register a single (network, address) entry. // Register should be call before any Get calls. func (p *connectionPoolImpl) Register(network string, address string) error
{ return p.pool.Register(network + " " + address) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/base_connection_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/base_connection_pool.go#L135-L144
go
train
// This gets an active connection from the connection pool. Note that network // and address arguments are ignored (The connections with point to the // network/address provided by the first Register call).
func (p *connectionPoolImpl) Get( network string, address string) (ManagedConn, error)
// This gets an active connection from the connection pool. Note that network // and address arguments are ignored (The connections with point to the // network/address provided by the first Register call). func (p *connectionPoolImpl) Get( network string, address string) (ManagedConn, error)
{ handle, err := p.pool.Get(network + " " + address) if err != nil { return nil, err } return NewManagedConn(network, address, handle, p, p.options), nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/responses.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/responses.go#L130-L137
go
train
// This creates a GetResponse from an error.
func NewGetErrorResponse(key string, err error) GetResponse
// This creates a GetResponse from an error. func NewGetErrorResponse(key string, err error) GetResponse
{ resp := &genericResponse{ err: err, allowNotFound: true, } resp.item.Key = key return resp }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/responses.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/responses.go#L140-L162
go
train
// This creates a normal GetResponse.
func NewGetResponse( key string, status ResponseStatus, flags uint32, value []byte, version uint64) GetResponse
// This creates a normal GetResponse. func NewGetResponse( key string, status ResponseStatus, flags uint32, value []byte, version uint64) GetResponse
{ resp := &genericResponse{ status: status, allowNotFound: true, } resp.item.Key = key if status == StatusNoError { if value == nil { resp.item.Value = []byte{} } else { resp.item.Value = value } resp.item.Flags = flags resp.item.DataVersionId = version } return resp }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/responses.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/responses.go#L165-L171
go
train
// This creates a MutateResponse from an error.
func NewMutateErrorResponse(key string, err error) MutateResponse
// This creates a MutateResponse from an error. func NewMutateErrorResponse(key string, err error) MutateResponse
{ resp := &genericResponse{ err: err, } resp.item.Key = key return resp }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/responses.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/responses.go#L174-L187
go
train
// This creates a normal MutateResponse.
func NewMutateResponse( key string, status ResponseStatus, version uint64) MutateResponse
// This creates a normal MutateResponse. func NewMutateResponse( key string, status ResponseStatus, version uint64) MutateResponse
{ resp := &genericResponse{ status: status, } resp.item.Key = key if status == StatusNoError { resp.item.DataVersionId = version } return resp }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/responses.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/responses.go#L190-L196
go
train
// This creates a CountResponse from an error.
func NewCountErrorResponse(key string, err error) CountResponse
// This creates a CountResponse from an error. func NewCountErrorResponse(key string, err error) CountResponse
{ resp := &genericResponse{ err: err, } resp.item.Key = key return resp }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/responses.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/responses.go#L199-L212
go
train
// This creates a normal CountResponse.
func NewCountResponse( key string, status ResponseStatus, count uint64) CountResponse
// This creates a normal CountResponse. func NewCountResponse( key string, status ResponseStatus, count uint64) CountResponse
{ resp := &genericResponse{ status: status, } resp.item.Key = key if status == StatusNoError { resp.count = count } return resp }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/responses.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/responses.go#L215-L222
go
train
// This creates a VersionResponse from an error.
func NewVersionErrorResponse( err error, versions map[int]string) VersionResponse
// This creates a VersionResponse from an error. func NewVersionErrorResponse( err error, versions map[int]string) VersionResponse
{ return &genericResponse{ err: err, versions: versions, } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/responses.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/responses.go#L225-L234
go
train
// This creates a normal VersionResponse.
func NewVersionResponse( status ResponseStatus, versions map[int]string) VersionResponse
// This creates a normal VersionResponse. func NewVersionResponse( status ResponseStatus, versions map[int]string) VersionResponse
{ resp := &genericResponse{ status: status, versions: versions, } return resp }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/responses.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/responses.go#L237-L244
go
train
// This creates a StatResponse from an error.
func NewStatErrorResponse( err error, entries map[int](map[string]string)) StatResponse
// This creates a StatResponse from an error. func NewStatErrorResponse( err error, entries map[int](map[string]string)) StatResponse
{ return &genericResponse{ err: err, statEntries: entries, } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/responses.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/responses.go#L247-L256
go
train
// This creates a normal StatResponse.
func NewStatResponse( status ResponseStatus, entries map[int](map[string]string)) StatResponse
// This creates a normal StatResponse. func NewStatResponse( status ResponseStatus, entries map[int](map[string]string)) StatResponse
{ resp := &genericResponse{ status: status, statEntries: entries, } return resp }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/base_shard_manager.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/base_shard_manager.go#L48-L59
go
train
// Initializes the BaseShardManager.
func (m *BaseShardManager) Init( shardFunc func(key string, numShard int) (shard int), logError func(err error), logInfo func(v ...interface{}), options net2.ConnectionOptions)
// Initializes the BaseShardManager. func (m *BaseShardManager) Init( shardFunc func(key string, numShard int) (shard int), logError func(err error), logInfo func(v ...interface{}), options net2.ConnectionOptions)
{ m.InitWithPool( shardFunc, logError, logInfo, net2.NewMultiConnectionPool(options)) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/base_shard_manager.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/base_shard_manager.go#L76-L103
go
train
// This updates the shard manager to use new shard states.
func (m *BaseShardManager) UpdateShardStates(shardStates []ShardState)
// This updates the shard manager to use new shard states. func (m *BaseShardManager) UpdateShardStates(shardStates []ShardState)
{ newAddrs := set.NewSet() for _, state := range shardStates { newAddrs.Add(state.Address) } m.rwMutex.Lock() defer m.rwMutex.Unlock() oldAddrs := set.NewSet() for _, state := range m.shardStates { oldAddrs.Add(state.Address) } for address := range set.Subtract(newAddrs, oldAddrs).Iter() { if err := m.pool.Register("tcp", address.(string)); err != nil { m.logError(err) } } for address := range set.Subtract(oldAddrs, newAddrs).Iter() { if err := m.pool.Unregister("tcp", address.(string)); err != nil { m.logError(err) } } m.shardStates = shardStates }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/base_shard_manager.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/base_shard_manager.go#L106-L132
go
train
// See ShardManager interface for documentation.
func (m *BaseShardManager) GetShard( key string) ( shardId int, conn net2.ManagedConn, err error)
// See ShardManager interface for documentation. func (m *BaseShardManager) GetShard( key string) ( shardId int, conn net2.ManagedConn, err error)
{ m.rwMutex.RLock() defer m.rwMutex.RUnlock() shardId = m.getShardId(key, len(m.shardStates)) if shardId == -1 { return } state := m.shardStates[shardId] if state.State != ActiveServer { m.logInfo("Memcache shard ", shardId, " is not in active state.") connSkippedByAddr.Add(state.Address, 1) return } entry := &ShardMapping{} m.fillEntryWithConnection(state.Address, entry) conn, err = entry.Connection, entry.ConnErr return }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/base_shard_manager.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/base_shard_manager.go#L135-L165
go
train
// See ShardManager interface for documentation.
func (m *BaseShardManager) GetShardsForKeys( keys []string) map[int]*ShardMapping
// See ShardManager interface for documentation. func (m *BaseShardManager) GetShardsForKeys( keys []string) map[int]*ShardMapping
{ m.rwMutex.RLock() defer m.rwMutex.RUnlock() numShards := len(m.shardStates) results := make(map[int]*ShardMapping) for _, key := range keys { shardId := m.getShardId(key, numShards) entry, inMap := results[shardId] if !inMap { entry = &ShardMapping{} if shardId != -1 { state := m.shardStates[shardId] if state.State == ActiveServer { m.fillEntryWithConnection(state.Address, entry) } else { connSkippedByAddr.Add(state.Address, 1) } } entry.Keys = make([]string, 0, 1) results[shardId] = entry } entry.Keys = append(entry.Keys, key) } return results }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/base_shard_manager.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/base_shard_manager.go#L168-L200
go
train
// See ShardManager interface for documentation.
func (m *BaseShardManager) GetShardsForItems( items []*Item) map[int]*ShardMapping
// See ShardManager interface for documentation. func (m *BaseShardManager) GetShardsForItems( items []*Item) map[int]*ShardMapping
{ m.rwMutex.RLock() defer m.rwMutex.RUnlock() numShards := len(m.shardStates) results := make(map[int]*ShardMapping) for _, item := range items { shardId := m.getShardId(item.Key, numShards) entry, inMap := results[shardId] if !inMap { entry = &ShardMapping{} if shardId != -1 { state := m.shardStates[shardId] if state.State == ActiveServer { m.fillEntryWithConnection(state.Address, entry) } else { connSkippedByAddr.Add(state.Address, 1) } } entry.Items = make([]*Item, 0, 1) entry.Keys = make([]string, 0, 1) results[shardId] = entry } entry.Items = append(entry.Items, item) entry.Keys = append(entry.Keys, item.Key) } return results }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/base_shard_manager.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/base_shard_manager.go#L203-L210
go
train
// See ShardManager interface for documentation.
func (m *BaseShardManager) GetShardsForSentinelsFromKeys( keys []string) map[int]*ShardMapping
// See ShardManager interface for documentation. func (m *BaseShardManager) GetShardsForSentinelsFromKeys( keys []string) map[int]*ShardMapping
{ m.rwMutex.RLock() defer m.rwMutex.RUnlock() return m.getShardsForSentinelsLocked(keys) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/base_shard_manager.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/base_shard_manager.go#L213-L251
go
train
// This method assumes that m.rwMutex is locked.
func (m *BaseShardManager) getShardsForSentinelsLocked( keys []string) map[int]*ShardMapping
// This method assumes that m.rwMutex is locked. func (m *BaseShardManager) getShardsForSentinelsLocked( keys []string) map[int]*ShardMapping
{ numShards := len(m.shardStates) results := make(map[int]*ShardMapping) for _, key := range keys { shardId := m.getShardId(key, numShards) entry, inMap := results[shardId] if !inMap { entry = &ShardMapping{} if shardId != -1 { state := m.shardStates[shardId] if state.State == ActiveServer || state.State == WriteOnlyServer || state.State == WarmUpServer { m.fillEntryWithConnection(state.Address, entry) // During WARM_UP state, we do try to write sentinels to // memcache but any failures are ignored. We run memcache // server in this mode for sometime to prime our memcache // and warm up memcache server. if state.State == WarmUpServer { entry.WarmingUp = true } } else { connSkippedByAddr.Add(state.Address, 1) } } entry.Keys = make([]string, 0, 1) results[shardId] = entry } entry.Keys = append(entry.Keys, key) } return results }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/base_shard_manager.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/base_shard_manager.go#L254-L280
go
train
// See ShardManager interface for documentation.
func (m *BaseShardManager) GetShardsForSentinelsFromItems( items []*Item) map[int]*ShardMapping
// See ShardManager interface for documentation. func (m *BaseShardManager) GetShardsForSentinelsFromItems( items []*Item) map[int]*ShardMapping
{ keys := make([]string, len(items)) for i, item := range items { keys[i] = item.Key } m.rwMutex.RLock() defer m.rwMutex.RUnlock() numShards := len(m.shardStates) results := m.getShardsForSentinelsLocked(keys) // Now fill in all entries with items. for _, item := range items { shardId := m.getShardId(item.Key, numShards) entry := results[shardId] if len(entry.Items) == 0 { entry.Items = make([]*Item, 0, len(entry.Keys)) } entry.Items = append(entry.Items, item) } return results }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/base_shard_manager.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/base_shard_manager.go#L283-L299
go
train
// See ShardManager interface for documentation.
func (m *BaseShardManager) GetAllShards() map[int]net2.ManagedConn
// See ShardManager interface for documentation. func (m *BaseShardManager) GetAllShards() map[int]net2.ManagedConn
{ results := make(map[int]net2.ManagedConn) m.rwMutex.RLock() defer m.rwMutex.RUnlock() for i, state := range m.shardStates { conn, err := m.pool.Get("tcp", state.Address) if err != nil { m.logError(err) conn = nil } results[i] = conn } return results }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/binlog/decoder.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/decoder.go#L21-L52
go
train
// Note: this is equivalent to net_field_length in sql-common/pack.c
func readFieldLength(valBytes []byte) ( length uint64, remaining []byte, err error)
// Note: this is equivalent to net_field_length in sql-common/pack.c func readFieldLength(valBytes []byte) ( length uint64, remaining []byte, err error)
{ if len(valBytes) == 0 { return 0, nil, errors.New("Empty field length input") } val := uint64(valBytes[0]) if val < 251 { return val, valBytes[1:], nil } else if val == 251 { return NullLength, valBytes[1:], nil } size := 9 if val == 252 { size = 3 } else if val == 253 { size = 4 } if len(valBytes) < size { return 0, nil, errors.Newf( "Invalid field length input (expected at least %d bytes)", size) } // NOTE: mysql's net_field_length implementation is somewhat broken. // In particular, when net_store_length encode a ulong using 8 bytes, // net_field_length will only read the first 4 bytes, and ignore the // rest .... return bytesToLEUint(valBytes[1:size]), valBytes[size:], nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
cinterop/buffered_work.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/cinterop/buffered_work.go#L11-L36
go
train
// this reads in a loop from socketRead putting batchSize bytes of work to copyTo until // the socketRead is empty. Will always block until a full workSize of units have been copied
func readBuffer(copyTo chan<- []byte, socketRead io.ReadCloser, batchSize int, workSize int)
// this reads in a loop from socketRead putting batchSize bytes of work to copyTo until // the socketRead is empty. Will always block until a full workSize of units have been copied func readBuffer(copyTo chan<- []byte, socketRead io.ReadCloser, batchSize int, workSize int)
{ defer close(copyTo) for { batch := make([]byte, batchSize) size, err := socketRead.Read(batch) if err == nil && workSize != 0 && size%workSize != 0 { var lsize int lsize, err = io.ReadFull( socketRead, batch[size:size+workSize-(size%workSize)]) size += lsize } if size > 0 { if err != nil && workSize != 0 { size -= (size % workSize) } copyTo <- batch[:size] } if err != nil { if err != io.EOF { log.Print("Error encountered in readBuffer:", err) } return } } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
cinterop/buffered_work.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/cinterop/buffered_work.go#L39-L51
go
train
// this simply copies data from the chan to the socketWrite writer
func writeBuffer(copyFrom <-chan []byte, socketWrite io.Writer)
// this simply copies data from the chan to the socketWrite writer func writeBuffer(copyFrom <-chan []byte, socketWrite io.Writer)
{ for buf := range copyFrom { if len(buf) > 0 { size, err := socketWrite.Write(buf) if err != nil { log.Print("Error encountered in writeBuffer:", err) return } else if size != len(buf) { panic(errors.New("Short Write: io.Writer not compliant")) } } } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
cinterop/buffered_work.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/cinterop/buffered_work.go#L55-L90
go
train
// this function takes data from socketRead and calls processBatch on a batch of it at a time // then the resulting bytes are written to wocketWrite as fast as possible
func ProcessBufferedData( socketRead io.ReadCloser, socketWrite io.Writer, // The caller must pass in a factory that returns a pair of functions. // The first processes a batch of []bytes and returns the processed bytes // The second is called with the same input and the result from the first function after // those results have been queued for streaming back to the client, // The second function makes it possible to prefetch another batch of data for the client makeProcessBatch func() ( func(input []byte) []byte, func(lastInput []byte, lastOutput []byte)), batchSize int, workItemSize int)
// this function takes data from socketRead and calls processBatch on a batch of it at a time // then the resulting bytes are written to wocketWrite as fast as possible func ProcessBufferedData( socketRead io.ReadCloser, socketWrite io.Writer, // The caller must pass in a factory that returns a pair of functions. // The first processes a batch of []bytes and returns the processed bytes // The second is called with the same input and the result from the first function after // those results have been queued for streaming back to the client, // The second function makes it possible to prefetch another batch of data for the client makeProcessBatch func() ( func(input []byte) []byte, func(lastInput []byte, lastOutput []byte)), batchSize int, workItemSize int)
{ readChan := make(chan []byte, 2) writeChan := make(chan []byte, 1+batchSize/workItemSize) go readBuffer(readChan, socketRead, batchSize, workItemSize) go writeBuffer(writeChan, socketWrite) pastInit := false defer func() { // this is if makeProcessBatch() fails if !pastInit { if r := recover(); r != nil { log.Print("Error in makeProcessBatch ", r) } } socketRead.Close() close(writeChan) }() processBatch, prefetchBatch := makeProcessBatch() pastInit = true for buf := range readChan { result := processBatch(buf) writeChan <- result prefetchBatch(buf, result) } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
time2/time2.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/time2/time2.go#L11-L13
go
train
// Convert Time to epoch seconds with subsecond precision.
func TimeToFloat(t time.Time) float64
// Convert Time to epoch seconds with subsecond precision. func TimeToFloat(t time.Time) float64
{ return float64(t.Unix()) + (float64(t.Nanosecond()) / 1e9) }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
nosync/once.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/nosync/once.go#L26-L39
go
train
// Do calls the function f if and only if Do is being called for the // first time for this instance of Once. In other words, given // var once Once // if once.Do(f) is called multiple times, only the first call will invoke f, // even if f has a different value in each invocation. A new instance of // Once is required for each function to execute. // // Do is intended for initialization that must be run exactly once. Since f // is niladic, it may be necessary to use a function literal to capture the // arguments to a function to be invoked by Do: // config.once.Do(func() { config.init(filename) }) // // If f causes Do to be called, it will panic. // // If f panics, Do considers it to have returned; future calls of Do return // without calling f. //
func (o *Once) Do(f func())
// Do calls the function f if and only if Do is being called for the // first time for this instance of Once. In other words, given // var once Once // if once.Do(f) is called multiple times, only the first call will invoke f, // even if f has a different value in each invocation. A new instance of // Once is required for each function to execute. // // Do is intended for initialization that must be run exactly once. Since f // is niladic, it may be necessary to use a function literal to capture the // arguments to a function to be invoked by Do: // config.once.Do(func() { config.init(filename) }) // // If f causes Do to be called, it will panic. // // If f panics, Do considers it to have returned; future calls of Do return // without calling f. // func (o *Once) Do(f func())
{ if o.done { return } if o.doing { panic("nosync: Do called within f") } o.doing = true defer func() { o.doing = false o.done = true }() f() }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
compiler/natives/src/time/time.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/compiler/natives/src/time/time.go#L90-L92
go
train
// indexByte is copied from strings package to avoid importing it (since the real time package doesn't).
func indexByte(s string, c byte) int
// indexByte is copied from strings package to avoid importing it (since the real time package doesn't). func indexByte(s string, c byte) int
{ return js.InternalObject(s).Call("indexOf", js.Global.Get("String").Call("fromCharCode", c)).Int() }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
nosync/mutex.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/nosync/mutex.go#L31-L36
go
train
// Lock locks m for writing. It is a run-time error if rw is already locked for reading or writing.
func (rw *RWMutex) Lock()
// Lock locks m for writing. It is a run-time error if rw is already locked for reading or writing. func (rw *RWMutex) Lock()
{ if rw.readLockCounter != 0 || rw.writeLocked { panic("nosync: mutex is already locked") } rw.writeLocked = true }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
nosync/mutex.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/nosync/mutex.go#L68-L73
go
train
// Add adds delta, which may be negative, to the WaitGroup If the counter goes negative, Add panics.
func (wg *WaitGroup) Add(delta int)
// Add adds delta, which may be negative, to the WaitGroup If the counter goes negative, Add panics. func (wg *WaitGroup) Add(delta int)
{ wg.counter += delta if wg.counter < 0 { panic("sync: negative WaitGroup counter") } }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
compiler/natives/src/sync/sync.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/compiler/natives/src/sync/sync.go#L27-L42
go
train
// SemacquireMutex is like Semacquire, but for profiling contended Mutexes. // Mutex profiling is not supported, so just use the same implementation as runtime_Semacquire. // TODO: Investigate this. If it's possible to implement, consider doing so, otherwise remove this comment.
func runtime_SemacquireMutex(s *uint32, lifo bool)
// SemacquireMutex is like Semacquire, but for profiling contended Mutexes. // Mutex profiling is not supported, so just use the same implementation as runtime_Semacquire. // TODO: Investigate this. If it's possible to implement, consider doing so, otherwise remove this comment. func runtime_SemacquireMutex(s *uint32, lifo bool)
{ if (*s - semAwoken[s]) == 0 { ch := make(chan bool) if lifo { semWaiters[s] = append([]chan bool{ch}, semWaiters[s]...) } else { semWaiters[s] = append(semWaiters[s], ch) } <-ch semAwoken[s] -= 1 if semAwoken[s] == 0 { delete(semAwoken, s) } } *s-- }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
compiler/natives/src/sync/sync.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/compiler/natives/src/sync/sync.go#L72-L75
go
train
// Copy of time.runtimeNano.
func runtime_nanotime() int64
// Copy of time.runtimeNano. func runtime_nanotime() int64
{ const millisecond = 1000000 return js.Global.Get("Date").New().Call("getTime").Int64() * millisecond }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
compiler/utils.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/compiler/utils.go#L662-L673
go
train
// formatJSStructTagVal returns JavaScript code for accessing an object's property // identified by jsTag. It prefers the dot notation over the bracket notation when // possible, since the dot notation produces slightly smaller output. // // For example: // // "my_name" -> ".my_name" // "my name" -> `["my name"]` // // For more information about JavaScript property accessors and identifiers, see // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors and // https://developer.mozilla.org/en-US/docs/Glossary/Identifier. //
func formatJSStructTagVal(jsTag string) string
// formatJSStructTagVal returns JavaScript code for accessing an object's property // identified by jsTag. It prefers the dot notation over the bracket notation when // possible, since the dot notation produces slightly smaller output. // // For example: // // "my_name" -> ".my_name" // "my name" -> `["my name"]` // // For more information about JavaScript property accessors and identifiers, see // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors and // https://developer.mozilla.org/en-US/docs/Glossary/Identifier. // func formatJSStructTagVal(jsTag string) string
{ for i, r := range jsTag { ok := unicode.IsLetter(r) || (i != 0 && unicode.IsNumber(r)) || r == '$' || r == '_' if !ok { // Saw an invalid JavaScript identifier character, // so use bracket notation. return `["` + template.JSEscapeString(jsTag) + `"]` } } // Safe to use dot notation without any escaping. return "." + jsTag }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
nosync/map.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/nosync/map.go#L16-L19
go
train
// Load returns the value stored in the map for a key, or nil if no // value is present. // The ok result indicates whether value was found in the map.
func (m *Map) Load(key interface{}) (value interface{}, ok bool)
// Load returns the value stored in the map for a key, or nil if no // value is present. // The ok result indicates whether value was found in the map. func (m *Map) Load(key interface{}) (value interface{}, ok bool)
{ value, ok = m.m[key] return value, ok }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
nosync/map.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/nosync/map.go#L22-L27
go
train
// Store sets the value for a key.
func (m *Map) Store(key, value interface{})
// Store sets the value for a key. func (m *Map) Store(key, value interface{})
{ if m.m == nil { m.m = make(map[interface{}]interface{}) } m.m[key] = value }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
nosync/map.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/nosync/map.go#L32-L41
go
train
// LoadOrStore returns the existing value for the key if present. // Otherwise, it stores and returns the given value. // The loaded result is true if the value was loaded, false if stored.
func (m *Map) LoadOrStore(key, value interface{}) (actual interface{}, loaded bool)
// LoadOrStore returns the existing value for the key if present. // Otherwise, it stores and returns the given value. // The loaded result is true if the value was loaded, false if stored. func (m *Map) LoadOrStore(key, value interface{}) (actual interface{}, loaded bool)
{ if value, ok := m.m[key]; ok { return value, true } if m.m == nil { m.m = make(map[interface{}]interface{}) } m.m[key] = value return value, false }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
nosync/map.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/nosync/map.go#L44-L49
go
train
// Delete deletes the value for a key.
func (m *Map) Delete(key interface{})
// Delete deletes the value for a key. func (m *Map) Delete(key interface{})
{ if m.m == nil { return } delete(m.m, key) }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
nosync/map.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/nosync/map.go#L61-L67
go
train
// Range calls f sequentially for each key and value present in the map. // If f returns false, range stops the iteration. // // Range does not necessarily correspond to any consistent snapshot of the Map's // contents: no key will be visited more than once, but if the value for any key // is stored or deleted concurrently, Range may reflect any mapping for that key // from any point during the Range call. // // Range may be O(N) with the number of elements in the map even if f returns // false after a constant number of calls.
func (m *Map) Range(f func(key, value interface{}) bool)
// Range calls f sequentially for each key and value present in the map. // If f returns false, range stops the iteration. // // Range does not necessarily correspond to any consistent snapshot of the Map's // contents: no key will be visited more than once, but if the value for any key // is stored or deleted concurrently, Range may reflect any mapping for that key // from any point during the Range call. // // Range may be O(N) with the number of elements in the map even if f returns // false after a constant number of calls. func (m *Map) Range(f func(key, value interface{}) bool)
{ for k, v := range m.m { if !f(k, v) { break } } }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
js/js.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/js/js.go#L115-L117
go
train
// MakeFunc wraps a function and gives access to the values of JavaScript's "this" and "arguments" keywords.
func MakeFunc(fn func(this *Object, arguments []*Object) interface{}) *Object
// MakeFunc wraps a function and gives access to the values of JavaScript's "this" and "arguments" keywords. func MakeFunc(fn func(this *Object, arguments []*Object) interface{}) *Object
{ return Global.Call("$makeFunc", InternalObject(fn)) }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
js/js.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/js/js.go#L120-L130
go
train
// Keys returns the keys of the given JavaScript object.
func Keys(o *Object) []string
// Keys returns the keys of the given JavaScript object. func Keys(o *Object) []string
{ if o == nil || o == Undefined { return nil } a := Global.Get("Object").Call("keys", o) s := make([]string, a.Length()) for i := 0; i < a.Length(); i++ { s[i] = a.Index(i).String() } return s }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
js/js.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/js/js.go#L133-L148
go
train
// MakeWrapper creates a JavaScript object which has wrappers for the exported methods of i. Use explicit getter and setter methods to expose struct fields to JavaScript.
func MakeWrapper(i interface{}) *Object
// MakeWrapper creates a JavaScript object which has wrappers for the exported methods of i. Use explicit getter and setter methods to expose struct fields to JavaScript. func MakeWrapper(i interface{}) *Object
{ v := InternalObject(i) o := Global.Get("Object").New() o.Set("__internal_object__", v) methods := v.Get("constructor").Get("methods") for i := 0; i < methods.Length(); i++ { m := methods.Index(i) if m.Get("pkg").String() != "" { // not exported continue } o.Set(m.Get("name").String(), func(args ...*Object) *Object { return Global.Call("$externalizeFunction", v.Get(m.Get("prop").String()), m.Get("typ"), true).Call("apply", v, args) }) } return o }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
js/js.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/js/js.go#L151-L156
go
train
// NewArrayBuffer creates a JavaScript ArrayBuffer from a byte slice.
func NewArrayBuffer(b []byte) *Object
// NewArrayBuffer creates a JavaScript ArrayBuffer from a byte slice. func NewArrayBuffer(b []byte) *Object
{ slice := InternalObject(b) offset := slice.Get("$offset").Int() length := slice.Get("$length").Int() return slice.Get("$array").Get("buffer").Call("slice", offset, offset+length) }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
compiler/natives/src/internal/poll/fd_poll.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/compiler/natives/src/internal/poll/fd_poll.go#L60-L67
go
train
// Copy of sync.runtime_Semacquire.
func runtime_Semacquire(s *uint32)
// Copy of sync.runtime_Semacquire. func runtime_Semacquire(s *uint32)
{ if *s == 0 { ch := make(chan bool) semWaiters[s] = append(semWaiters[s], ch) <-ch } *s-- }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
compiler/natives/src/internal/poll/fd_poll.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/compiler/natives/src/internal/poll/fd_poll.go#L70-L86
go
train
// Copy of sync.runtime_Semrelease.
func runtime_Semrelease(s *uint32)
// Copy of sync.runtime_Semrelease. func runtime_Semrelease(s *uint32)
{ *s++ w := semWaiters[s] if len(w) == 0 { return } ch := w[0] w = w[1:] semWaiters[s] = w if len(w) == 0 { delete(semWaiters, s) } ch <- true }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
build/build.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/build/build.go#L44-L89
go
train
// NewBuildContext creates a build context for building Go packages // with GopherJS compiler. // // Core GopherJS packages (i.e., "github.com/gopherjs/gopherjs/js", "github.com/gopherjs/gopherjs/nosync") // are loaded from gopherjspkg.FS virtual filesystem rather than GOPATH.
func NewBuildContext(installSuffix string, buildTags []string) *build.Context
// NewBuildContext creates a build context for building Go packages // with GopherJS compiler. // // Core GopherJS packages (i.e., "github.com/gopherjs/gopherjs/js", "github.com/gopherjs/gopherjs/nosync") // are loaded from gopherjspkg.FS virtual filesystem rather than GOPATH. func NewBuildContext(installSuffix string, buildTags []string) *build.Context
{ gopherjsRoot := filepath.Join(build.Default.GOROOT, "src", "github.com", "gopherjs", "gopherjs") return &build.Context{ GOROOT: build.Default.GOROOT, GOPATH: build.Default.GOPATH, GOOS: build.Default.GOOS, GOARCH: "js", InstallSuffix: installSuffix, Compiler: "gc", BuildTags: append(buildTags, "netgo", // See https://godoc.org/net#hdr-Name_Resolution. "purego", // See https://golang.org/issues/23172. ), ReleaseTags: build.Default.ReleaseTags, CgoEnabled: true, // detect `import "C"` to throw proper error IsDir: func(path string) bool { if strings.HasPrefix(path, gopherjsRoot+string(filepath.Separator)) { path = filepath.ToSlash(path[len(gopherjsRoot):]) if fi, err := vfsutil.Stat(gopherjspkg.FS, path); err == nil { return fi.IsDir() } } fi, err := os.Stat(path) return err == nil && fi.IsDir() }, ReadDir: func(path string) ([]os.FileInfo, error) { if strings.HasPrefix(path, gopherjsRoot+string(filepath.Separator)) { path = filepath.ToSlash(path[len(gopherjsRoot):]) if fis, err := vfsutil.ReadDir(gopherjspkg.FS, path); err == nil { return fis, nil } } return ioutil.ReadDir(path) }, OpenFile: func(path string) (io.ReadCloser, error) { if strings.HasPrefix(path, gopherjsRoot+string(filepath.Separator)) { path = filepath.ToSlash(path[len(gopherjsRoot):]) if f, err := gopherjspkg.FS.Open(path); err == nil { return f, nil } } return os.Open(path) }, } }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
build/build.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/build/build.go#L94-L103
go
train
// statFile returns an os.FileInfo describing the named file. // For files in "$GOROOT/src/github.com/gopherjs/gopherjs" directory, // gopherjspkg.FS is consulted first.
func statFile(path string) (os.FileInfo, error)
// statFile returns an os.FileInfo describing the named file. // For files in "$GOROOT/src/github.com/gopherjs/gopherjs" directory, // gopherjspkg.FS is consulted first. func statFile(path string) (os.FileInfo, error)
{ gopherjsRoot := filepath.Join(build.Default.GOROOT, "src", "github.com", "gopherjs", "gopherjs") if strings.HasPrefix(path, gopherjsRoot+string(filepath.Separator)) { path = filepath.ToSlash(path[len(gopherjsRoot):]) if fi, err := vfsutil.Stat(gopherjspkg.FS, path); err == nil { return fi, nil } } return os.Stat(path) }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
build/build.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/build/build.go#L119-L129
go
train
// Import returns details about the Go package named by the import path. If the // path is a local import path naming a package that can be imported using // a standard import path, the returned package will set p.ImportPath to // that path. // // In the directory containing the package, .go and .inc.js files are // considered part of the package except for: // // - .go files in package documentation // - files starting with _ or . (likely editor temporary files) // - files with build constraints not satisfied by the context // // If an error occurs, Import returns a non-nil error and a nil // *PackageData.
func Import(path string, mode build.ImportMode, installSuffix string, buildTags []string) (*PackageData, error)
// Import returns details about the Go package named by the import path. If the // path is a local import path naming a package that can be imported using // a standard import path, the returned package will set p.ImportPath to // that path. // // In the directory containing the package, .go and .inc.js files are // considered part of the package except for: // // - .go files in package documentation // - files starting with _ or . (likely editor temporary files) // - files with build constraints not satisfied by the context // // If an error occurs, Import returns a non-nil error and a nil // *PackageData. func Import(path string, mode build.ImportMode, installSuffix string, buildTags []string) (*PackageData, error)
{ wd, err := os.Getwd() if err != nil { // Getwd may fail if we're in GOARCH=js mode. That's okay, handle // it by falling back to empty working directory. It just means // Import will not be able to resolve relative import paths. wd = "" } bctx := NewBuildContext(installSuffix, buildTags) return importWithSrcDir(*bctx, path, wd, mode, installSuffix) }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
build/build.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/build/build.go#L205-L214
go
train
// excludeExecutable excludes all executable implementation .go files. // They have "executable_" prefix.
func excludeExecutable(goFiles []string) []string
// excludeExecutable excludes all executable implementation .go files. // They have "executable_" prefix. func excludeExecutable(goFiles []string) []string
{ var s []string for _, f := range goFiles { if strings.HasPrefix(f, "executable_") { continue } s = append(s, f) } return s }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
build/build.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/build/build.go#L217-L229
go
train
// exclude returns files, excluding specified files.
func exclude(files []string, exclude ...string) []string
// exclude returns files, excluding specified files. func exclude(files []string, exclude ...string) []string
{ var s []string Outer: for _, f := range files { for _, e := range exclude { if f == e { continue Outer } } s = append(s, f) } return s }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
build/build.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/build/build.go#L233-L246
go
train
// ImportDir is like Import but processes the Go package found in the named // directory.
func ImportDir(dir string, mode build.ImportMode, installSuffix string, buildTags []string) (*PackageData, error)
// ImportDir is like Import but processes the Go package found in the named // directory. func ImportDir(dir string, mode build.ImportMode, installSuffix string, buildTags []string) (*PackageData, error)
{ bctx := NewBuildContext(installSuffix, buildTags) pkg, err := bctx.ImportDir(dir, mode) if err != nil { return nil, err } jsFiles, err := jsFilesFromDir(bctx, pkg.Dir) if err != nil { return nil, err } return &PackageData{Package: pkg, JSFiles: jsFiles}, nil }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
build/build.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/build/build.go#L259-L440
go
train
// parseAndAugment parses and returns all .go files of given pkg. // Standard Go library packages are augmented with files in compiler/natives folder. // If isTest is true and pkg.ImportPath has no _test suffix, package is built for running internal tests. // If isTest is true and pkg.ImportPath has _test suffix, package is built for running external tests. // // The native packages are augmented by the contents of natives.FS in the following way. // The file names do not matter except the usual `_test` suffix. The files for // native overrides get added to the package (even if they have the same name // as an existing file from the standard library). For all identifiers that exist // in the original AND the overrides, the original identifier in the AST gets // replaced by `_`. New identifiers that don't exist in original package get added.
func parseAndAugment(bctx *build.Context, pkg *build.Package, isTest bool, fileSet *token.FileSet) ([]*ast.File, error)
// parseAndAugment parses and returns all .go files of given pkg. // Standard Go library packages are augmented with files in compiler/natives folder. // If isTest is true and pkg.ImportPath has no _test suffix, package is built for running internal tests. // If isTest is true and pkg.ImportPath has _test suffix, package is built for running external tests. // // The native packages are augmented by the contents of natives.FS in the following way. // The file names do not matter except the usual `_test` suffix. The files for // native overrides get added to the package (even if they have the same name // as an existing file from the standard library). For all identifiers that exist // in the original AND the overrides, the original identifier in the AST gets // replaced by `_`. New identifiers that don't exist in original package get added. func parseAndAugment(bctx *build.Context, pkg *build.Package, isTest bool, fileSet *token.FileSet) ([]*ast.File, error)
{ var files []*ast.File replacedDeclNames := make(map[string]bool) funcName := func(d *ast.FuncDecl) string { if d.Recv == nil || len(d.Recv.List) == 0 { return d.Name.Name } recv := d.Recv.List[0].Type if star, ok := recv.(*ast.StarExpr); ok { recv = star.X } return recv.(*ast.Ident).Name + "." + d.Name.Name } isXTest := strings.HasSuffix(pkg.ImportPath, "_test") importPath := pkg.ImportPath if isXTest { importPath = importPath[:len(importPath)-5] } nativesContext := &build.Context{ GOROOT: "/", GOOS: build.Default.GOOS, GOARCH: "js", Compiler: "gc", JoinPath: path.Join, SplitPathList: func(list string) []string { if list == "" { return nil } return strings.Split(list, "/") }, IsAbsPath: path.IsAbs, IsDir: func(name string) bool { dir, err := natives.FS.Open(name) if err != nil { return false } defer dir.Close() info, err := dir.Stat() if err != nil { return false } return info.IsDir() }, HasSubdir: func(root, name string) (rel string, ok bool) { panic("not implemented") }, ReadDir: func(name string) (fi []os.FileInfo, err error) { dir, err := natives.FS.Open(name) if err != nil { return nil, err } defer dir.Close() return dir.Readdir(0) }, OpenFile: func(name string) (r io.ReadCloser, err error) { return natives.FS.Open(name) }, } // reflect needs to tell Go 1.11 apart from Go 1.11.1 for https://github.com/gopherjs/gopherjs/issues/862, // so provide it with the custom go1.11.1 build tag whenever we're on Go 1.11.1 or later. // TODO: Remove this ad hoc special behavior in GopherJS 1.12. if runtime.Version() != "go1.11" { nativesContext.ReleaseTags = append(nativesContext.ReleaseTags, "go1.11.1") } if nativesPkg, err := nativesContext.Import(importPath, "", 0); err == nil { names := nativesPkg.GoFiles if isTest { names = append(names, nativesPkg.TestGoFiles...) } if isXTest { names = nativesPkg.XTestGoFiles } for _, name := range names { fullPath := path.Join(nativesPkg.Dir, name) r, err := nativesContext.OpenFile(fullPath) if err != nil { panic(err) } file, err := parser.ParseFile(fileSet, fullPath, r, parser.ParseComments) if err != nil { panic(err) } r.Close() for _, decl := range file.Decls { switch d := decl.(type) { case *ast.FuncDecl: replacedDeclNames[funcName(d)] = true case *ast.GenDecl: switch d.Tok { case token.TYPE: for _, spec := range d.Specs { replacedDeclNames[spec.(*ast.TypeSpec).Name.Name] = true } case token.VAR, token.CONST: for _, spec := range d.Specs { for _, name := range spec.(*ast.ValueSpec).Names { replacedDeclNames[name.Name] = true } } } } } files = append(files, file) } } delete(replacedDeclNames, "init") var errList compiler.ErrorList for _, name := range pkg.GoFiles { if !filepath.IsAbs(name) { // name might be absolute if specified directly. E.g., `gopherjs build /abs/file.go`. name = filepath.Join(pkg.Dir, name) } r, err := buildutil.OpenFile(bctx, name) if err != nil { return nil, err } file, err := parser.ParseFile(fileSet, name, r, parser.ParseComments) r.Close() if err != nil { if list, isList := err.(scanner.ErrorList); isList { if len(list) > 10 { list = append(list[:10], &scanner.Error{Pos: list[9].Pos, Msg: "too many errors"}) } for _, entry := range list { errList = append(errList, entry) } continue } errList = append(errList, err) continue } switch pkg.ImportPath { case "crypto/rand", "encoding/gob", "encoding/json", "expvar", "go/token", "log", "math/big", "math/rand", "regexp", "testing", "time": for _, spec := range file.Imports { path, _ := strconv.Unquote(spec.Path.Value) if path == "sync" { if spec.Name == nil { spec.Name = ast.NewIdent("sync") } spec.Path.Value = `"github.com/gopherjs/gopherjs/nosync"` } } } for _, decl := range file.Decls { switch d := decl.(type) { case *ast.FuncDecl: if replacedDeclNames[funcName(d)] { d.Name = ast.NewIdent("_") } case *ast.GenDecl: switch d.Tok { case token.TYPE: for _, spec := range d.Specs { s := spec.(*ast.TypeSpec) if replacedDeclNames[s.Name.Name] { s.Name = ast.NewIdent("_") } } case token.VAR, token.CONST: for _, spec := range d.Specs { s := spec.(*ast.ValueSpec) for i, name := range s.Names { if replacedDeclNames[name.Name] { s.Names[i] = ast.NewIdent("_") } } } } } } files = append(files, file) } if errList != nil { return nil, errList } return files, nil }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
build/build.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/build/build.go#L843-L852
go
train
// hasGopathPrefix returns true and the length of the matched GOPATH workspace, // iff file has a prefix that matches one of the GOPATH workspaces.
func hasGopathPrefix(file, gopath string) (hasGopathPrefix bool, prefixLen int)
// hasGopathPrefix returns true and the length of the matched GOPATH workspace, // iff file has a prefix that matches one of the GOPATH workspaces. func hasGopathPrefix(file, gopath string) (hasGopathPrefix bool, prefixLen int)
{ gopathWorkspaces := filepath.SplitList(gopath) for _, gopathWorkspace := range gopathWorkspaces { gopathWorkspace = filepath.Clean(gopathWorkspace) if strings.HasPrefix(file, gopathWorkspace) { return true, len(gopathWorkspace) } } return false, 0 }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
internal/sysutil/sysutil.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/internal/sysutil/sysutil.go#L9-L13
go
train
// RlimitStack reports the current stack size limit in bytes.
func RlimitStack() (cur uint64, err error)
// RlimitStack reports the current stack size limit in bytes. func RlimitStack() (cur uint64, err error)
{ var r unix.Rlimit err = unix.Getrlimit(unix.RLIMIT_STACK, &r) return uint64(r.Cur), err // Type conversion because Cur is one of uint64, int64 depending on unix flavor. }
gopherjs/gopherjs
3e4dfb77656c424b6d1196a4d5fed0fcf63677cc
compiler/natives/src/syscall/syscall.go
https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/compiler/natives/src/syscall/syscall.go#L57-L64
go
train
// indexByte is copied from bytes package to avoid importing it (since the real syscall package doesn't).
func indexByte(s []byte, c byte) int
// indexByte is copied from bytes package to avoid importing it (since the real syscall package doesn't). func indexByte(s []byte, c byte) int
{ for i, b := range s { if b == c { return i } } return -1 }