id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
12,100
trivago/tgo
tsync/queue.go
IsEmpty
func (q *Queue) IsEmpty() bool { return atomic.LoadUint64(q.write.processing) == atomic.LoadUint64(q.read.processing) }
go
func (q *Queue) IsEmpty() bool { return atomic.LoadUint64(q.write.processing) == atomic.LoadUint64(q.read.processing) }
[ "func", "(", "q", "*", "Queue", ")", "IsEmpty", "(", ")", "bool", "{", "return", "atomic", ".", "LoadUint64", "(", "q", ".", "write", ".", "processing", ")", "==", "atomic", ".", "LoadUint64", "(", "q", ".", "read", ".", "processing", ")", "\n", "}" ]
// IsEmpty returns true if there is no item in the queue to be processed. // Please note that this state is extremely volatile unless IsClosed // returned true.
[ "IsEmpty", "returns", "true", "if", "there", "is", "no", "item", "in", "the", "queue", "to", "be", "processed", ".", "Please", "note", "that", "this", "state", "is", "extremely", "volatile", "unless", "IsClosed", "returned", "true", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tsync/queue.go#L152-L154
12,101
trivago/tgo
treflect/typeregistry.go
RegisterWithDepth
func (registry TypeRegistry) RegisterWithDepth(typeInstance interface{}, depth int) { structType := reflect.TypeOf(typeInstance) packageName := structType.PkgPath() typeName := structType.Name() pathTokens := strings.Split(packageName, "/") maxDepth := 3 if len(pathTokens) < maxDepth { maxDepth = len(pathTokens) } for n := depth; n <= maxDepth; n++ { shortTypeName := strings.Join(pathTokens[len(pathTokens)-n:], ".") + "." + typeName registry.namedType[shortTypeName] = structType } }
go
func (registry TypeRegistry) RegisterWithDepth(typeInstance interface{}, depth int) { structType := reflect.TypeOf(typeInstance) packageName := structType.PkgPath() typeName := structType.Name() pathTokens := strings.Split(packageName, "/") maxDepth := 3 if len(pathTokens) < maxDepth { maxDepth = len(pathTokens) } for n := depth; n <= maxDepth; n++ { shortTypeName := strings.Join(pathTokens[len(pathTokens)-n:], ".") + "." + typeName registry.namedType[shortTypeName] = structType } }
[ "func", "(", "registry", "TypeRegistry", ")", "RegisterWithDepth", "(", "typeInstance", "interface", "{", "}", ",", "depth", "int", ")", "{", "structType", ":=", "reflect", ".", "TypeOf", "(", "typeInstance", ")", "\n", "packageName", ":=", "structType", ".", "PkgPath", "(", ")", "\n", "typeName", ":=", "structType", ".", "Name", "(", ")", "\n\n", "pathTokens", ":=", "strings", ".", "Split", "(", "packageName", ",", "\"", "\"", ")", "\n", "maxDepth", ":=", "3", "\n", "if", "len", "(", "pathTokens", ")", "<", "maxDepth", "{", "maxDepth", "=", "len", "(", "pathTokens", ")", "\n", "}", "\n\n", "for", "n", ":=", "depth", ";", "n", "<=", "maxDepth", ";", "n", "++", "{", "shortTypeName", ":=", "strings", ".", "Join", "(", "pathTokens", "[", "len", "(", "pathTokens", ")", "-", "n", ":", "]", ",", "\"", "\"", ")", "+", "\"", "\"", "+", "typeName", "\n", "registry", ".", "namedType", "[", "shortTypeName", "]", "=", "structType", "\n", "}", "\n", "}" ]
// RegisterWithDepth to register a plugin to the TypeRegistry by passing an uninitialized object.
[ "RegisterWithDepth", "to", "register", "a", "plugin", "to", "the", "TypeRegistry", "by", "passing", "an", "uninitialized", "object", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/treflect/typeregistry.go#L42-L57
12,102
trivago/tgo
treflect/typeregistry.go
GetTypeOf
func (registry TypeRegistry) GetTypeOf(typeName string) reflect.Type { if structType, exists := registry.namedType[typeName]; exists { return reflect.PtrTo(structType) } return nil }
go
func (registry TypeRegistry) GetTypeOf(typeName string) reflect.Type { if structType, exists := registry.namedType[typeName]; exists { return reflect.PtrTo(structType) } return nil }
[ "func", "(", "registry", "TypeRegistry", ")", "GetTypeOf", "(", "typeName", "string", ")", "reflect", ".", "Type", "{", "if", "structType", ",", "exists", ":=", "registry", ".", "namedType", "[", "typeName", "]", ";", "exists", "{", "return", "reflect", ".", "PtrTo", "(", "structType", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetTypeOf returns only the type asscociated with the given name. // If the name is not registered, nil is returned. // The type returned will be a pointer type.
[ "GetTypeOf", "returns", "only", "the", "type", "asscociated", "with", "the", "given", "name", ".", "If", "the", "name", "is", "not", "registered", "nil", "is", "returned", ".", "The", "type", "returned", "will", "be", "a", "pointer", "type", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/treflect/typeregistry.go#L73-L78
12,103
trivago/tgo
treflect/typeregistry.go
IsTypeRegistered
func (registry TypeRegistry) IsTypeRegistered(typeName string) bool { _, exists := registry.namedType[typeName] return exists }
go
func (registry TypeRegistry) IsTypeRegistered(typeName string) bool { _, exists := registry.namedType[typeName] return exists }
[ "func", "(", "registry", "TypeRegistry", ")", "IsTypeRegistered", "(", "typeName", "string", ")", "bool", "{", "_", ",", "exists", ":=", "registry", ".", "namedType", "[", "typeName", "]", "\n", "return", "exists", "\n", "}" ]
// IsTypeRegistered returns true if a type is registered to this registry. // Note that GetTypeOf can do the same thing by checking for nil but also // returns the type, so in many cases you will want to call this function.
[ "IsTypeRegistered", "returns", "true", "if", "a", "type", "is", "registered", "to", "this", "registry", ".", "Note", "that", "GetTypeOf", "can", "do", "the", "same", "thing", "by", "checking", "for", "nil", "but", "also", "returns", "the", "type", "so", "in", "many", "cases", "you", "will", "want", "to", "call", "this", "function", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/treflect/typeregistry.go#L83-L86
12,104
trivago/tgo
treflect/typeregistry.go
GetRegistered
func (registry TypeRegistry) GetRegistered(packageName string) []string { var result []string for key := range registry.namedType { if strings.HasPrefix(key, packageName) { result = append(result, key) } } return result }
go
func (registry TypeRegistry) GetRegistered(packageName string) []string { var result []string for key := range registry.namedType { if strings.HasPrefix(key, packageName) { result = append(result, key) } } return result }
[ "func", "(", "registry", "TypeRegistry", ")", "GetRegistered", "(", "packageName", "string", ")", "[", "]", "string", "{", "var", "result", "[", "]", "string", "\n", "for", "key", ":=", "range", "registry", ".", "namedType", "{", "if", "strings", ".", "HasPrefix", "(", "key", ",", "packageName", ")", "{", "result", "=", "append", "(", "result", ",", "key", ")", "\n", "}", "\n", "}", "\n", "return", "result", "\n", "}" ]
// GetRegistered returns the names of all registered types for a given package
[ "GetRegistered", "returns", "the", "names", "of", "all", "registered", "types", "for", "a", "given", "package" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/treflect/typeregistry.go#L89-L97
12,105
trivago/tgo
tfmt/color.go
Colorize
func Colorize(c Color, b BackgroundColor, text string) string { return fmt.Sprintf("%s%s%s%s%s", ResetColors, c, b, text, ResetColors.String()) }
go
func Colorize(c Color, b BackgroundColor, text string) string { return fmt.Sprintf("%s%s%s%s%s", ResetColors, c, b, text, ResetColors.String()) }
[ "func", "Colorize", "(", "c", "Color", ",", "b", "BackgroundColor", ",", "text", "string", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ResetColors", ",", "c", ",", "b", ",", "text", ",", "ResetColors", ".", "String", "(", ")", ")", "\n", "}" ]
// Colorize returns a colored string with the given colors.
[ "Colorize", "returns", "a", "colored", "string", "with", "the", "given", "colors", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tfmt/color.go#L52-L54
12,106
trivago/tgo
tfmt/color.go
Colorizef
func Colorizef(c Color, b BackgroundColor, format string, args ...interface{}) string { args = append([]interface{}{ResetColors, c, b}, args...) args = append(args, ResetColors) return fmt.Sprintf("%s%s%s"+format+"%s", args...) }
go
func Colorizef(c Color, b BackgroundColor, format string, args ...interface{}) string { args = append([]interface{}{ResetColors, c, b}, args...) args = append(args, ResetColors) return fmt.Sprintf("%s%s%s"+format+"%s", args...) }
[ "func", "Colorizef", "(", "c", "Color", ",", "b", "BackgroundColor", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "string", "{", "args", "=", "append", "(", "[", "]", "interface", "{", "}", "{", "ResetColors", ",", "c", ",", "b", "}", ",", "args", "...", ")", "\n", "args", "=", "append", "(", "args", ",", "ResetColors", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "format", "+", "\"", "\"", ",", "args", "...", ")", "\n", "}" ]
// Colorizef returns a colored, formatted string with the given colors.
[ "Colorizef", "returns", "a", "colored", "formatted", "string", "with", "the", "given", "colors", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tfmt/color.go#L57-L61
12,107
trivago/tgo
tsync/mutex.go
NewMutex
func NewMutex(priority SpinPriority) *Mutex { return &Mutex{ state: new(int32), priority: priority, } }
go
func NewMutex(priority SpinPriority) *Mutex { return &Mutex{ state: new(int32), priority: priority, } }
[ "func", "NewMutex", "(", "priority", "SpinPriority", ")", "*", "Mutex", "{", "return", "&", "Mutex", "{", "state", ":", "new", "(", "int32", ")", ",", "priority", ":", "priority", ",", "}", "\n", "}" ]
// NewMutex creates a new mutex with the given spin priority used during Lock.
[ "NewMutex", "creates", "a", "new", "mutex", "with", "the", "given", "spin", "priority", "used", "during", "Lock", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tsync/mutex.go#L35-L40
12,108
trivago/tgo
tsync/mutex.go
TryLock
func (m *Mutex) TryLock() bool { return atomic.CompareAndSwapInt32(m.state, mutexUnlocked, mutexLocked) }
go
func (m *Mutex) TryLock() bool { return atomic.CompareAndSwapInt32(m.state, mutexUnlocked, mutexLocked) }
[ "func", "(", "m", "*", "Mutex", ")", "TryLock", "(", ")", "bool", "{", "return", "atomic", ".", "CompareAndSwapInt32", "(", "m", ".", "state", ",", "mutexUnlocked", ",", "mutexLocked", ")", "\n", "}" ]
// TryLock tries to acquire a lock and returns true if it succeeds. This // function does not block.
[ "TryLock", "tries", "to", "acquire", "a", "lock", "and", "returns", "true", "if", "it", "succeeds", ".", "This", "function", "does", "not", "block", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tsync/mutex.go#L52-L54
12,109
trivago/tgo
tlog/lognull.go
Write
func (log logNull) Write(message []byte) (int, error) { return len(message), nil }
go
func (log logNull) Write(message []byte) (int, error) { return len(message), nil }
[ "func", "(", "log", "logNull", ")", "Write", "(", "message", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "return", "len", "(", "message", ")", ",", "nil", "\n", "}" ]
// Write Drops all messages
[ "Write", "Drops", "all", "messages" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tlog/lognull.go#L21-L23
12,110
trivago/tgo
tmath/bits.go
NextPowerOf2U16
func NextPowerOf2U16(v uint16) uint16 { v-- v |= v >> 1 v |= v >> 2 v |= v >> 4 v |= v >> 8 v++ return v }
go
func NextPowerOf2U16(v uint16) uint16 { v-- v |= v >> 1 v |= v >> 2 v |= v >> 4 v |= v >> 8 v++ return v }
[ "func", "NextPowerOf2U16", "(", "v", "uint16", ")", "uint16", "{", "v", "--", "\n", "v", "|=", "v", ">>", "1", "\n", "v", "|=", "v", ">>", "2", "\n", "v", "|=", "v", ">>", "4", "\n", "v", "|=", "v", ">>", "8", "\n", "v", "++", "\n", "return", "v", "\n", "}" ]
// NextPowerOf2U16 returns the next power of 2 for a given 16bit number
[ "NextPowerOf2U16", "returns", "the", "next", "power", "of", "2", "for", "a", "given", "16bit", "number" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tmath/bits.go#L18-L26
12,111
trivago/tgo
tmath/bits.go
NextPowerOf2U32
func NextPowerOf2U32(v uint32) uint32 { v-- v |= v >> 1 v |= v >> 2 v |= v >> 4 v |= v >> 8 v |= v >> 16 v++ return v }
go
func NextPowerOf2U32(v uint32) uint32 { v-- v |= v >> 1 v |= v >> 2 v |= v >> 4 v |= v >> 8 v |= v >> 16 v++ return v }
[ "func", "NextPowerOf2U32", "(", "v", "uint32", ")", "uint32", "{", "v", "--", "\n", "v", "|=", "v", ">>", "1", "\n", "v", "|=", "v", ">>", "2", "\n", "v", "|=", "v", ">>", "4", "\n", "v", "|=", "v", ">>", "8", "\n", "v", "|=", "v", ">>", "16", "\n", "v", "++", "\n", "return", "v", "\n", "}" ]
// NextPowerOf2U32 returns the next power of 2 for a given 32bit number
[ "NextPowerOf2U32", "returns", "the", "next", "power", "of", "2", "for", "a", "given", "32bit", "number" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tmath/bits.go#L29-L38
12,112
trivago/tgo
tmath/bits.go
NextPowerOf2U64
func NextPowerOf2U64(v uint64) uint64 { v-- v |= v >> 1 v |= v >> 2 v |= v >> 4 v |= v >> 8 v |= v >> 16 v |= v >> 32 v++ return v }
go
func NextPowerOf2U64(v uint64) uint64 { v-- v |= v >> 1 v |= v >> 2 v |= v >> 4 v |= v >> 8 v |= v >> 16 v |= v >> 32 v++ return v }
[ "func", "NextPowerOf2U64", "(", "v", "uint64", ")", "uint64", "{", "v", "--", "\n", "v", "|=", "v", ">>", "1", "\n", "v", "|=", "v", ">>", "2", "\n", "v", "|=", "v", ">>", "4", "\n", "v", "|=", "v", ">>", "8", "\n", "v", "|=", "v", ">>", "16", "\n", "v", "|=", "v", ">>", "32", "\n", "v", "++", "\n", "return", "v", "\n", "}" ]
// NextPowerOf2U64 returns the next power of 2 for a given 64bit number
[ "NextPowerOf2U64", "returns", "the", "next", "power", "of", "2", "for", "a", "given", "64bit", "number" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tmath/bits.go#L41-L51
12,113
trivago/tgo
tsync/stack.go
NewStackWithGrowSize
func NewStackWithGrowSize(size, grow int) Stack { return NewStackWithSpinnerAndGrowSize(size, grow, NewSpinner(SpinPriorityMedium)) }
go
func NewStackWithGrowSize(size, grow int) Stack { return NewStackWithSpinnerAndGrowSize(size, grow, NewSpinner(SpinPriorityMedium)) }
[ "func", "NewStackWithGrowSize", "(", "size", ",", "grow", "int", ")", "Stack", "{", "return", "NewStackWithSpinnerAndGrowSize", "(", "size", ",", "grow", ",", "NewSpinner", "(", "SpinPriorityMedium", ")", ")", "\n", "}" ]
// NewStackWithGrowSize allows to pass a custom grow size to the stack. // SpinPriorityMedium is used to initialize the spinner.
[ "NewStackWithGrowSize", "allows", "to", "pass", "a", "custom", "grow", "size", "to", "the", "stack", ".", "SpinPriorityMedium", "is", "used", "to", "initialize", "the", "spinner", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tsync/stack.go#L45-L47
12,114
trivago/tgo
tsync/stack.go
NewStackWithSpinner
func NewStackWithSpinner(size int, spin Spinner) Stack { return NewStackWithSpinnerAndGrowSize(size, size, spin) }
go
func NewStackWithSpinner(size int, spin Spinner) Stack { return NewStackWithSpinnerAndGrowSize(size, size, spin) }
[ "func", "NewStackWithSpinner", "(", "size", "int", ",", "spin", "Spinner", ")", "Stack", "{", "return", "NewStackWithSpinnerAndGrowSize", "(", "size", ",", "size", ",", "spin", ")", "\n", "}" ]
// NewStackWithSpinner allows to pass a custom spinner to the stack. // The given size will also be used as grow size.
[ "NewStackWithSpinner", "allows", "to", "pass", "a", "custom", "spinner", "to", "the", "stack", ".", "The", "given", "size", "will", "also", "be", "used", "as", "grow", "size", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tsync/stack.go#L51-L53
12,115
trivago/tgo
tsync/stack.go
NewStackWithSpinnerAndGrowSize
func NewStackWithSpinnerAndGrowSize(size, grow int, spin Spinner) Stack { return Stack{ data: make([]interface{}, tmath.MinI(size, 1)), growBy: tmath.MinI(grow, 1), head: new(uint32), spin: spin, } }
go
func NewStackWithSpinnerAndGrowSize(size, grow int, spin Spinner) Stack { return Stack{ data: make([]interface{}, tmath.MinI(size, 1)), growBy: tmath.MinI(grow, 1), head: new(uint32), spin: spin, } }
[ "func", "NewStackWithSpinnerAndGrowSize", "(", "size", ",", "grow", "int", ",", "spin", "Spinner", ")", "Stack", "{", "return", "Stack", "{", "data", ":", "make", "(", "[", "]", "interface", "{", "}", ",", "tmath", ".", "MinI", "(", "size", ",", "1", ")", ")", ",", "growBy", ":", "tmath", ".", "MinI", "(", "grow", ",", "1", ")", ",", "head", ":", "new", "(", "uint32", ")", ",", "spin", ":", "spin", ",", "}", "\n", "}" ]
// NewStackWithSpinnerAndGrowSize allows to fully configure the new stack.
[ "NewStackWithSpinnerAndGrowSize", "allows", "to", "fully", "configure", "the", "new", "stack", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tsync/stack.go#L56-L63
12,116
trivago/tgo
tsync/stack.go
Len
func (s *Stack) Len() int { return int(atomic.LoadUint32(s.head) & unlockMask) }
go
func (s *Stack) Len() int { return int(atomic.LoadUint32(s.head) & unlockMask) }
[ "func", "(", "s", "*", "Stack", ")", "Len", "(", ")", "int", "{", "return", "int", "(", "atomic", ".", "LoadUint32", "(", "s", ".", "head", ")", "&", "unlockMask", ")", "\n", "}" ]
// Len returns the number of elements on the stack. // Please note that this value can be highly unreliable in multithreaded // environments as this is only a snapshot of the state at calltime.
[ "Len", "returns", "the", "number", "of", "elements", "on", "the", "stack", ".", "Please", "note", "that", "this", "value", "can", "be", "highly", "unreliable", "in", "multithreaded", "environments", "as", "this", "is", "only", "a", "snapshot", "of", "the", "state", "at", "calltime", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tsync/stack.go#L68-L70
12,117
trivago/tgo
tsync/stack.go
Pop
func (s *Stack) Pop() (interface{}, error) { spin := s.spin for { head := atomic.LoadUint32(s.head) unlockedHead := head & unlockMask lockedHead := head | lockMask // Always work with unlocked head as head might be locked if unlockedHead == 0 { return nil, LimitError{"Stack is empty"} } if atomic.CompareAndSwapUint32(s.head, unlockedHead, lockedHead) { data := s.data[unlockedHead-1] // copy data atomic.StoreUint32(s.head, unlockedHead-1) // unlock return data, nil // ### return ### } spin.Yield() } }
go
func (s *Stack) Pop() (interface{}, error) { spin := s.spin for { head := atomic.LoadUint32(s.head) unlockedHead := head & unlockMask lockedHead := head | lockMask // Always work with unlocked head as head might be locked if unlockedHead == 0 { return nil, LimitError{"Stack is empty"} } if atomic.CompareAndSwapUint32(s.head, unlockedHead, lockedHead) { data := s.data[unlockedHead-1] // copy data atomic.StoreUint32(s.head, unlockedHead-1) // unlock return data, nil // ### return ### } spin.Yield() } }
[ "func", "(", "s", "*", "Stack", ")", "Pop", "(", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "spin", ":=", "s", ".", "spin", "\n", "for", "{", "head", ":=", "atomic", ".", "LoadUint32", "(", "s", ".", "head", ")", "\n", "unlockedHead", ":=", "head", "&", "unlockMask", "\n", "lockedHead", ":=", "head", "|", "lockMask", "\n\n", "// Always work with unlocked head as head might be locked", "if", "unlockedHead", "==", "0", "{", "return", "nil", ",", "LimitError", "{", "\"", "\"", "}", "\n", "}", "\n\n", "if", "atomic", ".", "CompareAndSwapUint32", "(", "s", ".", "head", ",", "unlockedHead", ",", "lockedHead", ")", "{", "data", ":=", "s", ".", "data", "[", "unlockedHead", "-", "1", "]", "// copy data", "\n", "atomic", ".", "StoreUint32", "(", "s", ".", "head", ",", "unlockedHead", "-", "1", ")", "// unlock", "\n", "return", "data", ",", "nil", "// ### return ###", "\n", "}", "\n\n", "spin", ".", "Yield", "(", ")", "\n", "}", "\n", "}" ]
// Pop retrieves the topmost element from the stack. // A LimitError is returned when the stack is empty.
[ "Pop", "retrieves", "the", "topmost", "element", "from", "the", "stack", ".", "A", "LimitError", "is", "returned", "when", "the", "stack", "is", "empty", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tsync/stack.go#L74-L94
12,118
trivago/tgo
tsync/stack.go
Push
func (s *Stack) Push(v interface{}) error { spin := s.spin for { head := atomic.LoadUint32(s.head) unlockedHead := head & unlockMask lockedHead := head | lockMask // Always work with unlocked head as head might be locked if unlockedHead == unlockMask { return LimitError{"Stack is full"} } if atomic.CompareAndSwapUint32(s.head, unlockedHead, lockedHead) { if unlockedHead == uint32(len(s.data)) { // Grow stack old := s.data s.data = make([]interface{}, len(s.data)+s.growBy) copy(s.data, old) } s.data[unlockedHead] = v // write to new head atomic.StoreUint32(s.head, unlockedHead+1) // unlock return nil // ### return ### } spin.Yield() } }
go
func (s *Stack) Push(v interface{}) error { spin := s.spin for { head := atomic.LoadUint32(s.head) unlockedHead := head & unlockMask lockedHead := head | lockMask // Always work with unlocked head as head might be locked if unlockedHead == unlockMask { return LimitError{"Stack is full"} } if atomic.CompareAndSwapUint32(s.head, unlockedHead, lockedHead) { if unlockedHead == uint32(len(s.data)) { // Grow stack old := s.data s.data = make([]interface{}, len(s.data)+s.growBy) copy(s.data, old) } s.data[unlockedHead] = v // write to new head atomic.StoreUint32(s.head, unlockedHead+1) // unlock return nil // ### return ### } spin.Yield() } }
[ "func", "(", "s", "*", "Stack", ")", "Push", "(", "v", "interface", "{", "}", ")", "error", "{", "spin", ":=", "s", ".", "spin", "\n", "for", "{", "head", ":=", "atomic", ".", "LoadUint32", "(", "s", ".", "head", ")", "\n", "unlockedHead", ":=", "head", "&", "unlockMask", "\n", "lockedHead", ":=", "head", "|", "lockMask", "\n\n", "// Always work with unlocked head as head might be locked", "if", "unlockedHead", "==", "unlockMask", "{", "return", "LimitError", "{", "\"", "\"", "}", "\n", "}", "\n\n", "if", "atomic", ".", "CompareAndSwapUint32", "(", "s", ".", "head", ",", "unlockedHead", ",", "lockedHead", ")", "{", "if", "unlockedHead", "==", "uint32", "(", "len", "(", "s", ".", "data", ")", ")", "{", "// Grow stack", "old", ":=", "s", ".", "data", "\n", "s", ".", "data", "=", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "s", ".", "data", ")", "+", "s", ".", "growBy", ")", "\n", "copy", "(", "s", ".", "data", ",", "old", ")", "\n", "}", "\n\n", "s", ".", "data", "[", "unlockedHead", "]", "=", "v", "// write to new head", "\n", "atomic", ".", "StoreUint32", "(", "s", ".", "head", ",", "unlockedHead", "+", "1", ")", "// unlock", "\n", "return", "nil", "// ### return ###", "\n", "}", "\n\n", "spin", ".", "Yield", "(", ")", "\n", "}", "\n", "}" ]
// Push adds an element to the top of the stack. // When the stack's capacity is reached the storage grows as defined during // construction. If the stack reaches 2^31 elements it is considered full // and will return an LimitError.
[ "Push", "adds", "an", "element", "to", "the", "top", "of", "the", "stack", ".", "When", "the", "stack", "s", "capacity", "is", "reached", "the", "storage", "grows", "as", "defined", "during", "construction", ".", "If", "the", "stack", "reaches", "2^31", "elements", "it", "is", "considered", "full", "and", "will", "return", "an", "LimitError", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tsync/stack.go#L100-L127
12,119
trivago/tgo
tstrings/strings.go
ItoLen
func ItoLen(number uint64) int { switch { case number < 10: return 1 default: return int(math.Log10(float64(number)) + 1) } }
go
func ItoLen(number uint64) int { switch { case number < 10: return 1 default: return int(math.Log10(float64(number)) + 1) } }
[ "func", "ItoLen", "(", "number", "uint64", ")", "int", "{", "switch", "{", "case", "number", "<", "10", ":", "return", "1", "\n", "default", ":", "return", "int", "(", "math", ".", "Log10", "(", "float64", "(", "number", ")", ")", "+", "1", ")", "\n", "}", "\n", "}" ]
// ItoLen returns the length of an unsingned integer when converted to a string
[ "ItoLen", "returns", "the", "length", "of", "an", "unsingned", "integer", "when", "converted", "to", "a", "string" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/strings.go#L41-L48
12,120
trivago/tgo
tstrings/strings.go
Itob
func Itob(number uint64, buffer []byte) error { numberLen := ItoLen(number) bufferLen := len(buffer) if numberLen > bufferLen { return fmt.Errorf("Number too large for buffer") } for i := numberLen - 1; i >= 0; i-- { buffer[i] = '0' + byte(number%10) number /= 10 } return nil }
go
func Itob(number uint64, buffer []byte) error { numberLen := ItoLen(number) bufferLen := len(buffer) if numberLen > bufferLen { return fmt.Errorf("Number too large for buffer") } for i := numberLen - 1; i >= 0; i-- { buffer[i] = '0' + byte(number%10) number /= 10 } return nil }
[ "func", "Itob", "(", "number", "uint64", ",", "buffer", "[", "]", "byte", ")", "error", "{", "numberLen", ":=", "ItoLen", "(", "number", ")", "\n", "bufferLen", ":=", "len", "(", "buffer", ")", "\n\n", "if", "numberLen", ">", "bufferLen", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "for", "i", ":=", "numberLen", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "buffer", "[", "i", "]", "=", "'0'", "+", "byte", "(", "number", "%", "10", ")", "\n", "number", "/=", "10", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Itob writes an unsigned integer to the start of a given byte buffer.
[ "Itob", "writes", "an", "unsigned", "integer", "to", "the", "start", "of", "a", "given", "byte", "buffer", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/strings.go#L51-L65
12,121
trivago/tgo
tstrings/strings.go
Itobe
func Itobe(number uint64, buffer []byte) error { for i := len(buffer) - 1; i >= 0; i-- { buffer[i] = '0' + byte(number%10) number /= 10 // Check here because the number 0 has to be written, too if number == 0 { return nil } } return fmt.Errorf("Number too large for buffer") }
go
func Itobe(number uint64, buffer []byte) error { for i := len(buffer) - 1; i >= 0; i-- { buffer[i] = '0' + byte(number%10) number /= 10 // Check here because the number 0 has to be written, too if number == 0 { return nil } } return fmt.Errorf("Number too large for buffer") }
[ "func", "Itobe", "(", "number", "uint64", ",", "buffer", "[", "]", "byte", ")", "error", "{", "for", "i", ":=", "len", "(", "buffer", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "buffer", "[", "i", "]", "=", "'0'", "+", "byte", "(", "number", "%", "10", ")", "\n", "number", "/=", "10", "\n\n", "// Check here because the number 0 has to be written, too", "if", "number", "==", "0", "{", "return", "nil", "\n", "}", "\n", "}", "\n\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// Itobe writes an unsigned integer to the end of a given byte buffer.
[ "Itobe", "writes", "an", "unsigned", "integer", "to", "the", "end", "of", "a", "given", "byte", "buffer", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/strings.go#L68-L80
12,122
trivago/tgo
tstrings/strings.go
Btoi
func Btoi(buffer []byte) (uint64, int) { number := uint64(0) index := 0 bufferLen := len(buffer) for index < bufferLen && buffer[index] >= '0' && buffer[index] <= '9' { parsed := uint64(buffer[index] - '0') number = number*10 + parsed index++ } return number, index }
go
func Btoi(buffer []byte) (uint64, int) { number := uint64(0) index := 0 bufferLen := len(buffer) for index < bufferLen && buffer[index] >= '0' && buffer[index] <= '9' { parsed := uint64(buffer[index] - '0') number = number*10 + parsed index++ } return number, index }
[ "func", "Btoi", "(", "buffer", "[", "]", "byte", ")", "(", "uint64", ",", "int", ")", "{", "number", ":=", "uint64", "(", "0", ")", "\n", "index", ":=", "0", "\n", "bufferLen", ":=", "len", "(", "buffer", ")", "\n\n", "for", "index", "<", "bufferLen", "&&", "buffer", "[", "index", "]", ">=", "'0'", "&&", "buffer", "[", "index", "]", "<=", "'9'", "{", "parsed", ":=", "uint64", "(", "buffer", "[", "index", "]", "-", "'0'", ")", "\n", "number", "=", "number", "*", "10", "+", "parsed", "\n", "index", "++", "\n", "}", "\n\n", "return", "number", ",", "index", "\n", "}" ]
// Btoi is a fast byte buffer to unsigned int parser that reads until the first // non-number character is found. It returns the number value as well as the // length of the number string encountered. // If a number could not be parsed the returned length will be 0
[ "Btoi", "is", "a", "fast", "byte", "buffer", "to", "unsigned", "int", "parser", "that", "reads", "until", "the", "first", "non", "-", "number", "character", "is", "found", ".", "It", "returns", "the", "number", "value", "as", "well", "as", "the", "length", "of", "the", "number", "string", "encountered", ".", "If", "a", "number", "could", "not", "be", "parsed", "the", "returned", "length", "will", "be", "0" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/strings.go#L86-L98
12,123
trivago/tgo
tstrings/strings.go
IndexN
func IndexN(s, sep string, n int) int { sepIdx := 0 for i := 0; i < n; i++ { nextIdx := strings.Index(s[sepIdx:], sep) if nextIdx == -1 { return -1 // ### return, not found ### } sepIdx += nextIdx + 1 } return sepIdx - 1 }
go
func IndexN(s, sep string, n int) int { sepIdx := 0 for i := 0; i < n; i++ { nextIdx := strings.Index(s[sepIdx:], sep) if nextIdx == -1 { return -1 // ### return, not found ### } sepIdx += nextIdx + 1 } return sepIdx - 1 }
[ "func", "IndexN", "(", "s", ",", "sep", "string", ",", "n", "int", ")", "int", "{", "sepIdx", ":=", "0", "\n", "for", "i", ":=", "0", ";", "i", "<", "n", ";", "i", "++", "{", "nextIdx", ":=", "strings", ".", "Index", "(", "s", "[", "sepIdx", ":", "]", ",", "sep", ")", "\n", "if", "nextIdx", "==", "-", "1", "{", "return", "-", "1", "// ### return, not found ###", "\n", "}", "\n", "sepIdx", "+=", "nextIdx", "+", "1", "\n", "}", "\n", "return", "sepIdx", "-", "1", "\n", "}" ]
// IndexN returns the nth occurrences of sep in s or -1 if there is no nth // occurrence of sep.
[ "IndexN", "returns", "the", "nth", "occurrences", "of", "sep", "in", "s", "or", "-", "1", "if", "there", "is", "no", "nth", "occurrence", "of", "sep", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/strings.go#L102-L112
12,124
trivago/tgo
tstrings/strings.go
LastIndexN
func LastIndexN(s, sep string, n int) int { if n == 0 { return -1 // ### return, nonsense ### } sepIdx := len(s) for i := 0; i < n; i++ { sepIdx = strings.LastIndex(s[:sepIdx], sep) if sepIdx == -1 { return -1 // ### return, not found ### } } return sepIdx }
go
func LastIndexN(s, sep string, n int) int { if n == 0 { return -1 // ### return, nonsense ### } sepIdx := len(s) for i := 0; i < n; i++ { sepIdx = strings.LastIndex(s[:sepIdx], sep) if sepIdx == -1 { return -1 // ### return, not found ### } } return sepIdx }
[ "func", "LastIndexN", "(", "s", ",", "sep", "string", ",", "n", "int", ")", "int", "{", "if", "n", "==", "0", "{", "return", "-", "1", "// ### return, nonsense ###", "\n", "}", "\n", "sepIdx", ":=", "len", "(", "s", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "n", ";", "i", "++", "{", "sepIdx", "=", "strings", ".", "LastIndex", "(", "s", "[", ":", "sepIdx", "]", ",", "sep", ")", "\n", "if", "sepIdx", "==", "-", "1", "{", "return", "-", "1", "// ### return, not found ###", "\n", "}", "\n", "}", "\n", "return", "sepIdx", "\n", "}" ]
// LastIndexN returns the nth occurrence of sep in s or -1 if there is no nth // occurrence of sep. Searching is going from the end of the string to the start.
[ "LastIndexN", "returns", "the", "nth", "occurrence", "of", "sep", "in", "s", "or", "-", "1", "if", "there", "is", "no", "nth", "occurrence", "of", "sep", ".", "Searching", "is", "going", "from", "the", "end", "of", "the", "string", "to", "the", "start", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/strings.go#L116-L128
12,125
trivago/tgo
tstrings/strings.go
IsInt
func IsInt(s string) bool { for i, c := range s { if (c < '0' || c > '9') && (c != '-' || i != 0) { return false } } return true }
go
func IsInt(s string) bool { for i, c := range s { if (c < '0' || c > '9') && (c != '-' || i != 0) { return false } } return true }
[ "func", "IsInt", "(", "s", "string", ")", "bool", "{", "for", "i", ",", "c", ":=", "range", "s", "{", "if", "(", "c", "<", "'0'", "||", "c", ">", "'9'", ")", "&&", "(", "c", "!=", "'-'", "||", "i", "!=", "0", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// IsInt returns true if the given string can be converted to an integer. // The string must contain no whitespaces.
[ "IsInt", "returns", "true", "if", "the", "given", "string", "can", "be", "converted", "to", "an", "integer", ".", "The", "string", "must", "contain", "no", "whitespaces", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/strings.go#L132-L139
12,126
trivago/tgo
tstrings/strings.go
IsJSON
func IsJSON(data []byte) (bool, error, *json.RawMessage) { delayedResult := new(json.RawMessage) err := json.Unmarshal(data, delayedResult) return err == nil, err, delayedResult }
go
func IsJSON(data []byte) (bool, error, *json.RawMessage) { delayedResult := new(json.RawMessage) err := json.Unmarshal(data, delayedResult) return err == nil, err, delayedResult }
[ "func", "IsJSON", "(", "data", "[", "]", "byte", ")", "(", "bool", ",", "error", ",", "*", "json", ".", "RawMessage", ")", "{", "delayedResult", ":=", "new", "(", "json", ".", "RawMessage", ")", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "delayedResult", ")", "\n", "return", "err", "==", "nil", ",", "err", ",", "delayedResult", "\n\n", "}" ]
// IsJSON returns true if the given byte slice contains valid JSON data. // You can access the results by utilizing the RawMessage returned.
[ "IsJSON", "returns", "true", "if", "the", "given", "byte", "slice", "contains", "valid", "JSON", "data", ".", "You", "can", "access", "the", "results", "by", "utilizing", "the", "RawMessage", "returned", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/strings.go#L143-L148
12,127
trivago/tgo
tstrings/strings.go
NewByteRef
func NewByteRef(a string) ByteRef { stringHeader := (*reflect.StringHeader)(unsafe.Pointer(&a)) sliceHeader := &reflect.SliceHeader{ Data: stringHeader.Data, Len: stringHeader.Len, Cap: stringHeader.Len, } return *(*ByteRef)(unsafe.Pointer(sliceHeader)) }
go
func NewByteRef(a string) ByteRef { stringHeader := (*reflect.StringHeader)(unsafe.Pointer(&a)) sliceHeader := &reflect.SliceHeader{ Data: stringHeader.Data, Len: stringHeader.Len, Cap: stringHeader.Len, } return *(*ByteRef)(unsafe.Pointer(sliceHeader)) }
[ "func", "NewByteRef", "(", "a", "string", ")", "ByteRef", "{", "stringHeader", ":=", "(", "*", "reflect", ".", "StringHeader", ")", "(", "unsafe", ".", "Pointer", "(", "&", "a", ")", ")", "\n", "sliceHeader", ":=", "&", "reflect", ".", "SliceHeader", "{", "Data", ":", "stringHeader", ".", "Data", ",", "Len", ":", "stringHeader", ".", "Len", ",", "Cap", ":", "stringHeader", ".", "Len", ",", "}", "\n", "return", "*", "(", "*", "ByteRef", ")", "(", "unsafe", ".", "Pointer", "(", "sliceHeader", ")", ")", "\n", "}" ]
// NewByteRef creates an unsafe byte slice reference to the given string. // The referenced data is not guaranteed to stay valid if no reference to the // original string is held anymore. The returned ByteRef does not count as // reference. // Writing to the returned ByteRef will result in a segfault.
[ "NewByteRef", "creates", "an", "unsafe", "byte", "slice", "reference", "to", "the", "given", "string", ".", "The", "referenced", "data", "is", "not", "guaranteed", "to", "stay", "valid", "if", "no", "reference", "to", "the", "original", "string", "is", "held", "anymore", ".", "The", "returned", "ByteRef", "does", "not", "count", "as", "reference", ".", "Writing", "to", "the", "returned", "ByteRef", "will", "result", "in", "a", "segfault", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/strings.go#L160-L168
12,128
trivago/tgo
tstrings/strings.go
NewStringRef
func NewStringRef(a []byte) StringRef { sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&a)) stringHeader := &reflect.StringHeader{ Data: sliceHeader.Data, Len: sliceHeader.Len, } return *(*StringRef)(unsafe.Pointer(stringHeader)) }
go
func NewStringRef(a []byte) StringRef { sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&a)) stringHeader := &reflect.StringHeader{ Data: sliceHeader.Data, Len: sliceHeader.Len, } return *(*StringRef)(unsafe.Pointer(stringHeader)) }
[ "func", "NewStringRef", "(", "a", "[", "]", "byte", ")", "StringRef", "{", "sliceHeader", ":=", "(", "*", "reflect", ".", "SliceHeader", ")", "(", "unsafe", ".", "Pointer", "(", "&", "a", ")", ")", "\n", "stringHeader", ":=", "&", "reflect", ".", "StringHeader", "{", "Data", ":", "sliceHeader", ".", "Data", ",", "Len", ":", "sliceHeader", ".", "Len", ",", "}", "\n", "return", "*", "(", "*", "StringRef", ")", "(", "unsafe", ".", "Pointer", "(", "stringHeader", ")", ")", "\n", "}" ]
// NewStringRef creates a unsafe string reference to to the given byte slice. // The referenced data is not guaranteed to stay valid if no reference to the // original byte slice is held anymore. The returned StringRef does not count as // reference. // Changing the size of the underlying byte slice will result in a segfault.
[ "NewStringRef", "creates", "a", "unsafe", "string", "reference", "to", "to", "the", "given", "byte", "slice", ".", "The", "referenced", "data", "is", "not", "guaranteed", "to", "stay", "valid", "if", "no", "reference", "to", "the", "original", "byte", "slice", "is", "held", "anymore", ".", "The", "returned", "StringRef", "does", "not", "count", "as", "reference", ".", "Changing", "the", "size", "of", "the", "underlying", "byte", "slice", "will", "result", "in", "a", "segfault", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/strings.go#L182-L189
12,129
trivago/tgo
tstrings/strings.go
JoinStringers
func JoinStringers(a []fmt.Stringer, sep string) string { if len(a) == 0 { return "" } if len(a) == 1 { return a[0].String() } str := make([]string, len(a)) for i, s := range a { str[i] = s.String() } return strings.Join(str, sep) }
go
func JoinStringers(a []fmt.Stringer, sep string) string { if len(a) == 0 { return "" } if len(a) == 1 { return a[0].String() } str := make([]string, len(a)) for i, s := range a { str[i] = s.String() } return strings.Join(str, sep) }
[ "func", "JoinStringers", "(", "a", "[", "]", "fmt", ".", "Stringer", ",", "sep", "string", ")", "string", "{", "if", "len", "(", "a", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "if", "len", "(", "a", ")", "==", "1", "{", "return", "a", "[", "0", "]", ".", "String", "(", ")", "\n", "}", "\n\n", "str", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "a", ")", ")", "\n", "for", "i", ",", "s", ":=", "range", "a", "{", "str", "[", "i", "]", "=", "s", ".", "String", "(", ")", "\n", "}", "\n\n", "return", "strings", ".", "Join", "(", "str", ",", "sep", ")", "\n", "}" ]
// JoinStringers works like strings.Join but takes an array of fmt.Stringer.
[ "JoinStringers", "works", "like", "strings", ".", "Join", "but", "takes", "an", "array", "of", "fmt", ".", "Stringer", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/strings.go#L192-L206
12,130
trivago/tgo
tstrings/strings.go
GetNumBase
func GetNumBase(num string) (string, int) { switch { case len(num) == 0: return num, 10 case len(num) > 1 && num[0] == '0': if num[1] == 'x' { return num[2:], 16 } return num[1:], 8 } return num, 10 }
go
func GetNumBase(num string) (string, int) { switch { case len(num) == 0: return num, 10 case len(num) > 1 && num[0] == '0': if num[1] == 'x' { return num[2:], 16 } return num[1:], 8 } return num, 10 }
[ "func", "GetNumBase", "(", "num", "string", ")", "(", "string", ",", "int", ")", "{", "switch", "{", "case", "len", "(", "num", ")", "==", "0", ":", "return", "num", ",", "10", "\n\n", "case", "len", "(", "num", ")", ">", "1", "&&", "num", "[", "0", "]", "==", "'0'", ":", "if", "num", "[", "1", "]", "==", "'x'", "{", "return", "num", "[", "2", ":", "]", ",", "16", "\n", "}", "\n", "return", "num", "[", "1", ":", "]", ",", "8", "\n", "}", "\n", "return", "num", ",", "10", "\n", "}" ]
// GetNumBase scans the given string for its numeric base. If num starts with // '0x' base 16 is assumed. Just '0' assumes base 8.
[ "GetNumBase", "scans", "the", "given", "string", "for", "its", "numeric", "base", ".", "If", "num", "starts", "with", "0x", "base", "16", "is", "assumed", ".", "Just", "0", "assumes", "base", "8", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/strings.go#L222-L234
12,131
trivago/tgo
tstrings/strings.go
AtoI64
func AtoI64(num string) (int64, error) { if len(num) == 0 { return 0, nil } n, b := GetNumBase(num) return strconv.ParseInt(n, b, 64) }
go
func AtoI64(num string) (int64, error) { if len(num) == 0 { return 0, nil } n, b := GetNumBase(num) return strconv.ParseInt(n, b, 64) }
[ "func", "AtoI64", "(", "num", "string", ")", "(", "int64", ",", "error", ")", "{", "if", "len", "(", "num", ")", "==", "0", "{", "return", "0", ",", "nil", "\n", "}", "\n", "n", ",", "b", ":=", "GetNumBase", "(", "num", ")", "\n", "return", "strconv", ".", "ParseInt", "(", "n", ",", "b", ",", "64", ")", "\n", "}" ]
// AtoI64 converts a numeric string to an int64, using GetNumBase to detect // the numeric base for conversion.
[ "AtoI64", "converts", "a", "numeric", "string", "to", "an", "int64", "using", "GetNumBase", "to", "detect", "the", "numeric", "base", "for", "conversion", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/strings.go#L238-L244
12,132
trivago/tgo
tstrings/strings.go
AtoU64
func AtoU64(num string) (uint64, error) { if len(num) == 0 { return 0, nil } n, b := GetNumBase(num) return strconv.ParseUint(n, b, 64) }
go
func AtoU64(num string) (uint64, error) { if len(num) == 0 { return 0, nil } n, b := GetNumBase(num) return strconv.ParseUint(n, b, 64) }
[ "func", "AtoU64", "(", "num", "string", ")", "(", "uint64", ",", "error", ")", "{", "if", "len", "(", "num", ")", "==", "0", "{", "return", "0", ",", "nil", "\n", "}", "\n", "n", ",", "b", ":=", "GetNumBase", "(", "num", ")", "\n", "return", "strconv", ".", "ParseUint", "(", "n", ",", "b", ",", "64", ")", "\n", "}" ]
// AtoU64 converts a numeric string to an uint64, using GetNumBase to detect // the numeric base for conversion.
[ "AtoU64", "converts", "a", "numeric", "string", "to", "an", "uint64", "using", "GetNumBase", "to", "detect", "the", "numeric", "base", "for", "conversion", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/strings.go#L248-L254
12,133
boj/redistore
redistore.go
Serialize
func (s JSONSerializer) Serialize(ss *sessions.Session) ([]byte, error) { m := make(map[string]interface{}, len(ss.Values)) for k, v := range ss.Values { ks, ok := k.(string) if !ok { err := fmt.Errorf("Non-string key value, cannot serialize session to JSON: %v", k) fmt.Printf("redistore.JSONSerializer.serialize() Error: %v", err) return nil, err } m[ks] = v } return json.Marshal(m) }
go
func (s JSONSerializer) Serialize(ss *sessions.Session) ([]byte, error) { m := make(map[string]interface{}, len(ss.Values)) for k, v := range ss.Values { ks, ok := k.(string) if !ok { err := fmt.Errorf("Non-string key value, cannot serialize session to JSON: %v", k) fmt.Printf("redistore.JSONSerializer.serialize() Error: %v", err) return nil, err } m[ks] = v } return json.Marshal(m) }
[ "func", "(", "s", "JSONSerializer", ")", "Serialize", "(", "ss", "*", "sessions", ".", "Session", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "m", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "len", "(", "ss", ".", "Values", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "ss", ".", "Values", "{", "ks", ",", "ok", ":=", "k", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "m", "[", "ks", "]", "=", "v", "\n", "}", "\n", "return", "json", ".", "Marshal", "(", "m", ")", "\n", "}" ]
// Serialize to JSON. Will err if there are unmarshalable key values
[ "Serialize", "to", "JSON", ".", "Will", "err", "if", "there", "are", "unmarshalable", "key", "values" ]
cd5dcc76aeff9ba06b0a924829fe24fd69cdd517
https://github.com/boj/redistore/blob/cd5dcc76aeff9ba06b0a924829fe24fd69cdd517/redistore.go#L36-L48
12,134
boj/redistore
redistore.go
Serialize
func (s GobSerializer) Serialize(ss *sessions.Session) ([]byte, error) { buf := new(bytes.Buffer) enc := gob.NewEncoder(buf) err := enc.Encode(ss.Values) if err == nil { return buf.Bytes(), nil } return nil, err }
go
func (s GobSerializer) Serialize(ss *sessions.Session) ([]byte, error) { buf := new(bytes.Buffer) enc := gob.NewEncoder(buf) err := enc.Encode(ss.Values) if err == nil { return buf.Bytes(), nil } return nil, err }
[ "func", "(", "s", "GobSerializer", ")", "Serialize", "(", "ss", "*", "sessions", ".", "Session", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "enc", ":=", "gob", ".", "NewEncoder", "(", "buf", ")", "\n", "err", ":=", "enc", ".", "Encode", "(", "ss", ".", "Values", ")", "\n", "if", "err", "==", "nil", "{", "return", "buf", ".", "Bytes", "(", ")", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}" ]
// Serialize using gob
[ "Serialize", "using", "gob" ]
cd5dcc76aeff9ba06b0a924829fe24fd69cdd517
https://github.com/boj/redistore/blob/cd5dcc76aeff9ba06b0a924829fe24fd69cdd517/redistore.go#L68-L76
12,135
boj/redistore
redistore.go
ping
func (s *RediStore) ping() (bool, error) { conn := s.Pool.Get() defer conn.Close() data, err := conn.Do("PING") if err != nil || data == nil { return false, err } return (data == "PONG"), nil }
go
func (s *RediStore) ping() (bool, error) { conn := s.Pool.Get() defer conn.Close() data, err := conn.Do("PING") if err != nil || data == nil { return false, err } return (data == "PONG"), nil }
[ "func", "(", "s", "*", "RediStore", ")", "ping", "(", ")", "(", "bool", ",", "error", ")", "{", "conn", ":=", "s", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "conn", ".", "Close", "(", ")", "\n", "data", ",", "err", ":=", "conn", ".", "Do", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "||", "data", "==", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "return", "(", "data", "==", "\"", "\"", ")", ",", "nil", "\n", "}" ]
// ping does an internal ping against a server to check if it is alive.
[ "ping", "does", "an", "internal", "ping", "against", "a", "server", "to", "check", "if", "it", "is", "alive", "." ]
cd5dcc76aeff9ba06b0a924829fe24fd69cdd517
https://github.com/boj/redistore/blob/cd5dcc76aeff9ba06b0a924829fe24fd69cdd517/redistore.go#L299-L307
12,136
boj/redistore
redistore.go
save
func (s *RediStore) save(session *sessions.Session) error { b, err := s.serializer.Serialize(session) if err != nil { return err } if s.maxLength != 0 && len(b) > s.maxLength { return errors.New("SessionStore: the value to store is too big") } conn := s.Pool.Get() defer conn.Close() if err = conn.Err(); err != nil { return err } age := session.Options.MaxAge if age == 0 { age = s.DefaultMaxAge } _, err = conn.Do("SETEX", s.keyPrefix+session.ID, age, b) return err }
go
func (s *RediStore) save(session *sessions.Session) error { b, err := s.serializer.Serialize(session) if err != nil { return err } if s.maxLength != 0 && len(b) > s.maxLength { return errors.New("SessionStore: the value to store is too big") } conn := s.Pool.Get() defer conn.Close() if err = conn.Err(); err != nil { return err } age := session.Options.MaxAge if age == 0 { age = s.DefaultMaxAge } _, err = conn.Do("SETEX", s.keyPrefix+session.ID, age, b) return err }
[ "func", "(", "s", "*", "RediStore", ")", "save", "(", "session", "*", "sessions", ".", "Session", ")", "error", "{", "b", ",", "err", ":=", "s", ".", "serializer", ".", "Serialize", "(", "session", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "s", ".", "maxLength", "!=", "0", "&&", "len", "(", "b", ")", ">", "s", ".", "maxLength", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "conn", ":=", "s", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "conn", ".", "Close", "(", ")", "\n", "if", "err", "=", "conn", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "age", ":=", "session", ".", "Options", ".", "MaxAge", "\n", "if", "age", "==", "0", "{", "age", "=", "s", ".", "DefaultMaxAge", "\n", "}", "\n", "_", ",", "err", "=", "conn", ".", "Do", "(", "\"", "\"", ",", "s", ".", "keyPrefix", "+", "session", ".", "ID", ",", "age", ",", "b", ")", "\n", "return", "err", "\n", "}" ]
// save stores the session in redis.
[ "save", "stores", "the", "session", "in", "redis", "." ]
cd5dcc76aeff9ba06b0a924829fe24fd69cdd517
https://github.com/boj/redistore/blob/cd5dcc76aeff9ba06b0a924829fe24fd69cdd517/redistore.go#L310-L329
12,137
boj/redistore
redistore.go
load
func (s *RediStore) load(session *sessions.Session) (bool, error) { conn := s.Pool.Get() defer conn.Close() if err := conn.Err(); err != nil { return false, err } data, err := conn.Do("GET", s.keyPrefix+session.ID) if err != nil { return false, err } if data == nil { return false, nil // no data was associated with this key } b, err := redis.Bytes(data, err) if err != nil { return false, err } return true, s.serializer.Deserialize(b, session) }
go
func (s *RediStore) load(session *sessions.Session) (bool, error) { conn := s.Pool.Get() defer conn.Close() if err := conn.Err(); err != nil { return false, err } data, err := conn.Do("GET", s.keyPrefix+session.ID) if err != nil { return false, err } if data == nil { return false, nil // no data was associated with this key } b, err := redis.Bytes(data, err) if err != nil { return false, err } return true, s.serializer.Deserialize(b, session) }
[ "func", "(", "s", "*", "RediStore", ")", "load", "(", "session", "*", "sessions", ".", "Session", ")", "(", "bool", ",", "error", ")", "{", "conn", ":=", "s", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "conn", ".", "Close", "(", ")", "\n", "if", "err", ":=", "conn", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "data", ",", "err", ":=", "conn", ".", "Do", "(", "\"", "\"", ",", "s", ".", "keyPrefix", "+", "session", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "if", "data", "==", "nil", "{", "return", "false", ",", "nil", "// no data was associated with this key", "\n", "}", "\n", "b", ",", "err", ":=", "redis", ".", "Bytes", "(", "data", ",", "err", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "return", "true", ",", "s", ".", "serializer", ".", "Deserialize", "(", "b", ",", "session", ")", "\n", "}" ]
// load reads the session from redis. // returns true if there is a sessoin data in DB
[ "load", "reads", "the", "session", "from", "redis", ".", "returns", "true", "if", "there", "is", "a", "sessoin", "data", "in", "DB" ]
cd5dcc76aeff9ba06b0a924829fe24fd69cdd517
https://github.com/boj/redistore/blob/cd5dcc76aeff9ba06b0a924829fe24fd69cdd517/redistore.go#L333-L351
12,138
boj/redistore
redistore.go
delete
func (s *RediStore) delete(session *sessions.Session) error { conn := s.Pool.Get() defer conn.Close() if _, err := conn.Do("DEL", s.keyPrefix+session.ID); err != nil { return err } return nil }
go
func (s *RediStore) delete(session *sessions.Session) error { conn := s.Pool.Get() defer conn.Close() if _, err := conn.Do("DEL", s.keyPrefix+session.ID); err != nil { return err } return nil }
[ "func", "(", "s", "*", "RediStore", ")", "delete", "(", "session", "*", "sessions", ".", "Session", ")", "error", "{", "conn", ":=", "s", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "conn", ".", "Close", "(", ")", "\n", "if", "_", ",", "err", ":=", "conn", ".", "Do", "(", "\"", "\"", ",", "s", ".", "keyPrefix", "+", "session", ".", "ID", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// delete removes keys from redis if MaxAge<0
[ "delete", "removes", "keys", "from", "redis", "if", "MaxAge<0" ]
cd5dcc76aeff9ba06b0a924829fe24fd69cdd517
https://github.com/boj/redistore/blob/cd5dcc76aeff9ba06b0a924829fe24fd69cdd517/redistore.go#L354-L361
12,139
modern-go/concurrent
go_below_19.go
Load
func (m *Map) Load(key interface{}) (elem interface{}, found bool) { m.lock.RLock() elem, found = m.data[key] m.lock.RUnlock() return }
go
func (m *Map) Load(key interface{}) (elem interface{}, found bool) { m.lock.RLock() elem, found = m.data[key] m.lock.RUnlock() return }
[ "func", "(", "m", "*", "Map", ")", "Load", "(", "key", "interface", "{", "}", ")", "(", "elem", "interface", "{", "}", ",", "found", "bool", ")", "{", "m", ".", "lock", ".", "RLock", "(", ")", "\n", "elem", ",", "found", "=", "m", ".", "data", "[", "key", "]", "\n", "m", ".", "lock", ".", "RUnlock", "(", ")", "\n", "return", "\n", "}" ]
// Load is same as sync.Map Load
[ "Load", "is", "same", "as", "sync", ".", "Map", "Load" ]
bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94
https://github.com/modern-go/concurrent/blob/bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94/go_below_19.go#L21-L26
12,140
modern-go/concurrent
go_below_19.go
Store
func (m *Map) Store(key interface{}, elem interface{}) { m.lock.Lock() m.data[key] = elem m.lock.Unlock() }
go
func (m *Map) Store(key interface{}, elem interface{}) { m.lock.Lock() m.data[key] = elem m.lock.Unlock() }
[ "func", "(", "m", "*", "Map", ")", "Store", "(", "key", "interface", "{", "}", ",", "elem", "interface", "{", "}", ")", "{", "m", ".", "lock", ".", "Lock", "(", ")", "\n", "m", ".", "data", "[", "key", "]", "=", "elem", "\n", "m", ".", "lock", ".", "Unlock", "(", ")", "\n", "}" ]
// Load is same as sync.Map Store
[ "Load", "is", "same", "as", "sync", ".", "Map", "Store" ]
bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94
https://github.com/modern-go/concurrent/blob/bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94/go_below_19.go#L29-L33
12,141
modern-go/concurrent
unbounded_executor.go
Go
func (executor *UnboundedExecutor) Go(handler func(ctx context.Context)) { pc := reflect.ValueOf(handler).Pointer() f := runtime.FuncForPC(pc) funcName := f.Name() file, line := f.FileLine(pc) executor.activeGoroutinesMutex.Lock() defer executor.activeGoroutinesMutex.Unlock() startFrom := fmt.Sprintf("%s:%d", file, line) executor.activeGoroutines[startFrom] += 1 go func() { defer func() { recovered := recover() // if you want to quit a goroutine without trigger HandlePanic // use runtime.Goexit() to quit if recovered != nil { if executor.HandlePanic == nil { HandlePanic(recovered, funcName) } else { executor.HandlePanic(recovered, funcName) } } executor.activeGoroutinesMutex.Lock() executor.activeGoroutines[startFrom] -= 1 executor.activeGoroutinesMutex.Unlock() }() handler(executor.ctx) }() }
go
func (executor *UnboundedExecutor) Go(handler func(ctx context.Context)) { pc := reflect.ValueOf(handler).Pointer() f := runtime.FuncForPC(pc) funcName := f.Name() file, line := f.FileLine(pc) executor.activeGoroutinesMutex.Lock() defer executor.activeGoroutinesMutex.Unlock() startFrom := fmt.Sprintf("%s:%d", file, line) executor.activeGoroutines[startFrom] += 1 go func() { defer func() { recovered := recover() // if you want to quit a goroutine without trigger HandlePanic // use runtime.Goexit() to quit if recovered != nil { if executor.HandlePanic == nil { HandlePanic(recovered, funcName) } else { executor.HandlePanic(recovered, funcName) } } executor.activeGoroutinesMutex.Lock() executor.activeGoroutines[startFrom] -= 1 executor.activeGoroutinesMutex.Unlock() }() handler(executor.ctx) }() }
[ "func", "(", "executor", "*", "UnboundedExecutor", ")", "Go", "(", "handler", "func", "(", "ctx", "context", ".", "Context", ")", ")", "{", "pc", ":=", "reflect", ".", "ValueOf", "(", "handler", ")", ".", "Pointer", "(", ")", "\n", "f", ":=", "runtime", ".", "FuncForPC", "(", "pc", ")", "\n", "funcName", ":=", "f", ".", "Name", "(", ")", "\n", "file", ",", "line", ":=", "f", ".", "FileLine", "(", "pc", ")", "\n", "executor", ".", "activeGoroutinesMutex", ".", "Lock", "(", ")", "\n", "defer", "executor", ".", "activeGoroutinesMutex", ".", "Unlock", "(", ")", "\n", "startFrom", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "file", ",", "line", ")", "\n", "executor", ".", "activeGoroutines", "[", "startFrom", "]", "+=", "1", "\n", "go", "func", "(", ")", "{", "defer", "func", "(", ")", "{", "recovered", ":=", "recover", "(", ")", "\n", "// if you want to quit a goroutine without trigger HandlePanic", "// use runtime.Goexit() to quit", "if", "recovered", "!=", "nil", "{", "if", "executor", ".", "HandlePanic", "==", "nil", "{", "HandlePanic", "(", "recovered", ",", "funcName", ")", "\n", "}", "else", "{", "executor", ".", "HandlePanic", "(", "recovered", ",", "funcName", ")", "\n", "}", "\n", "}", "\n", "executor", ".", "activeGoroutinesMutex", ".", "Lock", "(", ")", "\n", "executor", ".", "activeGoroutines", "[", "startFrom", "]", "-=", "1", "\n", "executor", ".", "activeGoroutinesMutex", ".", "Unlock", "(", ")", "\n", "}", "(", ")", "\n", "handler", "(", "executor", ".", "ctx", ")", "\n", "}", "(", ")", "\n", "}" ]
// Go starts a new goroutine and tracks its lifecycle. // Panic will be recovered and logged automatically, except for StopSignal
[ "Go", "starts", "a", "new", "goroutine", "and", "tracks", "its", "lifecycle", ".", "Panic", "will", "be", "recovered", "and", "logged", "automatically", "except", "for", "StopSignal" ]
bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94
https://github.com/modern-go/concurrent/blob/bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94/unbounded_executor.go#L50-L77
12,142
modern-go/concurrent
unbounded_executor.go
StopAndWait
func (executor *UnboundedExecutor) StopAndWait(ctx context.Context) { executor.cancel() for { oneHundredMilliseconds := time.NewTimer(time.Millisecond * 100) select { case <-oneHundredMilliseconds.C: if executor.checkNoActiveGoroutines() { return } case <-ctx.Done(): return } } }
go
func (executor *UnboundedExecutor) StopAndWait(ctx context.Context) { executor.cancel() for { oneHundredMilliseconds := time.NewTimer(time.Millisecond * 100) select { case <-oneHundredMilliseconds.C: if executor.checkNoActiveGoroutines() { return } case <-ctx.Done(): return } } }
[ "func", "(", "executor", "*", "UnboundedExecutor", ")", "StopAndWait", "(", "ctx", "context", ".", "Context", ")", "{", "executor", ".", "cancel", "(", ")", "\n", "for", "{", "oneHundredMilliseconds", ":=", "time", ".", "NewTimer", "(", "time", ".", "Millisecond", "*", "100", ")", "\n", "select", "{", "case", "<-", "oneHundredMilliseconds", ".", "C", ":", "if", "executor", ".", "checkNoActiveGoroutines", "(", ")", "{", "return", "\n", "}", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// StopAndWait cancel all goroutines started by this executor and wait. // Wait can be cancelled by the context passed in.
[ "StopAndWait", "cancel", "all", "goroutines", "started", "by", "this", "executor", "and", "wait", ".", "Wait", "can", "be", "cancelled", "by", "the", "context", "passed", "in", "." ]
bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94
https://github.com/modern-go/concurrent/blob/bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94/unbounded_executor.go#L92-L105
12,143
segmentio/stats
influxdb/measure.go
AppendMeasure
func AppendMeasure(b []byte, t time.Time, m stats.Measure) []byte { b = append(b, m.Name...) for _, tag := range m.Tags { b = append(b, ',') b = append(b, tag.Name...) b = append(b, '=') b = append(b, tag.Value...) } for i, field := range m.Fields { if len(field.Name) == 0 { field.Name = "value" } if i == 0 { b = append(b, ' ') } else { b = append(b, ',') } b = append(b, field.Name...) b = append(b, '=') switch v := field.Value; v.Type() { case stats.Null: case stats.Bool: if v.Bool() { b = append(b, "true"...) } else { b = append(b, "false"...) } case stats.Int: b = strconv.AppendInt(b, v.Int(), 10) case stats.Uint: b = strconv.AppendUint(b, v.Uint(), 10) case stats.Float: b = strconv.AppendFloat(b, v.Float(), 'g', -1, 64) case stats.Duration: b = strconv.AppendFloat(b, v.Duration().Seconds(), 'g', -1, 64) } } b = append(b, ' ') b = strconv.AppendInt(b, t.UnixNano(), 10) return append(b, '\n') }
go
func AppendMeasure(b []byte, t time.Time, m stats.Measure) []byte { b = append(b, m.Name...) for _, tag := range m.Tags { b = append(b, ',') b = append(b, tag.Name...) b = append(b, '=') b = append(b, tag.Value...) } for i, field := range m.Fields { if len(field.Name) == 0 { field.Name = "value" } if i == 0 { b = append(b, ' ') } else { b = append(b, ',') } b = append(b, field.Name...) b = append(b, '=') switch v := field.Value; v.Type() { case stats.Null: case stats.Bool: if v.Bool() { b = append(b, "true"...) } else { b = append(b, "false"...) } case stats.Int: b = strconv.AppendInt(b, v.Int(), 10) case stats.Uint: b = strconv.AppendUint(b, v.Uint(), 10) case stats.Float: b = strconv.AppendFloat(b, v.Float(), 'g', -1, 64) case stats.Duration: b = strconv.AppendFloat(b, v.Duration().Seconds(), 'g', -1, 64) } } b = append(b, ' ') b = strconv.AppendInt(b, t.UnixNano(), 10) return append(b, '\n') }
[ "func", "AppendMeasure", "(", "b", "[", "]", "byte", ",", "t", "time", ".", "Time", ",", "m", "stats", ".", "Measure", ")", "[", "]", "byte", "{", "b", "=", "append", "(", "b", ",", "m", ".", "Name", "...", ")", "\n\n", "for", "_", ",", "tag", ":=", "range", "m", ".", "Tags", "{", "b", "=", "append", "(", "b", ",", "','", ")", "\n", "b", "=", "append", "(", "b", ",", "tag", ".", "Name", "...", ")", "\n", "b", "=", "append", "(", "b", ",", "'='", ")", "\n", "b", "=", "append", "(", "b", ",", "tag", ".", "Value", "...", ")", "\n", "}", "\n\n", "for", "i", ",", "field", ":=", "range", "m", ".", "Fields", "{", "if", "len", "(", "field", ".", "Name", ")", "==", "0", "{", "field", ".", "Name", "=", "\"", "\"", "\n", "}", "\n\n", "if", "i", "==", "0", "{", "b", "=", "append", "(", "b", ",", "' '", ")", "\n", "}", "else", "{", "b", "=", "append", "(", "b", ",", "','", ")", "\n", "}", "\n\n", "b", "=", "append", "(", "b", ",", "field", ".", "Name", "...", ")", "\n", "b", "=", "append", "(", "b", ",", "'='", ")", "\n\n", "switch", "v", ":=", "field", ".", "Value", ";", "v", ".", "Type", "(", ")", "{", "case", "stats", ".", "Null", ":", "case", "stats", ".", "Bool", ":", "if", "v", ".", "Bool", "(", ")", "{", "b", "=", "append", "(", "b", ",", "\"", "\"", "...", ")", "\n", "}", "else", "{", "b", "=", "append", "(", "b", ",", "\"", "\"", "...", ")", "\n", "}", "\n", "case", "stats", ".", "Int", ":", "b", "=", "strconv", ".", "AppendInt", "(", "b", ",", "v", ".", "Int", "(", ")", ",", "10", ")", "\n", "case", "stats", ".", "Uint", ":", "b", "=", "strconv", ".", "AppendUint", "(", "b", ",", "v", ".", "Uint", "(", ")", ",", "10", ")", "\n", "case", "stats", ".", "Float", ":", "b", "=", "strconv", ".", "AppendFloat", "(", "b", ",", "v", ".", "Float", "(", ")", ",", "'g'", ",", "-", "1", ",", "64", ")", "\n", "case", "stats", ".", "Duration", ":", "b", "=", "strconv", ".", "AppendFloat", "(", "b", ",", "v", ".", "Duration", "(", ")", ".", "Seconds", "(", ")", ",", "'g'", ",", "-", "1", ",", "64", ")", "\n", "}", "\n", "}", "\n\n", "b", "=", "append", "(", "b", ",", "' '", ")", "\n", "b", "=", "strconv", ".", "AppendInt", "(", "b", ",", "t", ".", "UnixNano", "(", ")", ",", "10", ")", "\n\n", "return", "append", "(", "b", ",", "'\\n'", ")", "\n", "}" ]
// AppendMeasure is a formatting routine to append the InflxDB line protocol // representation of a measure to a memory buffer.
[ "AppendMeasure", "is", "a", "formatting", "routine", "to", "append", "the", "InflxDB", "line", "protocol", "representation", "of", "a", "measure", "to", "a", "memory", "buffer", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/influxdb/measure.go#L12-L59
12,144
segmentio/stats
engine.go
NewEngine
func NewEngine(prefix string, handler Handler, tags ...Tag) *Engine { return &Engine{ Handler: handler, Prefix: prefix, Tags: SortTags(copyTags(tags)), } }
go
func NewEngine(prefix string, handler Handler, tags ...Tag) *Engine { return &Engine{ Handler: handler, Prefix: prefix, Tags: SortTags(copyTags(tags)), } }
[ "func", "NewEngine", "(", "prefix", "string", ",", "handler", "Handler", ",", "tags", "...", "Tag", ")", "*", "Engine", "{", "return", "&", "Engine", "{", "Handler", ":", "handler", ",", "Prefix", ":", "prefix", ",", "Tags", ":", "SortTags", "(", "copyTags", "(", "tags", ")", ")", ",", "}", "\n", "}" ]
// NewEngine creates and returns a new engine configured with prefix, handler, // and tags.
[ "NewEngine", "creates", "and", "returns", "a", "new", "engine", "configured", "with", "prefix", "handler", "and", "tags", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/engine.go#L42-L48
12,145
segmentio/stats
engine.go
Register
func (eng *Engine) Register(handler Handler) { if eng.Handler == Discard { eng.Handler = handler } else { eng.Handler = MultiHandler(eng.Handler, handler) } }
go
func (eng *Engine) Register(handler Handler) { if eng.Handler == Discard { eng.Handler = handler } else { eng.Handler = MultiHandler(eng.Handler, handler) } }
[ "func", "(", "eng", "*", "Engine", ")", "Register", "(", "handler", "Handler", ")", "{", "if", "eng", ".", "Handler", "==", "Discard", "{", "eng", ".", "Handler", "=", "handler", "\n", "}", "else", "{", "eng", ".", "Handler", "=", "MultiHandler", "(", "eng", ".", "Handler", ",", "handler", ")", "\n", "}", "\n", "}" ]
// Register adds handler to eng.
[ "Register", "adds", "handler", "to", "eng", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/engine.go#L51-L57
12,146
segmentio/stats
engine.go
WithPrefix
func (eng *Engine) WithPrefix(prefix string, tags ...Tag) *Engine { return &Engine{ Handler: eng.Handler, Prefix: eng.makeName(prefix), Tags: eng.makeTags(tags), } }
go
func (eng *Engine) WithPrefix(prefix string, tags ...Tag) *Engine { return &Engine{ Handler: eng.Handler, Prefix: eng.makeName(prefix), Tags: eng.makeTags(tags), } }
[ "func", "(", "eng", "*", "Engine", ")", "WithPrefix", "(", "prefix", "string", ",", "tags", "...", "Tag", ")", "*", "Engine", "{", "return", "&", "Engine", "{", "Handler", ":", "eng", ".", "Handler", ",", "Prefix", ":", "eng", ".", "makeName", "(", "prefix", ")", ",", "Tags", ":", "eng", ".", "makeTags", "(", "tags", ")", ",", "}", "\n", "}" ]
// WithPrefix returns a copy of the engine with prefix appended to eng's current // prefix and tags set to the merge of eng's current tags and those passed as // argument. Both eng and the returned engine share the same handler.
[ "WithPrefix", "returns", "a", "copy", "of", "the", "engine", "with", "prefix", "appended", "to", "eng", "s", "current", "prefix", "and", "tags", "set", "to", "the", "merge", "of", "eng", "s", "current", "tags", "and", "those", "passed", "as", "argument", ".", "Both", "eng", "and", "the", "returned", "engine", "share", "the", "same", "handler", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/engine.go#L67-L73
12,147
segmentio/stats
engine.go
Clock
func (eng *Engine) Clock(name string, tags ...Tag) *Clock { return eng.ClockAt(name, time.Now(), tags...) }
go
func (eng *Engine) Clock(name string, tags ...Tag) *Clock { return eng.ClockAt(name, time.Now(), tags...) }
[ "func", "(", "eng", "*", "Engine", ")", "Clock", "(", "name", "string", ",", "tags", "...", "Tag", ")", "*", "Clock", "{", "return", "eng", ".", "ClockAt", "(", "name", ",", "time", ".", "Now", "(", ")", ",", "tags", "...", ")", "\n", "}" ]
// Clock returns a new clock identified by name and tags.
[ "Clock", "returns", "a", "new", "clock", "identified", "by", "name", "and", "tags", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/engine.go#L123-L125
12,148
segmentio/stats
engine.go
ClockAt
func (eng *Engine) ClockAt(name string, start time.Time, tags ...Tag) *Clock { cpy := make([]Tag, len(tags), len(tags)+1) // clock always appends a stamp. copy(cpy, tags) return &Clock{ name: name, first: start, last: start, tags: cpy, eng: eng, } }
go
func (eng *Engine) ClockAt(name string, start time.Time, tags ...Tag) *Clock { cpy := make([]Tag, len(tags), len(tags)+1) // clock always appends a stamp. copy(cpy, tags) return &Clock{ name: name, first: start, last: start, tags: cpy, eng: eng, } }
[ "func", "(", "eng", "*", "Engine", ")", "ClockAt", "(", "name", "string", ",", "start", "time", ".", "Time", ",", "tags", "...", "Tag", ")", "*", "Clock", "{", "cpy", ":=", "make", "(", "[", "]", "Tag", ",", "len", "(", "tags", ")", ",", "len", "(", "tags", ")", "+", "1", ")", "// clock always appends a stamp.", "\n", "copy", "(", "cpy", ",", "tags", ")", "\n", "return", "&", "Clock", "{", "name", ":", "name", ",", "first", ":", "start", ",", "last", ":", "start", ",", "tags", ":", "cpy", ",", "eng", ":", "eng", ",", "}", "\n", "}" ]
// ClockAt returns a new clock identified by name and tags with a specified // start time.
[ "ClockAt", "returns", "a", "new", "clock", "identified", "by", "name", "and", "tags", "with", "a", "specified", "start", "time", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/engine.go#L129-L139
12,149
segmentio/stats
engine.go
ReportAt
func (eng *Engine) ReportAt(time time.Time, metrics interface{}, tags ...Tag) { var tb *tagsBuffer if len(tags) == 0 { // fast path for the common case where there are no dynamic tags tags = eng.Tags } else { tb = tagsPool.Get().(*tagsBuffer) tb.append(tags...) tb.append(eng.Tags...) tb.sort() tags = tb.tags } mb := measurePool.Get().(*measuresBuffer) mb.measures = appendMeasures(mb.measures[:0], &eng.cache, eng.Prefix, reflect.ValueOf(metrics), tags...) ms := mb.measures eng.Handler.HandleMeasures(time, ms...) for i := range ms { ms[i].reset() } if tb != nil { tb.reset() tagsPool.Put(tb) } measurePool.Put(mb) }
go
func (eng *Engine) ReportAt(time time.Time, metrics interface{}, tags ...Tag) { var tb *tagsBuffer if len(tags) == 0 { // fast path for the common case where there are no dynamic tags tags = eng.Tags } else { tb = tagsPool.Get().(*tagsBuffer) tb.append(tags...) tb.append(eng.Tags...) tb.sort() tags = tb.tags } mb := measurePool.Get().(*measuresBuffer) mb.measures = appendMeasures(mb.measures[:0], &eng.cache, eng.Prefix, reflect.ValueOf(metrics), tags...) ms := mb.measures eng.Handler.HandleMeasures(time, ms...) for i := range ms { ms[i].reset() } if tb != nil { tb.reset() tagsPool.Put(tb) } measurePool.Put(mb) }
[ "func", "(", "eng", "*", "Engine", ")", "ReportAt", "(", "time", "time", ".", "Time", ",", "metrics", "interface", "{", "}", ",", "tags", "...", "Tag", ")", "{", "var", "tb", "*", "tagsBuffer", "\n\n", "if", "len", "(", "tags", ")", "==", "0", "{", "// fast path for the common case where there are no dynamic tags", "tags", "=", "eng", ".", "Tags", "\n", "}", "else", "{", "tb", "=", "tagsPool", ".", "Get", "(", ")", ".", "(", "*", "tagsBuffer", ")", "\n", "tb", ".", "append", "(", "tags", "...", ")", "\n", "tb", ".", "append", "(", "eng", ".", "Tags", "...", ")", "\n", "tb", ".", "sort", "(", ")", "\n", "tags", "=", "tb", ".", "tags", "\n", "}", "\n\n", "mb", ":=", "measurePool", ".", "Get", "(", ")", ".", "(", "*", "measuresBuffer", ")", "\n", "mb", ".", "measures", "=", "appendMeasures", "(", "mb", ".", "measures", "[", ":", "0", "]", ",", "&", "eng", ".", "cache", ",", "eng", ".", "Prefix", ",", "reflect", ".", "ValueOf", "(", "metrics", ")", ",", "tags", "...", ")", "\n\n", "ms", ":=", "mb", ".", "measures", "\n", "eng", ".", "Handler", ".", "HandleMeasures", "(", "time", ",", "ms", "...", ")", "\n\n", "for", "i", ":=", "range", "ms", "{", "ms", "[", "i", "]", ".", "reset", "(", ")", "\n", "}", "\n\n", "if", "tb", "!=", "nil", "{", "tb", ".", "reset", "(", ")", "\n", "tagsPool", ".", "Put", "(", "tb", ")", "\n", "}", "\n\n", "measurePool", ".", "Put", "(", "mb", ")", "\n", "}" ]
// ReportAt reports a set of metrics for a given time. The metrics must be of // type struct, pointer to struct, or a slice or array to one of those. See // MakeMeasures for details about how to make struct types exposing metrics.
[ "ReportAt", "reports", "a", "set", "of", "metrics", "for", "a", "given", "time", ".", "The", "metrics", "must", "be", "of", "type", "struct", "pointer", "to", "struct", "or", "a", "slice", "or", "array", "to", "one", "of", "those", ".", "See", "MakeMeasures", "for", "details", "about", "how", "to", "make", "struct", "types", "exposing", "metrics", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/engine.go#L189-L219
12,150
segmentio/stats
engine.go
WithPrefix
func WithPrefix(prefix string, tags ...Tag) *Engine { return DefaultEngine.WithPrefix(prefix, tags...) }
go
func WithPrefix(prefix string, tags ...Tag) *Engine { return DefaultEngine.WithPrefix(prefix, tags...) }
[ "func", "WithPrefix", "(", "prefix", "string", ",", "tags", "...", "Tag", ")", "*", "Engine", "{", "return", "DefaultEngine", ".", "WithPrefix", "(", "prefix", ",", "tags", "...", ")", "\n", "}" ]
// WithPrefix returns a copy of the engine with prefix appended to default // engine's current prefix and tags set to the merge of eng's current tags and // those passed as argument. Both the default engine and the returned engine // share the same handler.
[ "WithPrefix", "returns", "a", "copy", "of", "the", "engine", "with", "prefix", "appended", "to", "default", "engine", "s", "current", "prefix", "and", "tags", "set", "to", "the", "merge", "of", "eng", "s", "current", "tags", "and", "those", "passed", "as", "argument", ".", "Both", "the", "default", "engine", "and", "the", "returned", "engine", "share", "the", "same", "handler", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/engine.go#L238-L240
12,151
segmentio/stats
engine.go
IncrAt
func IncrAt(time time.Time, name string, tags ...Tag) { DefaultEngine.IncrAt(time, name, tags...) }
go
func IncrAt(time time.Time, name string, tags ...Tag) { DefaultEngine.IncrAt(time, name, tags...) }
[ "func", "IncrAt", "(", "time", "time", ".", "Time", ",", "name", "string", ",", "tags", "...", "Tag", ")", "{", "DefaultEngine", ".", "IncrAt", "(", "time", ",", "name", ",", "tags", "...", ")", "\n", "}" ]
// IncrAt increments by one the counter identified by name and tags.
[ "IncrAt", "increments", "by", "one", "the", "counter", "identified", "by", "name", "and", "tags", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/engine.go#L255-L257
12,152
segmentio/stats
engine.go
ObserveAt
func ObserveAt(time time.Time, name string, value interface{}, tags ...Tag) { DefaultEngine.ObserveAt(time, name, value, tags...) }
go
func ObserveAt(time time.Time, name string, value interface{}, tags ...Tag) { DefaultEngine.ObserveAt(time, name, value, tags...) }
[ "func", "ObserveAt", "(", "time", "time", ".", "Time", ",", "name", "string", ",", "value", "interface", "{", "}", ",", "tags", "...", "Tag", ")", "{", "DefaultEngine", ".", "ObserveAt", "(", "time", ",", "name", ",", "value", ",", "tags", "...", ")", "\n", "}" ]
// ObserveAt reports value for the histogram identified by name and tags.
[ "ObserveAt", "reports", "value", "for", "the", "histogram", "identified", "by", "name", "and", "tags", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/engine.go#L285-L287
12,153
segmentio/stats
engine.go
ReportAt
func ReportAt(time time.Time, metrics interface{}, tags ...Tag) { DefaultEngine.ReportAt(time, metrics, tags...) }
go
func ReportAt(time time.Time, metrics interface{}, tags ...Tag) { DefaultEngine.ReportAt(time, metrics, tags...) }
[ "func", "ReportAt", "(", "time", "time", ".", "Time", ",", "metrics", "interface", "{", "}", ",", "tags", "...", "Tag", ")", "{", "DefaultEngine", ".", "ReportAt", "(", "time", ",", "metrics", ",", "tags", "...", ")", "\n", "}" ]
// ReportAt is a helper function that delegates to DefaultEngine.
[ "ReportAt", "is", "a", "helper", "function", "that", "delegates", "to", "DefaultEngine", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/engine.go#L295-L297
12,154
segmentio/stats
datadog/measure.go
AppendMeasure
func AppendMeasure(b []byte, m stats.Measure) []byte { return AppendMeasureFiltered(b, m, nil) }
go
func AppendMeasure(b []byte, m stats.Measure) []byte { return AppendMeasureFiltered(b, m, nil) }
[ "func", "AppendMeasure", "(", "b", "[", "]", "byte", ",", "m", "stats", ".", "Measure", ")", "[", "]", "byte", "{", "return", "AppendMeasureFiltered", "(", "b", ",", "m", ",", "nil", ")", "\n", "}" ]
// AppendMeasure is a formatting routine to append the dogstatsd protocol // representation of a measure to a memory buffer.
[ "AppendMeasure", "is", "a", "formatting", "routine", "to", "append", "the", "dogstatsd", "protocol", "representation", "of", "a", "measure", "to", "a", "memory", "buffer", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/datadog/measure.go#L12-L14
12,155
segmentio/stats
httpstats/metrics.go
statusCode
func statusCode(code int) string { if code >= 100 { switch { case code < 200: return statusCodeWithTable(code-100, statusCode100[:]) case code < 300: return statusCodeWithTable(code-200, statusCode200[:]) case code < 400: return statusCodeWithTable(code-300, statusCode300[:]) case code < 500: return statusCodeWithTable(code-400, statusCode400[:]) case code < 600: return statusCodeWithTable(code-500, statusCode500[:]) } } return strconv.Itoa(code) }
go
func statusCode(code int) string { if code >= 100 { switch { case code < 200: return statusCodeWithTable(code-100, statusCode100[:]) case code < 300: return statusCodeWithTable(code-200, statusCode200[:]) case code < 400: return statusCodeWithTable(code-300, statusCode300[:]) case code < 500: return statusCodeWithTable(code-400, statusCode400[:]) case code < 600: return statusCodeWithTable(code-500, statusCode500[:]) } } return strconv.Itoa(code) }
[ "func", "statusCode", "(", "code", "int", ")", "string", "{", "if", "code", ">=", "100", "{", "switch", "{", "case", "code", "<", "200", ":", "return", "statusCodeWithTable", "(", "code", "-", "100", ",", "statusCode100", "[", ":", "]", ")", "\n", "case", "code", "<", "300", ":", "return", "statusCodeWithTable", "(", "code", "-", "200", ",", "statusCode200", "[", ":", "]", ")", "\n", "case", "code", "<", "400", ":", "return", "statusCodeWithTable", "(", "code", "-", "300", ",", "statusCode300", "[", ":", "]", ")", "\n", "case", "code", "<", "500", ":", "return", "statusCodeWithTable", "(", "code", "-", "400", ",", "statusCode400", "[", ":", "]", ")", "\n", "case", "code", "<", "600", ":", "return", "statusCodeWithTable", "(", "code", "-", "500", ",", "statusCode500", "[", ":", "]", ")", "\n", "}", "\n", "}", "\n", "return", "strconv", ".", "Itoa", "(", "code", ")", "\n", "}" ]
// statusCode behaves like strconv.Itoa but uses a lookup table to avoid having // to do a dynamic memory allocation to convert common http status codes to a // string representation.
[ "statusCode", "behaves", "like", "strconv", ".", "Itoa", "but", "uses", "a", "lookup", "table", "to", "avoid", "having", "to", "do", "a", "dynamic", "memory", "allocation", "to", "convert", "common", "http", "status", "codes", "to", "a", "string", "representation", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/httpstats/metrics.go#L404-L420
12,156
segmentio/stats
prometheus/metric.go
le
func le(buckets []stats.Value) string { if len(buckets) == 0 { return "" } b := make([]byte, 0, 8*len(buckets)) for i, v := range buckets { if i != 0 { b = append(b, ':') } b = appendFloat(b, valueOf(v)) } return *(*string)(unsafe.Pointer(&reflect.StringHeader{ Data: uintptr(unsafe.Pointer(&b[0])), Len: len(b), })) }
go
func le(buckets []stats.Value) string { if len(buckets) == 0 { return "" } b := make([]byte, 0, 8*len(buckets)) for i, v := range buckets { if i != 0 { b = append(b, ':') } b = appendFloat(b, valueOf(v)) } return *(*string)(unsafe.Pointer(&reflect.StringHeader{ Data: uintptr(unsafe.Pointer(&b[0])), Len: len(b), })) }
[ "func", "le", "(", "buckets", "[", "]", "stats", ".", "Value", ")", "string", "{", "if", "len", "(", "buckets", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "b", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "8", "*", "len", "(", "buckets", ")", ")", "\n\n", "for", "i", ",", "v", ":=", "range", "buckets", "{", "if", "i", "!=", "0", "{", "b", "=", "append", "(", "b", ",", "':'", ")", "\n", "}", "\n", "b", "=", "appendFloat", "(", "b", ",", "valueOf", "(", "v", ")", ")", "\n", "}", "\n\n", "return", "*", "(", "*", "string", ")", "(", "unsafe", ".", "Pointer", "(", "&", "reflect", ".", "StringHeader", "{", "Data", ":", "uintptr", "(", "unsafe", ".", "Pointer", "(", "&", "b", "[", "0", "]", ")", ")", ",", "Len", ":", "len", "(", "b", ")", ",", "}", ")", ")", "\n", "}" ]
// This function builds a string of column-separated float representations of // the given list of buckets, which is then split by calls to nextLe to generate // the values of the "le" label for each bucket of a histogram. // // The intent is to keep the number of dynamic memory allocations constant // instead of increasing linearly with the number of buckets.
[ "This", "function", "builds", "a", "string", "of", "column", "-", "separated", "float", "representations", "of", "the", "given", "list", "of", "buckets", "which", "is", "then", "split", "by", "calls", "to", "nextLe", "to", "generate", "the", "values", "of", "the", "le", "label", "for", "each", "bucket", "of", "a", "histogram", ".", "The", "intent", "is", "to", "keep", "the", "number", "of", "dynamic", "memory", "allocations", "constant", "instead", "of", "increasing", "linearly", "with", "the", "number", "of", "buckets", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/prometheus/metric.go#L391-L409
12,157
segmentio/stats
buffer.go
HandleMeasures
func (b *Buffer) HandleMeasures(time time.Time, measures ...Measure) { if len(measures) == 0 { return } size := b.bufferSize() b.prepare(size) buffer := b.acquireBuffer() length := buffer.len() buffer.append(b.Serializer, time, measures...) if buffer.len() >= size { if length == 0 { // When there were no data in the buffer prior to writing the set of // measures we unfortunately have to overflow the configured buffer // size, but the Serializer documentation mentions that this corner // case has to be handled. length = buffer.len() } buffer.flush(b.Serializer, length) } buffer.release() }
go
func (b *Buffer) HandleMeasures(time time.Time, measures ...Measure) { if len(measures) == 0 { return } size := b.bufferSize() b.prepare(size) buffer := b.acquireBuffer() length := buffer.len() buffer.append(b.Serializer, time, measures...) if buffer.len() >= size { if length == 0 { // When there were no data in the buffer prior to writing the set of // measures we unfortunately have to overflow the configured buffer // size, but the Serializer documentation mentions that this corner // case has to be handled. length = buffer.len() } buffer.flush(b.Serializer, length) } buffer.release() }
[ "func", "(", "b", "*", "Buffer", ")", "HandleMeasures", "(", "time", "time", ".", "Time", ",", "measures", "...", "Measure", ")", "{", "if", "len", "(", "measures", ")", "==", "0", "{", "return", "\n", "}", "\n\n", "size", ":=", "b", ".", "bufferSize", "(", ")", "\n", "b", ".", "prepare", "(", "size", ")", "\n\n", "buffer", ":=", "b", ".", "acquireBuffer", "(", ")", "\n", "length", ":=", "buffer", ".", "len", "(", ")", "\n", "buffer", ".", "append", "(", "b", ".", "Serializer", ",", "time", ",", "measures", "...", ")", "\n\n", "if", "buffer", ".", "len", "(", ")", ">=", "size", "{", "if", "length", "==", "0", "{", "// When there were no data in the buffer prior to writing the set of", "// measures we unfortunately have to overflow the configured buffer", "// size, but the Serializer documentation mentions that this corner", "// case has to be handled.", "length", "=", "buffer", ".", "len", "(", ")", "\n", "}", "\n", "buffer", ".", "flush", "(", "b", ".", "Serializer", ",", "length", ")", "\n", "}", "\n\n", "buffer", ".", "release", "(", ")", "\n", "}" ]
// HandleMeasures satisfies the Handler interface.
[ "HandleMeasures", "satisfies", "the", "Handler", "interface", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/buffer.go#L42-L66
12,158
segmentio/stats
buffer.go
Flush
func (b *Buffer) Flush() { b.prepare(b.bufferSize()) for i := range b.buffers { if buffer := &b.buffers[i]; buffer.acquire() { buffer.flush(b.Serializer, buffer.len()) buffer.release() } } }
go
func (b *Buffer) Flush() { b.prepare(b.bufferSize()) for i := range b.buffers { if buffer := &b.buffers[i]; buffer.acquire() { buffer.flush(b.Serializer, buffer.len()) buffer.release() } } }
[ "func", "(", "b", "*", "Buffer", ")", "Flush", "(", ")", "{", "b", ".", "prepare", "(", "b", ".", "bufferSize", "(", ")", ")", "\n\n", "for", "i", ":=", "range", "b", ".", "buffers", "{", "if", "buffer", ":=", "&", "b", ".", "buffers", "[", "i", "]", ";", "buffer", ".", "acquire", "(", ")", "{", "buffer", ".", "flush", "(", "b", ".", "Serializer", ",", "buffer", ".", "len", "(", ")", ")", "\n", "buffer", ".", "release", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Flush satisfies the Flusher interface.
[ "Flush", "satisfies", "the", "Flusher", "interface", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/buffer.go#L69-L78
12,159
segmentio/stats
grafana/search.go
ServeSearch
func (f SearchHandlerFunc) ServeSearch(ctx context.Context, res SearchResponse, req *SearchRequest) error { return f(ctx, res, req) }
go
func (f SearchHandlerFunc) ServeSearch(ctx context.Context, res SearchResponse, req *SearchRequest) error { return f(ctx, res, req) }
[ "func", "(", "f", "SearchHandlerFunc", ")", "ServeSearch", "(", "ctx", "context", ".", "Context", ",", "res", "SearchResponse", ",", "req", "*", "SearchRequest", ")", "error", "{", "return", "f", "(", "ctx", ",", "res", ",", "req", ")", "\n", "}" ]
// ServeSearch calls f, satisfies the SearchHandler interface.
[ "ServeSearch", "calls", "f", "satisfies", "the", "SearchHandler", "interface", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/grafana/search.go#L29-L31
12,160
segmentio/stats
field.go
MakeField
func MakeField(name string, value interface{}, ftype FieldType) Field { f := Field{Name: name, Value: ValueOf(value)} f.setType(ftype) return f }
go
func MakeField(name string, value interface{}, ftype FieldType) Field { f := Field{Name: name, Value: ValueOf(value)} f.setType(ftype) return f }
[ "func", "MakeField", "(", "name", "string", ",", "value", "interface", "{", "}", ",", "ftype", "FieldType", ")", "Field", "{", "f", ":=", "Field", "{", "Name", ":", "name", ",", "Value", ":", "ValueOf", "(", "value", ")", "}", "\n", "f", ".", "setType", "(", "ftype", ")", "\n", "return", "f", "\n", "}" ]
// MakeField constructs and returns a new Field from name, value, and ftype.
[ "MakeField", "constructs", "and", "returns", "a", "new", "Field", "from", "name", "value", "and", "ftype", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/field.go#L12-L16
12,161
segmentio/stats
httpstats/transport.go
NewTransport
func NewTransport(t http.RoundTripper) http.RoundTripper { return NewTransportWith(stats.DefaultEngine, t) }
go
func NewTransport(t http.RoundTripper) http.RoundTripper { return NewTransportWith(stats.DefaultEngine, t) }
[ "func", "NewTransport", "(", "t", "http", ".", "RoundTripper", ")", "http", ".", "RoundTripper", "{", "return", "NewTransportWith", "(", "stats", ".", "DefaultEngine", ",", "t", ")", "\n", "}" ]
// NewTransport wraps t to produce metrics on the default engine for every request // sent and every response received.
[ "NewTransport", "wraps", "t", "to", "produce", "metrics", "on", "the", "default", "engine", "for", "every", "request", "sent", "and", "every", "response", "received", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/httpstats/transport.go#L28-L30
12,162
segmentio/stats
httpstats/transport.go
NewTransportWith
func NewTransportWith(eng *stats.Engine, t http.RoundTripper) http.RoundTripper { return &transport{ transport: t, eng: eng, } }
go
func NewTransportWith(eng *stats.Engine, t http.RoundTripper) http.RoundTripper { return &transport{ transport: t, eng: eng, } }
[ "func", "NewTransportWith", "(", "eng", "*", "stats", ".", "Engine", ",", "t", "http", ".", "RoundTripper", ")", "http", ".", "RoundTripper", "{", "return", "&", "transport", "{", "transport", ":", "t", ",", "eng", ":", "eng", ",", "}", "\n", "}" ]
// NewTransportWith wraps t to produce metrics on eng for every request sent and // every response received.
[ "NewTransportWith", "wraps", "t", "to", "produce", "metrics", "on", "eng", "for", "every", "request", "sent", "and", "every", "response", "received", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/httpstats/transport.go#L34-L39
12,163
segmentio/stats
httpstats/transport.go
RequestWithTags
func RequestWithTags(req *http.Request, tags ...stats.Tag) *http.Request { ctx := req.Context() ctx = context.WithValue(ctx, contextKeyReqTags, tags) return req.WithContext(ctx) }
go
func RequestWithTags(req *http.Request, tags ...stats.Tag) *http.Request { ctx := req.Context() ctx = context.WithValue(ctx, contextKeyReqTags, tags) return req.WithContext(ctx) }
[ "func", "RequestWithTags", "(", "req", "*", "http", ".", "Request", ",", "tags", "...", "stats", ".", "Tag", ")", "*", "http", ".", "Request", "{", "ctx", ":=", "req", ".", "Context", "(", ")", "\n", "ctx", "=", "context", ".", "WithValue", "(", "ctx", ",", "contextKeyReqTags", ",", "tags", ")", "\n", "return", "req", ".", "WithContext", "(", "ctx", ")", "\n", "}" ]
// RequestWithTags returns a shallow copy of req with its context changed with this provided tags // so the they can be used later during the RoundTrip in the metrics recording. // The provided ctx must be non-nil.
[ "RequestWithTags", "returns", "a", "shallow", "copy", "of", "req", "with", "its", "context", "changed", "with", "this", "provided", "tags", "so", "the", "they", "can", "be", "used", "later", "during", "the", "RoundTrip", "in", "the", "metrics", "recording", ".", "The", "provided", "ctx", "must", "be", "non", "-", "nil", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/httpstats/transport.go#L49-L53
12,164
segmentio/stats
httpstats/transport.go
RoundTrip
func (t *transport) RoundTrip(req *http.Request) (res *http.Response, err error) { start := time.Now() rtrip := t.transport eng := t.eng if rtrip == nil { rtrip = http.DefaultTransport } if tags, ok := req.Context().Value(contextKeyReqTags).([]stats.Tag); ok { eng = eng.WithTags(tags...) } if req.Body == nil { req.Body = &nullBody{} } m := &metrics{} req.Body = &requestBody{ eng: eng, req: req, metrics: m, body: req.Body, op: "write", } res, err = rtrip.RoundTrip(req) // safe guard, the transport should have done it already req.Body.Close() // nolint if err != nil { m.observeError(time.Now().Sub(start)) eng.ReportAt(start, m) } else { res.Body = &responseBody{ eng: eng, res: res, metrics: m, body: res.Body, op: "read", start: start, } } return }
go
func (t *transport) RoundTrip(req *http.Request) (res *http.Response, err error) { start := time.Now() rtrip := t.transport eng := t.eng if rtrip == nil { rtrip = http.DefaultTransport } if tags, ok := req.Context().Value(contextKeyReqTags).([]stats.Tag); ok { eng = eng.WithTags(tags...) } if req.Body == nil { req.Body = &nullBody{} } m := &metrics{} req.Body = &requestBody{ eng: eng, req: req, metrics: m, body: req.Body, op: "write", } res, err = rtrip.RoundTrip(req) // safe guard, the transport should have done it already req.Body.Close() // nolint if err != nil { m.observeError(time.Now().Sub(start)) eng.ReportAt(start, m) } else { res.Body = &responseBody{ eng: eng, res: res, metrics: m, body: res.Body, op: "read", start: start, } } return }
[ "func", "(", "t", "*", "transport", ")", "RoundTrip", "(", "req", "*", "http", ".", "Request", ")", "(", "res", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "start", ":=", "time", ".", "Now", "(", ")", "\n", "rtrip", ":=", "t", ".", "transport", "\n", "eng", ":=", "t", ".", "eng", "\n\n", "if", "rtrip", "==", "nil", "{", "rtrip", "=", "http", ".", "DefaultTransport", "\n", "}", "\n\n", "if", "tags", ",", "ok", ":=", "req", ".", "Context", "(", ")", ".", "Value", "(", "contextKeyReqTags", ")", ".", "(", "[", "]", "stats", ".", "Tag", ")", ";", "ok", "{", "eng", "=", "eng", ".", "WithTags", "(", "tags", "...", ")", "\n", "}", "\n\n", "if", "req", ".", "Body", "==", "nil", "{", "req", ".", "Body", "=", "&", "nullBody", "{", "}", "\n", "}", "\n\n", "m", ":=", "&", "metrics", "{", "}", "\n\n", "req", ".", "Body", "=", "&", "requestBody", "{", "eng", ":", "eng", ",", "req", ":", "req", ",", "metrics", ":", "m", ",", "body", ":", "req", ".", "Body", ",", "op", ":", "\"", "\"", ",", "}", "\n\n", "res", ",", "err", "=", "rtrip", ".", "RoundTrip", "(", "req", ")", "\n", "// safe guard, the transport should have done it already", "req", ".", "Body", ".", "Close", "(", ")", "// nolint", "\n\n", "if", "err", "!=", "nil", "{", "m", ".", "observeError", "(", "time", ".", "Now", "(", ")", ".", "Sub", "(", "start", ")", ")", "\n", "eng", ".", "ReportAt", "(", "start", ",", "m", ")", "\n", "}", "else", "{", "res", ".", "Body", "=", "&", "responseBody", "{", "eng", ":", "eng", ",", "res", ":", "res", ",", "metrics", ":", "m", ",", "body", ":", "res", ".", "Body", ",", "op", ":", "\"", "\"", ",", "start", ":", "start", ",", "}", "\n", "}", "\n\n", "return", "\n", "}" ]
// RoundTrip implements http.RoundTripper
[ "RoundTrip", "implements", "http", ".", "RoundTripper" ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/httpstats/transport.go#L56-L102
12,165
segmentio/stats
grafana/query.go
ServeQuery
func (f QueryHandlerFunc) ServeQuery(ctx context.Context, res QueryResponse, req *QueryRequest) error { return f(ctx, res, req) }
go
func (f QueryHandlerFunc) ServeQuery(ctx context.Context, res QueryResponse, req *QueryRequest) error { return f(ctx, res, req) }
[ "func", "(", "f", "QueryHandlerFunc", ")", "ServeQuery", "(", "ctx", "context", ".", "Context", ",", "res", "QueryResponse", ",", "req", "*", "QueryRequest", ")", "error", "{", "return", "f", "(", "ctx", ",", "res", ",", "req", ")", "\n", "}" ]
// ServeQuery calls f, satisfies the QueryHandler interface.
[ "ServeQuery", "calls", "f", "satisfies", "the", "QueryHandler", "interface", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/grafana/query.go#L30-L32
12,166
segmentio/stats
grafana/query.go
Col
func Col(text string, colType ColumnType) Column { return Column{Text: text, Type: colType} }
go
func Col(text string, colType ColumnType) Column { return Column{Text: text, Type: colType} }
[ "func", "Col", "(", "text", "string", ",", "colType", "ColumnType", ")", "Column", "{", "return", "Column", "{", "Text", ":", "text", ",", "Type", ":", "colType", "}", "\n", "}" ]
// Col constructs a new Column value from a text and column type.
[ "Col", "constructs", "a", "new", "Column", "value", "from", "a", "text", "and", "column", "type", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/grafana/query.go#L91-L93
12,167
segmentio/stats
grafana/query.go
AscCol
func AscCol(text string, colType ColumnType) Column { return Column{Text: text, Type: colType, Sort: true} }
go
func AscCol(text string, colType ColumnType) Column { return Column{Text: text, Type: colType, Sort: true} }
[ "func", "AscCol", "(", "text", "string", ",", "colType", "ColumnType", ")", "Column", "{", "return", "Column", "{", "Text", ":", "text", ",", "Type", ":", "colType", ",", "Sort", ":", "true", "}", "\n", "}" ]
// AscCol constructs a ne Column value from a text a column type, which is // configured as a sorted column in ascending order.
[ "AscCol", "constructs", "a", "ne", "Column", "value", "from", "a", "text", "a", "column", "type", "which", "is", "configured", "as", "a", "sorted", "column", "in", "ascending", "order", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/grafana/query.go#L97-L99
12,168
segmentio/stats
grafana/query.go
DescCol
func DescCol(text string, colType ColumnType) Column { return Column{Text: text, Type: colType, Sort: true, Desc: true} }
go
func DescCol(text string, colType ColumnType) Column { return Column{Text: text, Type: colType, Sort: true, Desc: true} }
[ "func", "DescCol", "(", "text", "string", ",", "colType", "ColumnType", ")", "Column", "{", "return", "Column", "{", "Text", ":", "text", ",", "Type", ":", "colType", ",", "Sort", ":", "true", ",", "Desc", ":", "true", "}", "\n", "}" ]
// DescCol constructs a ne Column value from a text a column type, which is // configured as a sorted column in descending order.
[ "DescCol", "constructs", "a", "ne", "Column", "value", "from", "a", "text", "a", "column", "type", "which", "is", "configured", "as", "a", "sorted", "column", "in", "descending", "order", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/grafana/query.go#L103-L105
12,169
segmentio/stats
buckets.go
Set
func (b HistogramBuckets) Set(key string, buckets ...interface{}) { v := make([]Value, len(buckets)) for i, b := range buckets { v[i] = ValueOf(b) } b[makeKey(key)] = v }
go
func (b HistogramBuckets) Set(key string, buckets ...interface{}) { v := make([]Value, len(buckets)) for i, b := range buckets { v[i] = ValueOf(b) } b[makeKey(key)] = v }
[ "func", "(", "b", "HistogramBuckets", ")", "Set", "(", "key", "string", ",", "buckets", "...", "interface", "{", "}", ")", "{", "v", ":=", "make", "(", "[", "]", "Value", ",", "len", "(", "buckets", ")", ")", "\n\n", "for", "i", ",", "b", ":=", "range", "buckets", "{", "v", "[", "i", "]", "=", "ValueOf", "(", "b", ")", "\n", "}", "\n\n", "b", "[", "makeKey", "(", "key", ")", "]", "=", "v", "\n", "}" ]
// Set sets a set of buckets to the given list of sorted values.
[ "Set", "sets", "a", "set", "of", "buckets", "to", "the", "given", "list", "of", "sorted", "values", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/buckets.go#L15-L23
12,170
segmentio/stats
procstats/proc.go
NewProcMetricsWith
func NewProcMetricsWith(eng *stats.Engine, pid int) *ProcMetrics { p := &ProcMetrics{engine: eng, pid: pid} p.cpu.user.typ = "user" p.cpu.system.typ = "system" p.memory.resident.typ = "resident" p.memory.shared.typ = "shared" p.memory.text.typ = "text" p.memory.data.typ = "data" p.memory.pagefault.major.typ = "major" p.memory.pagefault.minor.typ = "minor" p.threads.switches.voluntary.typ = "voluntary" p.threads.switches.involuntary.typ = "involuntary" return p }
go
func NewProcMetricsWith(eng *stats.Engine, pid int) *ProcMetrics { p := &ProcMetrics{engine: eng, pid: pid} p.cpu.user.typ = "user" p.cpu.system.typ = "system" p.memory.resident.typ = "resident" p.memory.shared.typ = "shared" p.memory.text.typ = "text" p.memory.data.typ = "data" p.memory.pagefault.major.typ = "major" p.memory.pagefault.minor.typ = "minor" p.threads.switches.voluntary.typ = "voluntary" p.threads.switches.involuntary.typ = "involuntary" return p }
[ "func", "NewProcMetricsWith", "(", "eng", "*", "stats", ".", "Engine", ",", "pid", "int", ")", "*", "ProcMetrics", "{", "p", ":=", "&", "ProcMetrics", "{", "engine", ":", "eng", ",", "pid", ":", "pid", "}", "\n\n", "p", ".", "cpu", ".", "user", ".", "typ", "=", "\"", "\"", "\n", "p", ".", "cpu", ".", "system", ".", "typ", "=", "\"", "\"", "\n\n", "p", ".", "memory", ".", "resident", ".", "typ", "=", "\"", "\"", "\n", "p", ".", "memory", ".", "shared", ".", "typ", "=", "\"", "\"", "\n", "p", ".", "memory", ".", "text", ".", "typ", "=", "\"", "\"", "\n", "p", ".", "memory", ".", "data", ".", "typ", "=", "\"", "\"", "\n\n", "p", ".", "memory", ".", "pagefault", ".", "major", ".", "typ", "=", "\"", "\"", "\n", "p", ".", "memory", ".", "pagefault", ".", "minor", ".", "typ", "=", "\"", "\"", "\n\n", "p", ".", "threads", ".", "switches", ".", "voluntary", ".", "typ", "=", "\"", "\"", "\n", "p", ".", "threads", ".", "switches", ".", "involuntary", ".", "typ", "=", "\"", "\"", "\n\n", "return", "p", "\n", "}" ]
// NewProcMetricsWith collects metrics on the process identified by pid and // reports them to eng.
[ "NewProcMetricsWith", "collects", "metrics", "on", "the", "process", "identified", "by", "pid", "and", "reports", "them", "to", "eng", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/procstats/proc.go#L111-L129
12,171
segmentio/stats
grafana/handler.go
NewHandler
func NewHandler(prefix string, handler Handler) http.Handler { mux := http.NewServeMux() Handle(mux, prefix, handler) return mux }
go
func NewHandler(prefix string, handler Handler) http.Handler { mux := http.NewServeMux() Handle(mux, prefix, handler) return mux }
[ "func", "NewHandler", "(", "prefix", "string", ",", "handler", "Handler", ")", "http", ".", "Handler", "{", "mux", ":=", "http", ".", "NewServeMux", "(", ")", "\n", "Handle", "(", "mux", ",", "prefix", ",", "handler", ")", "\n", "return", "mux", "\n", "}" ]
// NewHandler returns a new http.Handler that implements the // simple-json-datasource API.
[ "NewHandler", "returns", "a", "new", "http", ".", "Handler", "that", "implements", "the", "simple", "-", "json", "-", "datasource", "API", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/grafana/handler.go#L28-L32
12,172
segmentio/stats
veneur/client.go
NewClient
func NewClient(addr string) *Client { return NewClientWith(ClientConfig{ClientConfig: datadog.ClientConfig{Address: addr}}) }
go
func NewClient(addr string) *Client { return NewClientWith(ClientConfig{ClientConfig: datadog.ClientConfig{Address: addr}}) }
[ "func", "NewClient", "(", "addr", "string", ")", "*", "Client", "{", "return", "NewClientWith", "(", "ClientConfig", "{", "ClientConfig", ":", "datadog", ".", "ClientConfig", "{", "Address", ":", "addr", "}", "}", ")", "\n", "}" ]
// NewClient creates and returns a new veneur client publishing metrics to the // server running at addr.
[ "NewClient", "creates", "and", "returns", "a", "new", "veneur", "client", "publishing", "metrics", "to", "the", "server", "running", "at", "addr", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/veneur/client.go#L54-L56
12,173
segmentio/stats
veneur/client.go
NewClientGlobal
func NewClientGlobal(addr string) *Client { return NewClientWith(ClientConfig{ClientConfig: datadog.ClientConfig{Address: addr}, GlobalOnly: true}) }
go
func NewClientGlobal(addr string) *Client { return NewClientWith(ClientConfig{ClientConfig: datadog.ClientConfig{Address: addr}, GlobalOnly: true}) }
[ "func", "NewClientGlobal", "(", "addr", "string", ")", "*", "Client", "{", "return", "NewClientWith", "(", "ClientConfig", "{", "ClientConfig", ":", "datadog", ".", "ClientConfig", "{", "Address", ":", "addr", "}", ",", "GlobalOnly", ":", "true", "}", ")", "\n", "}" ]
// NewClientGlobal creates a client that sends all metrics to the Global Veneur Aggregator
[ "NewClientGlobal", "creates", "a", "client", "that", "sends", "all", "metrics", "to", "the", "Global", "Veneur", "Aggregator" ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/veneur/client.go#L59-L61
12,174
segmentio/stats
veneur/client.go
NewClientWith
func NewClientWith(config ClientConfig) *Client { // Construct Veneur-specific Tags we will append to measures tags := []stats.Tag{} if config.GlobalOnly { tags = append(tags, stats.Tag{Name: GlobalOnly}) } else if config.LocalOnly { tags = append(tags, stats.Tag{Name: LocalOnly}) } for _, t := range config.SinksOnly { tags = append(tags, stats.Tag{Name: SinkOnly, Value: t}) } return &Client{ Client: datadog.NewClientWith(datadog.ClientConfig{ Address: config.Address, BufferSize: config.BufferSize, Filters: config.Filters, }), tags: tags, } }
go
func NewClientWith(config ClientConfig) *Client { // Construct Veneur-specific Tags we will append to measures tags := []stats.Tag{} if config.GlobalOnly { tags = append(tags, stats.Tag{Name: GlobalOnly}) } else if config.LocalOnly { tags = append(tags, stats.Tag{Name: LocalOnly}) } for _, t := range config.SinksOnly { tags = append(tags, stats.Tag{Name: SinkOnly, Value: t}) } return &Client{ Client: datadog.NewClientWith(datadog.ClientConfig{ Address: config.Address, BufferSize: config.BufferSize, Filters: config.Filters, }), tags: tags, } }
[ "func", "NewClientWith", "(", "config", "ClientConfig", ")", "*", "Client", "{", "// Construct Veneur-specific Tags we will append to measures", "tags", ":=", "[", "]", "stats", ".", "Tag", "{", "}", "\n", "if", "config", ".", "GlobalOnly", "{", "tags", "=", "append", "(", "tags", ",", "stats", ".", "Tag", "{", "Name", ":", "GlobalOnly", "}", ")", "\n", "}", "else", "if", "config", ".", "LocalOnly", "{", "tags", "=", "append", "(", "tags", ",", "stats", ".", "Tag", "{", "Name", ":", "LocalOnly", "}", ")", "\n", "}", "\n", "for", "_", ",", "t", ":=", "range", "config", ".", "SinksOnly", "{", "tags", "=", "append", "(", "tags", ",", "stats", ".", "Tag", "{", "Name", ":", "SinkOnly", ",", "Value", ":", "t", "}", ")", "\n", "}", "\n\n", "return", "&", "Client", "{", "Client", ":", "datadog", ".", "NewClientWith", "(", "datadog", ".", "ClientConfig", "{", "Address", ":", "config", ".", "Address", ",", "BufferSize", ":", "config", ".", "BufferSize", ",", "Filters", ":", "config", ".", "Filters", ",", "}", ")", ",", "tags", ":", "tags", ",", "}", "\n", "}" ]
// NewClientWith creates and returns a new veneur client configured with the // given config.
[ "NewClientWith", "creates", "and", "returns", "a", "new", "veneur", "client", "configured", "with", "the", "given", "config", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/veneur/client.go#L65-L86
12,175
segmentio/stats
httpstats/handler.go
NewHandler
func NewHandler(h http.Handler) http.Handler { return NewHandlerWith(stats.DefaultEngine, h) }
go
func NewHandler(h http.Handler) http.Handler { return NewHandlerWith(stats.DefaultEngine, h) }
[ "func", "NewHandler", "(", "h", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "NewHandlerWith", "(", "stats", ".", "DefaultEngine", ",", "h", ")", "\n", "}" ]
// NewHandler wraps h to produce metrics on the default engine for every request // received and every response sent.
[ "NewHandler", "wraps", "h", "to", "produce", "metrics", "on", "the", "default", "engine", "for", "every", "request", "received", "and", "every", "response", "sent", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/httpstats/handler.go#L14-L16
12,176
segmentio/stats
httpstats/handler.go
NewHandlerWith
func NewHandlerWith(eng *stats.Engine, h http.Handler) http.Handler { return &handler{ handler: h, eng: eng, } }
go
func NewHandlerWith(eng *stats.Engine, h http.Handler) http.Handler { return &handler{ handler: h, eng: eng, } }
[ "func", "NewHandlerWith", "(", "eng", "*", "stats", ".", "Engine", ",", "h", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "&", "handler", "{", "handler", ":", "h", ",", "eng", ":", "eng", ",", "}", "\n", "}" ]
// NewHandlerWith wraps h to produce metrics on eng for every request received // and every response sent.
[ "NewHandlerWith", "wraps", "h", "to", "produce", "metrics", "on", "eng", "for", "every", "request", "received", "and", "every", "response", "sent", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/httpstats/handler.go#L20-L25
12,177
segmentio/stats
datadog/server.go
ListenAndServe
func ListenAndServe(addr string, handler Handler) (err error) { var conn net.PacketConn if conn, err = net.ListenPacket("udp", addr); err != nil { return } err = Serve(conn, handler) return }
go
func ListenAndServe(addr string, handler Handler) (err error) { var conn net.PacketConn if conn, err = net.ListenPacket("udp", addr); err != nil { return } err = Serve(conn, handler) return }
[ "func", "ListenAndServe", "(", "addr", "string", ",", "handler", "Handler", ")", "(", "err", "error", ")", "{", "var", "conn", "net", ".", "PacketConn", "\n\n", "if", "conn", ",", "err", "=", "net", ".", "ListenPacket", "(", "\"", "\"", ",", "addr", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "err", "=", "Serve", "(", "conn", ",", "handler", ")", "\n", "return", "\n", "}" ]
// ListenAndServe starts a new dogstatsd server, listening for UDP datagrams on // addr and forwarding the metrics to handler.
[ "ListenAndServe", "starts", "a", "new", "dogstatsd", "server", "listening", "for", "UDP", "datagrams", "on", "addr", "and", "forwarding", "the", "metrics", "to", "handler", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/datadog/server.go#L39-L48
12,178
segmentio/stats
datadog/server.go
Serve
func Serve(conn net.PacketConn, handler Handler) (err error) { defer conn.Close() concurrency := runtime.GOMAXPROCS(-1) if concurrency <= 0 { concurrency = 1 } done := make(chan error, concurrency) conn.SetDeadline(time.Time{}) for i := 0; i != concurrency; i++ { go serve(conn, handler, done) } for i := 0; i != concurrency; i++ { switch e := <-done; e { case nil, io.EOF, io.ErrClosedPipe, io.ErrUnexpectedEOF: default: err = e } conn.Close() } return }
go
func Serve(conn net.PacketConn, handler Handler) (err error) { defer conn.Close() concurrency := runtime.GOMAXPROCS(-1) if concurrency <= 0 { concurrency = 1 } done := make(chan error, concurrency) conn.SetDeadline(time.Time{}) for i := 0; i != concurrency; i++ { go serve(conn, handler, done) } for i := 0; i != concurrency; i++ { switch e := <-done; e { case nil, io.EOF, io.ErrClosedPipe, io.ErrUnexpectedEOF: default: err = e } conn.Close() } return }
[ "func", "Serve", "(", "conn", "net", ".", "PacketConn", ",", "handler", "Handler", ")", "(", "err", "error", ")", "{", "defer", "conn", ".", "Close", "(", ")", "\n\n", "concurrency", ":=", "runtime", ".", "GOMAXPROCS", "(", "-", "1", ")", "\n", "if", "concurrency", "<=", "0", "{", "concurrency", "=", "1", "\n", "}", "\n\n", "done", ":=", "make", "(", "chan", "error", ",", "concurrency", ")", "\n", "conn", ".", "SetDeadline", "(", "time", ".", "Time", "{", "}", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "!=", "concurrency", ";", "i", "++", "{", "go", "serve", "(", "conn", ",", "handler", ",", "done", ")", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "!=", "concurrency", ";", "i", "++", "{", "switch", "e", ":=", "<-", "done", ";", "e", "{", "case", "nil", ",", "io", ".", "EOF", ",", "io", ".", "ErrClosedPipe", ",", "io", ".", "ErrUnexpectedEOF", ":", "default", ":", "err", "=", "e", "\n", "}", "\n", "conn", ".", "Close", "(", ")", "\n", "}", "\n\n", "return", "\n", "}" ]
// Serve runs a dogstatsd server, listening for datagrams on conn and forwarding // the metrics to handler.
[ "Serve", "runs", "a", "dogstatsd", "server", "listening", "for", "datagrams", "on", "conn", "and", "forwarding", "the", "metrics", "to", "handler", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/datadog/server.go#L52-L77
12,179
segmentio/stats
tag.go
M
func M(m map[string]string) []Tag { tags := make([]Tag, 0, len(m)) for k, v := range m { tags = append(tags, T(k, v)) } return tags }
go
func M(m map[string]string) []Tag { tags := make([]Tag, 0, len(m)) for k, v := range m { tags = append(tags, T(k, v)) } return tags }
[ "func", "M", "(", "m", "map", "[", "string", "]", "string", ")", "[", "]", "Tag", "{", "tags", ":=", "make", "(", "[", "]", "Tag", ",", "0", ",", "len", "(", "m", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "m", "{", "tags", "=", "append", "(", "tags", ",", "T", "(", "k", ",", "v", ")", ")", "\n", "}", "\n", "return", "tags", "\n", "}" ]
// M allows for creating a tag list from a map.
[ "M", "allows", "for", "creating", "a", "tag", "list", "from", "a", "map", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/tag.go#L26-L32
12,180
segmentio/stats
tag.go
TagsAreSorted
func TagsAreSorted(tags []Tag) bool { if len(tags) > 1 { min := tags[0].Name for _, tag := range tags[1:] { if tag.Name < min { return false } min = tag.Name } } return true }
go
func TagsAreSorted(tags []Tag) bool { if len(tags) > 1 { min := tags[0].Name for _, tag := range tags[1:] { if tag.Name < min { return false } min = tag.Name } } return true }
[ "func", "TagsAreSorted", "(", "tags", "[", "]", "Tag", ")", "bool", "{", "if", "len", "(", "tags", ")", ">", "1", "{", "min", ":=", "tags", "[", "0", "]", ".", "Name", "\n", "for", "_", ",", "tag", ":=", "range", "tags", "[", "1", ":", "]", "{", "if", "tag", ".", "Name", "<", "min", "{", "return", "false", "\n", "}", "\n", "min", "=", "tag", ".", "Name", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// TagsAreSorted returns true if the given list of tags is sorted by tag name, // false otherwise.
[ "TagsAreSorted", "returns", "true", "if", "the", "given", "list", "of", "tags", "is", "sorted", "by", "tag", "name", "false", "otherwise", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/tag.go#L36-L47
12,181
segmentio/stats
tag.go
SortTags
func SortTags(tags []Tag) []Tag { // Insertion sort since these arrays are very small and allocation is the // primary enemy of performance here. if len(tags) >= 20 { sort.Sort(tagsByName(tags)) } else { for i := 0; i < len(tags); i++ { for j := i; j > 0 && tags[j-1].Name > tags[j].Name; j-- { tags[j], tags[j-1] = tags[j-1], tags[j] } } } return tags }
go
func SortTags(tags []Tag) []Tag { // Insertion sort since these arrays are very small and allocation is the // primary enemy of performance here. if len(tags) >= 20 { sort.Sort(tagsByName(tags)) } else { for i := 0; i < len(tags); i++ { for j := i; j > 0 && tags[j-1].Name > tags[j].Name; j-- { tags[j], tags[j-1] = tags[j-1], tags[j] } } } return tags }
[ "func", "SortTags", "(", "tags", "[", "]", "Tag", ")", "[", "]", "Tag", "{", "// Insertion sort since these arrays are very small and allocation is the", "// primary enemy of performance here.", "if", "len", "(", "tags", ")", ">=", "20", "{", "sort", ".", "Sort", "(", "tagsByName", "(", "tags", ")", ")", "\n", "}", "else", "{", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "tags", ")", ";", "i", "++", "{", "for", "j", ":=", "i", ";", "j", ">", "0", "&&", "tags", "[", "j", "-", "1", "]", ".", "Name", ">", "tags", "[", "j", "]", ".", "Name", ";", "j", "--", "{", "tags", "[", "j", "]", ",", "tags", "[", "j", "-", "1", "]", "=", "tags", "[", "j", "-", "1", "]", ",", "tags", "[", "j", "]", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "tags", "\n", "}" ]
// SortTags sorts the slice of tags.
[ "SortTags", "sorts", "the", "slice", "of", "tags", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/tag.go#L50-L63
12,182
segmentio/stats
datadog/client.go
NewClientWith
func NewClientWith(config ClientConfig) *Client { if len(config.Address) == 0 { config.Address = DefaultAddress } if config.BufferSize == 0 { config.BufferSize = DefaultBufferSize } if config.Filters == nil { config.Filters = DefaultFilters } // transform filters from array to map filterMap := make(map[string]struct{}) for _, f := range config.Filters { filterMap[f] = struct{}{} } c := &Client{ serializer: serializer{ filters: filterMap, }, } conn, bufferSize, err := dial(config.Address, config.BufferSize) if err != nil { log.Printf("stats/datadog: %s", err) } c.conn, c.err, c.bufferSize = conn, err, bufferSize c.buffer.BufferSize = bufferSize c.buffer.Serializer = &c.serializer log.Printf("stats/datadog: sending metrics with a buffer of size %d B", bufferSize) return c }
go
func NewClientWith(config ClientConfig) *Client { if len(config.Address) == 0 { config.Address = DefaultAddress } if config.BufferSize == 0 { config.BufferSize = DefaultBufferSize } if config.Filters == nil { config.Filters = DefaultFilters } // transform filters from array to map filterMap := make(map[string]struct{}) for _, f := range config.Filters { filterMap[f] = struct{}{} } c := &Client{ serializer: serializer{ filters: filterMap, }, } conn, bufferSize, err := dial(config.Address, config.BufferSize) if err != nil { log.Printf("stats/datadog: %s", err) } c.conn, c.err, c.bufferSize = conn, err, bufferSize c.buffer.BufferSize = bufferSize c.buffer.Serializer = &c.serializer log.Printf("stats/datadog: sending metrics with a buffer of size %d B", bufferSize) return c }
[ "func", "NewClientWith", "(", "config", "ClientConfig", ")", "*", "Client", "{", "if", "len", "(", "config", ".", "Address", ")", "==", "0", "{", "config", ".", "Address", "=", "DefaultAddress", "\n", "}", "\n\n", "if", "config", ".", "BufferSize", "==", "0", "{", "config", ".", "BufferSize", "=", "DefaultBufferSize", "\n", "}", "\n\n", "if", "config", ".", "Filters", "==", "nil", "{", "config", ".", "Filters", "=", "DefaultFilters", "\n", "}", "\n\n", "// transform filters from array to map", "filterMap", ":=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "for", "_", ",", "f", ":=", "range", "config", ".", "Filters", "{", "filterMap", "[", "f", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n\n", "c", ":=", "&", "Client", "{", "serializer", ":", "serializer", "{", "filters", ":", "filterMap", ",", "}", ",", "}", "\n\n", "conn", ",", "bufferSize", ",", "err", ":=", "dial", "(", "config", ".", "Address", ",", "config", ".", "BufferSize", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "c", ".", "conn", ",", "c", ".", "err", ",", "c", ".", "bufferSize", "=", "conn", ",", "err", ",", "bufferSize", "\n", "c", ".", "buffer", ".", "BufferSize", "=", "bufferSize", "\n", "c", ".", "buffer", ".", "Serializer", "=", "&", "c", ".", "serializer", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "bufferSize", ")", "\n", "return", "c", "\n", "}" ]
// NewClientWith creates and returns a new datadog client configured with the // given config.
[ "NewClientWith", "creates", "and", "returns", "a", "new", "datadog", "client", "configured", "with", "the", "given", "config", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/datadog/client.go#L67-L102
12,183
segmentio/stats
grafana/annotations.go
ServeAnnotations
func (f AnnotationsHandlerFunc) ServeAnnotations(ctx context.Context, res AnnotationsResponse, req *AnnotationsRequest) error { return f(ctx, res, req) }
go
func (f AnnotationsHandlerFunc) ServeAnnotations(ctx context.Context, res AnnotationsResponse, req *AnnotationsRequest) error { return f(ctx, res, req) }
[ "func", "(", "f", "AnnotationsHandlerFunc", ")", "ServeAnnotations", "(", "ctx", "context", ".", "Context", ",", "res", "AnnotationsResponse", ",", "req", "*", "AnnotationsRequest", ")", "error", "{", "return", "f", "(", "ctx", ",", "res", ",", "req", ")", "\n", "}" ]
// ServeAnnotations calls f, satisfies the AnnotationsHandler interface.
[ "ServeAnnotations", "calls", "f", "satisfies", "the", "AnnotationsHandler", "interface", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/grafana/annotations.go#L25-L27
12,184
segmentio/stats
handler.go
HandleMeasures
func (f HandlerFunc) HandleMeasures(time time.Time, measures ...Measure) { f(time, measures...) }
go
func (f HandlerFunc) HandleMeasures(time time.Time, measures ...Measure) { f(time, measures...) }
[ "func", "(", "f", "HandlerFunc", ")", "HandleMeasures", "(", "time", "time", ".", "Time", ",", "measures", "...", "Measure", ")", "{", "f", "(", "time", ",", "measures", "...", ")", "\n", "}" ]
// HandleMeasures calls f, satisfies the Handler interface.
[ "HandleMeasures", "calls", "f", "satisfies", "the", "Handler", "interface", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/handler.go#L35-L37
12,185
segmentio/stats
handler.go
MultiHandler
func MultiHandler(handlers ...Handler) Handler { multi := make([]Handler, 0, len(handlers)) for _, h := range handlers { if h != nil { if m, ok := h.(*multiHandler); ok { multi = append(multi, m.handlers...) // flatten multi handlers } else { multi = append(multi, h) } } } if len(multi) == 1 { return multi[0] } return &multiHandler{handlers: multi} }
go
func MultiHandler(handlers ...Handler) Handler { multi := make([]Handler, 0, len(handlers)) for _, h := range handlers { if h != nil { if m, ok := h.(*multiHandler); ok { multi = append(multi, m.handlers...) // flatten multi handlers } else { multi = append(multi, h) } } } if len(multi) == 1 { return multi[0] } return &multiHandler{handlers: multi} }
[ "func", "MultiHandler", "(", "handlers", "...", "Handler", ")", "Handler", "{", "multi", ":=", "make", "(", "[", "]", "Handler", ",", "0", ",", "len", "(", "handlers", ")", ")", "\n\n", "for", "_", ",", "h", ":=", "range", "handlers", "{", "if", "h", "!=", "nil", "{", "if", "m", ",", "ok", ":=", "h", ".", "(", "*", "multiHandler", ")", ";", "ok", "{", "multi", "=", "append", "(", "multi", ",", "m", ".", "handlers", "...", ")", "// flatten multi handlers", "\n", "}", "else", "{", "multi", "=", "append", "(", "multi", ",", "h", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "multi", ")", "==", "1", "{", "return", "multi", "[", "0", "]", "\n", "}", "\n\n", "return", "&", "multiHandler", "{", "handlers", ":", "multi", "}", "\n", "}" ]
// MultiHandler constructs a handler which dispatches measures to all given // handlers.
[ "MultiHandler", "constructs", "a", "handler", "which", "dispatches", "measures", "to", "all", "given", "handlers", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/handler.go#L41-L59
12,186
segmentio/stats
netstats/handler.go
NewHandlerWith
func NewHandlerWith(eng *stats.Engine, hdl Handler) Handler { return &handler{ handler: hdl, eng: eng, } }
go
func NewHandlerWith(eng *stats.Engine, hdl Handler) Handler { return &handler{ handler: hdl, eng: eng, } }
[ "func", "NewHandlerWith", "(", "eng", "*", "stats", ".", "Engine", ",", "hdl", "Handler", ")", "Handler", "{", "return", "&", "handler", "{", "handler", ":", "hdl", ",", "eng", ":", "eng", ",", "}", "\n", "}" ]
// NewHandlerWith returns a Handler object that warps hdl and produces // metrics on eng.
[ "NewHandlerWith", "returns", "a", "Handler", "object", "that", "warps", "hdl", "and", "produces", "metrics", "on", "eng", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/netstats/handler.go#L24-L29
12,187
segmentio/stats
prometheus/handler.go
ServeHTTP
func (h *Handler) ServeHTTP(res http.ResponseWriter, req *http.Request) { switch req.Method { case "GET", "HEAD": default: res.WriteHeader(http.StatusMethodNotAllowed) return } w := io.Writer(res) res.Header().Set("Content-Type", "text/plain; version=0.0.4") if acceptEncoding(req.Header.Get("Accept-Encoding"), "gzip") { res.Header().Set("Content-Encoding", "gzip") zw := gzip.NewWriter(w) defer zw.Close() w = zw } h.WriteStats(w) }
go
func (h *Handler) ServeHTTP(res http.ResponseWriter, req *http.Request) { switch req.Method { case "GET", "HEAD": default: res.WriteHeader(http.StatusMethodNotAllowed) return } w := io.Writer(res) res.Header().Set("Content-Type", "text/plain; version=0.0.4") if acceptEncoding(req.Header.Get("Accept-Encoding"), "gzip") { res.Header().Set("Content-Encoding", "gzip") zw := gzip.NewWriter(w) defer zw.Close() w = zw } h.WriteStats(w) }
[ "func", "(", "h", "*", "Handler", ")", "ServeHTTP", "(", "res", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "switch", "req", ".", "Method", "{", "case", "\"", "\"", ",", "\"", "\"", ":", "default", ":", "res", ".", "WriteHeader", "(", "http", ".", "StatusMethodNotAllowed", ")", "\n", "return", "\n", "}", "\n\n", "w", ":=", "io", ".", "Writer", "(", "res", ")", "\n", "res", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "if", "acceptEncoding", "(", "req", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "{", "res", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "zw", ":=", "gzip", ".", "NewWriter", "(", "w", ")", "\n", "defer", "zw", ".", "Close", "(", ")", "\n", "w", "=", "zw", "\n", "}", "\n\n", "h", ".", "WriteStats", "(", "w", ")", "\n", "}" ]
// ServeHTTP satisfies the http.Handler interface.
[ "ServeHTTP", "satisfies", "the", "http", ".", "Handler", "interface", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/prometheus/handler.go#L117-L136
12,188
segmentio/stats
influxdb/client.go
NewClientWith
func NewClientWith(config ClientConfig) *Client { if len(config.Address) == 0 { config.Address = DefaultAddress } if len(config.Database) == 0 { config.Database = DefaultDatabase } if config.BufferSize == 0 { config.BufferSize = DefaultBufferSize } if config.Timeout == 0 { config.Timeout = DefaultTimeout } c := &Client{ serializer: serializer{ url: makeURL(config.Address, config.Database), done: make(chan struct{}), http: http.Client{ Timeout: config.Timeout, Transport: config.Transport, }, }, } c.buffer.BufferSize = config.BufferSize c.buffer.Serializer = &c.serializer return c }
go
func NewClientWith(config ClientConfig) *Client { if len(config.Address) == 0 { config.Address = DefaultAddress } if len(config.Database) == 0 { config.Database = DefaultDatabase } if config.BufferSize == 0 { config.BufferSize = DefaultBufferSize } if config.Timeout == 0 { config.Timeout = DefaultTimeout } c := &Client{ serializer: serializer{ url: makeURL(config.Address, config.Database), done: make(chan struct{}), http: http.Client{ Timeout: config.Timeout, Transport: config.Transport, }, }, } c.buffer.BufferSize = config.BufferSize c.buffer.Serializer = &c.serializer return c }
[ "func", "NewClientWith", "(", "config", "ClientConfig", ")", "*", "Client", "{", "if", "len", "(", "config", ".", "Address", ")", "==", "0", "{", "config", ".", "Address", "=", "DefaultAddress", "\n", "}", "\n\n", "if", "len", "(", "config", ".", "Database", ")", "==", "0", "{", "config", ".", "Database", "=", "DefaultDatabase", "\n", "}", "\n\n", "if", "config", ".", "BufferSize", "==", "0", "{", "config", ".", "BufferSize", "=", "DefaultBufferSize", "\n", "}", "\n\n", "if", "config", ".", "Timeout", "==", "0", "{", "config", ".", "Timeout", "=", "DefaultTimeout", "\n", "}", "\n\n", "c", ":=", "&", "Client", "{", "serializer", ":", "serializer", "{", "url", ":", "makeURL", "(", "config", ".", "Address", ",", "config", ".", "Database", ")", ",", "done", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "http", ":", "http", ".", "Client", "{", "Timeout", ":", "config", ".", "Timeout", ",", "Transport", ":", "config", ".", "Transport", ",", "}", ",", "}", ",", "}", "\n\n", "c", ".", "buffer", ".", "BufferSize", "=", "config", ".", "BufferSize", "\n", "c", ".", "buffer", ".", "Serializer", "=", "&", "c", ".", "serializer", "\n", "return", "c", "\n", "}" ]
// NewClientWith creates and returns a new InfluxDB client configured with the // given config.
[ "NewClientWith", "creates", "and", "returns", "a", "new", "InfluxDB", "client", "configured", "with", "the", "given", "config", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/influxdb/client.go#L73-L104
12,189
segmentio/stats
influxdb/client.go
CreateDB
func (c *Client) CreateDB(db string) error { u := *c.url q := u.Query() q.Del("db") u.Path = "/query" u.RawQuery = q.Encode() r, err := c.http.Post(u.String(), "application/x-www-form-urlencoded", strings.NewReader( fmt.Sprintf("q=CREATE DATABASE %q", db), )) if err != nil { return err } return readResponse(r) }
go
func (c *Client) CreateDB(db string) error { u := *c.url q := u.Query() q.Del("db") u.Path = "/query" u.RawQuery = q.Encode() r, err := c.http.Post(u.String(), "application/x-www-form-urlencoded", strings.NewReader( fmt.Sprintf("q=CREATE DATABASE %q", db), )) if err != nil { return err } return readResponse(r) }
[ "func", "(", "c", "*", "Client", ")", "CreateDB", "(", "db", "string", ")", "error", "{", "u", ":=", "*", "c", ".", "url", "\n", "q", ":=", "u", ".", "Query", "(", ")", "\n", "q", ".", "Del", "(", "\"", "\"", ")", "\n", "u", ".", "Path", "=", "\"", "\"", "\n", "u", ".", "RawQuery", "=", "q", ".", "Encode", "(", ")", "\n\n", "r", ",", "err", ":=", "c", ".", "http", ".", "Post", "(", "u", ".", "String", "(", ")", ",", "\"", "\"", ",", "strings", ".", "NewReader", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "db", ")", ",", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "readResponse", "(", "r", ")", "\n", "}" ]
// CreateDB creates a database named db in the InfluxDB server that the client // was configured to send metrics to.
[ "CreateDB", "creates", "a", "database", "named", "db", "in", "the", "InfluxDB", "server", "that", "the", "client", "was", "configured", "to", "send", "metrics", "to", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/influxdb/client.go#L108-L122
12,190
segmentio/stats
clock.go
StopAt
func (c *Clock) StopAt(now time.Time) { c.observe("total", now.Sub(c.first)) }
go
func (c *Clock) StopAt(now time.Time) { c.observe("total", now.Sub(c.first)) }
[ "func", "(", "c", "*", "Clock", ")", "StopAt", "(", "now", "time", ".", "Time", ")", "{", "c", ".", "observe", "(", "\"", "\"", ",", "now", ".", "Sub", "(", "c", ".", "first", ")", ")", "\n", "}" ]
// StopAt reports the time difference between now and the time the clock was created at. // // The metric produced by this method call will have a "stamp" tag set to // "total".
[ "StopAt", "reports", "the", "time", "difference", "between", "now", "and", "the", "time", "the", "clock", "was", "created", "at", ".", "The", "metric", "produced", "by", "this", "method", "call", "will", "have", "a", "stamp", "tag", "set", "to", "total", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/clock.go#L46-L48
12,191
segmentio/stats
procstats/delaystats.go
NewDelayMetricsWith
func NewDelayMetricsWith(eng *stats.Engine, pid int) *DelayMetrics { return &DelayMetrics{engine: eng, pid: pid} }
go
func NewDelayMetricsWith(eng *stats.Engine, pid int) *DelayMetrics { return &DelayMetrics{engine: eng, pid: pid} }
[ "func", "NewDelayMetricsWith", "(", "eng", "*", "stats", ".", "Engine", ",", "pid", "int", ")", "*", "DelayMetrics", "{", "return", "&", "DelayMetrics", "{", "engine", ":", "eng", ",", "pid", ":", "pid", "}", "\n", "}" ]
// NewDelayStatsWith collects metrics on the process identified by pid and // reports them to eng.
[ "NewDelayStatsWith", "collects", "metrics", "on", "the", "process", "identified", "by", "pid", "and", "reports", "them", "to", "eng", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/procstats/delaystats.go#L29-L31
12,192
segmentio/stats
procstats/go.go
NewGoMetricsWith
func NewGoMetricsWith(eng *stats.Engine) *GoMetrics { g := &GoMetrics{ engine: eng, version: runtime.Version(), } g.memstats.total.memtype = "total" g.memstats.heap.memtype = "heap" g.memstats.stack.memtype = "stack" g.memstats.mspan.memtype = "mspan" g.memstats.mcache.memtype = "mcache" g.memstats.buckhash.memtype = "bucket_hash_table" g.memstats.gc.memtype = "gc" g.memstats.other.memtype = "other" return g }
go
func NewGoMetricsWith(eng *stats.Engine) *GoMetrics { g := &GoMetrics{ engine: eng, version: runtime.Version(), } g.memstats.total.memtype = "total" g.memstats.heap.memtype = "heap" g.memstats.stack.memtype = "stack" g.memstats.mspan.memtype = "mspan" g.memstats.mcache.memtype = "mcache" g.memstats.buckhash.memtype = "bucket_hash_table" g.memstats.gc.memtype = "gc" g.memstats.other.memtype = "other" return g }
[ "func", "NewGoMetricsWith", "(", "eng", "*", "stats", ".", "Engine", ")", "*", "GoMetrics", "{", "g", ":=", "&", "GoMetrics", "{", "engine", ":", "eng", ",", "version", ":", "runtime", ".", "Version", "(", ")", ",", "}", "\n\n", "g", ".", "memstats", ".", "total", ".", "memtype", "=", "\"", "\"", "\n", "g", ".", "memstats", ".", "heap", ".", "memtype", "=", "\"", "\"", "\n", "g", ".", "memstats", ".", "stack", ".", "memtype", "=", "\"", "\"", "\n", "g", ".", "memstats", ".", "mspan", ".", "memtype", "=", "\"", "\"", "\n", "g", ".", "memstats", ".", "mcache", ".", "memtype", "=", "\"", "\"", "\n", "g", ".", "memstats", ".", "buckhash", ".", "memtype", "=", "\"", "\"", "\n", "g", ".", "memstats", ".", "gc", ".", "memtype", "=", "\"", "\"", "\n", "g", ".", "memstats", ".", "other", ".", "memtype", "=", "\"", "\"", "\n", "return", "g", "\n", "}" ]
// NewGoMetricsWith creates a new collector for the Go unrtime that producers // metrics on eng.
[ "NewGoMetricsWith", "creates", "a", "new", "collector", "for", "the", "Go", "unrtime", "that", "producers", "metrics", "on", "eng", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/procstats/go.go#L114-L129
12,193
segmentio/stats
netstats/conn.go
NewConn
func NewConn(c net.Conn) net.Conn { return NewConnWith(stats.DefaultEngine, c) }
go
func NewConn(c net.Conn) net.Conn { return NewConnWith(stats.DefaultEngine, c) }
[ "func", "NewConn", "(", "c", "net", ".", "Conn", ")", "net", ".", "Conn", "{", "return", "NewConnWith", "(", "stats", ".", "DefaultEngine", ",", "c", ")", "\n", "}" ]
// NewConn returns a net.Conn object that wraps c and produces metrics on the // default engine.
[ "NewConn", "returns", "a", "net", ".", "Conn", "object", "that", "wraps", "c", "and", "produces", "metrics", "on", "the", "default", "engine", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/netstats/conn.go#L33-L35
12,194
segmentio/stats
netstats/conn.go
NewConnWith
func NewConnWith(eng *stats.Engine, c net.Conn) net.Conn { nc := &conn{Conn: c, eng: eng} proto := c.LocalAddr().Network() nc.r.metrics.protocol = proto nc.w.metrics.protocol = proto eng.Incr("conn.open:count", stats.T("protocol", proto)) return nc }
go
func NewConnWith(eng *stats.Engine, c net.Conn) net.Conn { nc := &conn{Conn: c, eng: eng} proto := c.LocalAddr().Network() nc.r.metrics.protocol = proto nc.w.metrics.protocol = proto eng.Incr("conn.open:count", stats.T("protocol", proto)) return nc }
[ "func", "NewConnWith", "(", "eng", "*", "stats", ".", "Engine", ",", "c", "net", ".", "Conn", ")", "net", ".", "Conn", "{", "nc", ":=", "&", "conn", "{", "Conn", ":", "c", ",", "eng", ":", "eng", "}", "\n\n", "proto", ":=", "c", ".", "LocalAddr", "(", ")", ".", "Network", "(", ")", "\n", "nc", ".", "r", ".", "metrics", ".", "protocol", "=", "proto", "\n", "nc", ".", "w", ".", "metrics", ".", "protocol", "=", "proto", "\n\n", "eng", ".", "Incr", "(", "\"", "\"", ",", "stats", ".", "T", "(", "\"", "\"", ",", "proto", ")", ")", "\n", "return", "nc", "\n", "}" ]
// NewConn returns a net.Conn object that wraps c and produces metrics on eng.
[ "NewConn", "returns", "a", "net", ".", "Conn", "object", "that", "wraps", "c", "and", "produces", "metrics", "on", "eng", "." ]
17e5e763373e9d6a80804ff4dab85a842ad03a09
https://github.com/segmentio/stats/blob/17e5e763373e9d6a80804ff4dab85a842ad03a09/netstats/conn.go#L38-L47
12,195
palantir/godel
pkg/products/products.go
List
func List() ([]string, error) { godelw, err := newGodelwRunner() if err != nil { return nil, err } products, err := godelw.run("products") if err != nil { return nil, err } return strings.Split(products, "\n"), nil }
go
func List() ([]string, error) { godelw, err := newGodelwRunner() if err != nil { return nil, err } products, err := godelw.run("products") if err != nil { return nil, err } return strings.Split(products, "\n"), nil }
[ "func", "List", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "godelw", ",", "err", ":=", "newGodelwRunner", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "products", ",", "err", ":=", "godelw", ".", "run", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "strings", ".", "Split", "(", "products", ",", "\"", "\\n", "\"", ")", ",", "nil", "\n", "}" ]
// List returns a slice that contains all of the products in the project.
[ "List", "returns", "a", "slice", "that", "contains", "all", "of", "the", "products", "in", "the", "project", "." ]
3410152fb9e7ba34206a144c5c26a7829d52b488
https://github.com/palantir/godel/blob/3410152fb9e7ba34206a144c5c26a7829d52b488/pkg/products/products.go#L27-L37
12,196
palantir/godel
pkg/products/products.go
Dist
func Dist(product string) (string, error) { godelw, err := newGodelwRunner() if err != nil { return "", err } if _, err := godelw.run("dist", product); err != nil { return "", err } return godelw.run("artifacts", "dist", "--absolute", product) }
go
func Dist(product string) (string, error) { godelw, err := newGodelwRunner() if err != nil { return "", err } if _, err := godelw.run("dist", product); err != nil { return "", err } return godelw.run("artifacts", "dist", "--absolute", product) }
[ "func", "Dist", "(", "product", "string", ")", "(", "string", ",", "error", ")", "{", "godelw", ",", "err", ":=", "newGodelwRunner", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "_", ",", "err", ":=", "godelw", ".", "run", "(", "\"", "\"", ",", "product", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "godelw", ".", "run", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "product", ")", "\n", "}" ]
// Dist builds the distribution for the specified product using the "godelw dist" command and returns the path to the // created distribution artifact.
[ "Dist", "builds", "the", "distribution", "for", "the", "specified", "product", "using", "the", "godelw", "dist", "command", "and", "returns", "the", "path", "to", "the", "created", "distribution", "artifact", "." ]
3410152fb9e7ba34206a144c5c26a7829d52b488
https://github.com/palantir/godel/blob/3410152fb9e7ba34206a144c5c26a7829d52b488/pkg/products/products.go#L78-L87
12,197
palantir/godel
framework/pluginapi/plugininfo.go
MustNewPluginInfo
func MustNewPluginInfo(group, product, version string, params ...PluginInfoParam) PluginInfo { cmd, err := NewPluginInfo(group, product, version, params...) if err != nil { panic(errors.Wrapf(err, "failed to create plugin info")) } return cmd }
go
func MustNewPluginInfo(group, product, version string, params ...PluginInfoParam) PluginInfo { cmd, err := NewPluginInfo(group, product, version, params...) if err != nil { panic(errors.Wrapf(err, "failed to create plugin info")) } return cmd }
[ "func", "MustNewPluginInfo", "(", "group", ",", "product", ",", "version", "string", ",", "params", "...", "PluginInfoParam", ")", "PluginInfo", "{", "cmd", ",", "err", ":=", "NewPluginInfo", "(", "group", ",", "product", ",", "version", ",", "params", "...", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "cmd", "\n", "}" ]
// MustNewPluginInfo returns the result of calling NewInfo with the provided parameters. Panics if the call to // NewPluginInfo returns an error, so this function should only be used when the inputs are static and known to be valid.
[ "MustNewPluginInfo", "returns", "the", "result", "of", "calling", "NewInfo", "with", "the", "provided", "parameters", ".", "Panics", "if", "the", "call", "to", "NewPluginInfo", "returns", "an", "error", "so", "this", "function", "should", "only", "be", "used", "when", "the", "inputs", "are", "static", "and", "known", "to", "be", "valid", "." ]
3410152fb9e7ba34206a144c5c26a7829d52b488
https://github.com/palantir/godel/blob/3410152fb9e7ba34206a144c5c26a7829d52b488/framework/pluginapi/plugininfo.go#L50-L56
12,198
palantir/godel
pkg/osarch/osarch.go
String
func (o OSArch) String() string { return fmt.Sprintf("%v-%v", o.OS, o.Arch) }
go
func (o OSArch) String() string { return fmt.Sprintf("%v-%v", o.OS, o.Arch) }
[ "func", "(", "o", "OSArch", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "o", ".", "OS", ",", "o", ".", "Arch", ")", "\n", "}" ]
// String returns a string representation of the form "GOOS-GOARCH".
[ "String", "returns", "a", "string", "representation", "of", "the", "form", "GOOS", "-", "GOARCH", "." ]
3410152fb9e7ba34206a144c5c26a7829d52b488
https://github.com/palantir/godel/blob/3410152fb9e7ba34206a144c5c26a7829d52b488/pkg/osarch/osarch.go#L29-L31
12,199
palantir/godel
pkg/versionedconfig/unsupported.go
ConfigNotSupported
func ConfigNotSupported(name string, cfgBytes []byte) ([]byte, error) { var mapSlice yaml.MapSlice if err := yaml.Unmarshal(cfgBytes, &mapSlice); err != nil { return nil, errors.Wrapf(err, "failed to unmarshal %s configuration as yaml.MapSlice", name) } if len(mapSlice) != 0 { return nil, errors.Errorf("%s does not currently support configuration", name) } return cfgBytes, nil }
go
func ConfigNotSupported(name string, cfgBytes []byte) ([]byte, error) { var mapSlice yaml.MapSlice if err := yaml.Unmarshal(cfgBytes, &mapSlice); err != nil { return nil, errors.Wrapf(err, "failed to unmarshal %s configuration as yaml.MapSlice", name) } if len(mapSlice) != 0 { return nil, errors.Errorf("%s does not currently support configuration", name) } return cfgBytes, nil }
[ "func", "ConfigNotSupported", "(", "name", "string", ",", "cfgBytes", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "mapSlice", "yaml", ".", "MapSlice", "\n", "if", "err", ":=", "yaml", ".", "Unmarshal", "(", "cfgBytes", ",", "&", "mapSlice", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "if", "len", "(", "mapSlice", ")", "!=", "0", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "return", "cfgBytes", ",", "nil", "\n", "}" ]
// ConfigNotSupported verifies that the provided bytes represent empty YAML. If the YAML is non-empty, return an error.
[ "ConfigNotSupported", "verifies", "that", "the", "provided", "bytes", "represent", "empty", "YAML", ".", "If", "the", "YAML", "is", "non", "-", "empty", "return", "an", "error", "." ]
3410152fb9e7ba34206a144c5c26a7829d52b488
https://github.com/palantir/godel/blob/3410152fb9e7ba34206a144c5c26a7829d52b488/pkg/versionedconfig/unsupported.go#L23-L32