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,000
trivago/tgo
tos/file.go
Copy
func Copy(dest, source string) error { srcStat, err := os.Lstat(source) if err != nil { return err } if srcStat.IsDir() { files, err := ioutil.ReadDir(source) if err != nil { return err } if err := os.MkdirAll(dest, srcStat.Mode()); err != nil && !os.IsExist(err) { return err } for _, file := range files { if err := Copy(dest+"/"+file.Name(), source+"/"+file.Name()); err != nil { return err } } return nil // ### return, copy done ### } // Symlink handling if srcStat.Mode()&os.ModeSymlink != 0 { target, err := os.Readlink(source) if err != nil { return err } return os.Symlink(target, dest) // ### return, copy done ### } srcFile, err := os.Open(source) if err != nil { return err } defer srcFile.Close() dstFile, err := os.Create(dest) if err != nil { return err } defer dstFile.Close() if _, err = io.Copy(dstFile, srcFile); err != nil { return err } return os.Chmod(dest, srcStat.Mode()) }
go
func Copy(dest, source string) error { srcStat, err := os.Lstat(source) if err != nil { return err } if srcStat.IsDir() { files, err := ioutil.ReadDir(source) if err != nil { return err } if err := os.MkdirAll(dest, srcStat.Mode()); err != nil && !os.IsExist(err) { return err } for _, file := range files { if err := Copy(dest+"/"+file.Name(), source+"/"+file.Name()); err != nil { return err } } return nil // ### return, copy done ### } // Symlink handling if srcStat.Mode()&os.ModeSymlink != 0 { target, err := os.Readlink(source) if err != nil { return err } return os.Symlink(target, dest) // ### return, copy done ### } srcFile, err := os.Open(source) if err != nil { return err } defer srcFile.Close() dstFile, err := os.Create(dest) if err != nil { return err } defer dstFile.Close() if _, err = io.Copy(dstFile, srcFile); err != nil { return err } return os.Chmod(dest, srcStat.Mode()) }
[ "func", "Copy", "(", "dest", ",", "source", "string", ")", "error", "{", "srcStat", ",", "err", ":=", "os", ".", "Lstat", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "srcStat", ".", "IsDir", "(", ")", "{", "files", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "dest", ",", "srcStat", ".", "Mode", "(", ")", ")", ";", "err", "!=", "nil", "&&", "!", "os", ".", "IsExist", "(", "err", ")", "{", "return", "err", "\n", "}", "\n\n", "for", "_", ",", "file", ":=", "range", "files", "{", "if", "err", ":=", "Copy", "(", "dest", "+", "\"", "\"", "+", "file", ".", "Name", "(", ")", ",", "source", "+", "\"", "\"", "+", "file", ".", "Name", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "// ### return, copy done ###", "\n", "}", "\n\n", "// Symlink handling", "if", "srcStat", ".", "Mode", "(", ")", "&", "os", ".", "ModeSymlink", "!=", "0", "{", "target", ",", "err", ":=", "os", ".", "Readlink", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "os", ".", "Symlink", "(", "target", ",", "dest", ")", "// ### return, copy done ###", "\n", "}", "\n\n", "srcFile", ",", "err", ":=", "os", ".", "Open", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "srcFile", ".", "Close", "(", ")", "\n\n", "dstFile", ",", "err", ":=", "os", ".", "Create", "(", "dest", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "dstFile", ".", "Close", "(", ")", "\n\n", "if", "_", ",", "err", "=", "io", ".", "Copy", "(", "dstFile", ",", "srcFile", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "os", ".", "Chmod", "(", "dest", ",", "srcStat", ".", "Mode", "(", ")", ")", "\n", "}" ]
// Copy is a file copy helper. Files will be copied to their destination, // overwriting existing files. Already existing files that are not part of the // copy process will not be touched. If source is a directory it is walked // recursively. Non-existing folders in dest will be created. // Copy returns upon the first error encountered. In-between results will not // be rolled back.
[ "Copy", "is", "a", "file", "copy", "helper", ".", "Files", "will", "be", "copied", "to", "their", "destination", "overwriting", "existing", "files", ".", "Already", "existing", "files", "that", "are", "not", "part", "of", "the", "copy", "process", "will", "not", "be", "touched", ".", "If", "source", "is", "a", "directory", "it", "is", "walked", "recursively", ".", "Non", "-", "existing", "folders", "in", "dest", "will", "be", "created", ".", "Copy", "returns", "upon", "the", "first", "error", "encountered", ".", "In", "-", "between", "results", "will", "not", "be", "rolled", "back", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tos/file.go#L125-L175
12,001
trivago/tgo
treflect/reflection.go
Int64
func Int64(v interface{}) (int64, bool) { switch reflect.TypeOf(v).Kind() { case reflect.Int: return int64(v.(int)), true case reflect.Int8: return int64(v.(int8)), true case reflect.Int16: return int64(v.(int16)), true case reflect.Int32: return int64(v.(int32)), true case reflect.Int64: return v.(int64), true case reflect.Float32: return int64(v.(float32)), true case reflect.Float64: return int64(v.(float64)), true } return 0, false }
go
func Int64(v interface{}) (int64, bool) { switch reflect.TypeOf(v).Kind() { case reflect.Int: return int64(v.(int)), true case reflect.Int8: return int64(v.(int8)), true case reflect.Int16: return int64(v.(int16)), true case reflect.Int32: return int64(v.(int32)), true case reflect.Int64: return v.(int64), true case reflect.Float32: return int64(v.(float32)), true case reflect.Float64: return int64(v.(float64)), true } return 0, false }
[ "func", "Int64", "(", "v", "interface", "{", "}", ")", "(", "int64", ",", "bool", ")", "{", "switch", "reflect", ".", "TypeOf", "(", "v", ")", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Int", ":", "return", "int64", "(", "v", ".", "(", "int", ")", ")", ",", "true", "\n", "case", "reflect", ".", "Int8", ":", "return", "int64", "(", "v", ".", "(", "int8", ")", ")", ",", "true", "\n", "case", "reflect", ".", "Int16", ":", "return", "int64", "(", "v", ".", "(", "int16", ")", ")", ",", "true", "\n", "case", "reflect", ".", "Int32", ":", "return", "int64", "(", "v", ".", "(", "int32", ")", ")", ",", "true", "\n", "case", "reflect", ".", "Int64", ":", "return", "v", ".", "(", "int64", ")", ",", "true", "\n", "case", "reflect", ".", "Float32", ":", "return", "int64", "(", "v", ".", "(", "float32", ")", ")", ",", "true", "\n", "case", "reflect", ".", "Float64", ":", "return", "int64", "(", "v", ".", "(", "float64", ")", ")", ",", "true", "\n", "}", "\n\n", "return", "0", ",", "false", "\n", "}" ]
// Int64 converts any signed number type to an int64. // The second parameter is returned as false if a non-number type was given.
[ "Int64", "converts", "any", "signed", "number", "type", "to", "an", "int64", ".", "The", "second", "parameter", "is", "returned", "as", "false", "if", "a", "non", "-", "number", "type", "was", "given", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/treflect/reflection.go#L69-L89
12,002
trivago/tgo
treflect/reflection.go
Uint64
func Uint64(v interface{}) (uint64, bool) { switch reflect.TypeOf(v).Kind() { case reflect.Uint: return uint64(v.(uint)), true case reflect.Uint8: return uint64(v.(uint8)), true case reflect.Uint16: return uint64(v.(uint16)), true case reflect.Uint32: return uint64(v.(uint32)), true case reflect.Uint64: return v.(uint64), true } return 0, false }
go
func Uint64(v interface{}) (uint64, bool) { switch reflect.TypeOf(v).Kind() { case reflect.Uint: return uint64(v.(uint)), true case reflect.Uint8: return uint64(v.(uint8)), true case reflect.Uint16: return uint64(v.(uint16)), true case reflect.Uint32: return uint64(v.(uint32)), true case reflect.Uint64: return v.(uint64), true } return 0, false }
[ "func", "Uint64", "(", "v", "interface", "{", "}", ")", "(", "uint64", ",", "bool", ")", "{", "switch", "reflect", ".", "TypeOf", "(", "v", ")", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Uint", ":", "return", "uint64", "(", "v", ".", "(", "uint", ")", ")", ",", "true", "\n", "case", "reflect", ".", "Uint8", ":", "return", "uint64", "(", "v", ".", "(", "uint8", ")", ")", ",", "true", "\n", "case", "reflect", ".", "Uint16", ":", "return", "uint64", "(", "v", ".", "(", "uint16", ")", ")", ",", "true", "\n", "case", "reflect", ".", "Uint32", ":", "return", "uint64", "(", "v", ".", "(", "uint32", ")", ")", ",", "true", "\n", "case", "reflect", ".", "Uint64", ":", "return", "v", ".", "(", "uint64", ")", ",", "true", "\n", "}", "\n\n", "return", "0", ",", "false", "\n", "}" ]
// Uint64 converts any unsigned number type to an uint64. // The second parameter is returned as false if a non-number type was given.
[ "Uint64", "converts", "any", "unsigned", "number", "type", "to", "an", "uint64", ".", "The", "second", "parameter", "is", "returned", "as", "false", "if", "a", "non", "-", "number", "type", "was", "given", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/treflect/reflection.go#L93-L109
12,003
trivago/tgo
treflect/reflection.go
Float32
func Float32(v interface{}) (float32, bool) { switch reflect.TypeOf(v).Kind() { case reflect.Int: return float32(v.(int)), true case reflect.Uint: return float32(v.(uint)), true case reflect.Int8: return float32(v.(int8)), true case reflect.Uint8: return float32(v.(uint8)), true case reflect.Int16: return float32(v.(int16)), true case reflect.Uint16: return float32(v.(uint16)), true case reflect.Int32: return float32(v.(int32)), true case reflect.Uint32: return float32(v.(uint32)), true case reflect.Int64: return float32(v.(int64)), true case reflect.Uint64: return float32(v.(uint64)), true case reflect.Float32: return v.(float32), true case reflect.Float64: return float32(v.(float64)), true } return 0, false }
go
func Float32(v interface{}) (float32, bool) { switch reflect.TypeOf(v).Kind() { case reflect.Int: return float32(v.(int)), true case reflect.Uint: return float32(v.(uint)), true case reflect.Int8: return float32(v.(int8)), true case reflect.Uint8: return float32(v.(uint8)), true case reflect.Int16: return float32(v.(int16)), true case reflect.Uint16: return float32(v.(uint16)), true case reflect.Int32: return float32(v.(int32)), true case reflect.Uint32: return float32(v.(uint32)), true case reflect.Int64: return float32(v.(int64)), true case reflect.Uint64: return float32(v.(uint64)), true case reflect.Float32: return v.(float32), true case reflect.Float64: return float32(v.(float64)), true } return 0, false }
[ "func", "Float32", "(", "v", "interface", "{", "}", ")", "(", "float32", ",", "bool", ")", "{", "switch", "reflect", ".", "TypeOf", "(", "v", ")", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Int", ":", "return", "float32", "(", "v", ".", "(", "int", ")", ")", ",", "true", "\n", "case", "reflect", ".", "Uint", ":", "return", "float32", "(", "v", ".", "(", "uint", ")", ")", ",", "true", "\n", "case", "reflect", ".", "Int8", ":", "return", "float32", "(", "v", ".", "(", "int8", ")", ")", ",", "true", "\n", "case", "reflect", ".", "Uint8", ":", "return", "float32", "(", "v", ".", "(", "uint8", ")", ")", ",", "true", "\n", "case", "reflect", ".", "Int16", ":", "return", "float32", "(", "v", ".", "(", "int16", ")", ")", ",", "true", "\n", "case", "reflect", ".", "Uint16", ":", "return", "float32", "(", "v", ".", "(", "uint16", ")", ")", ",", "true", "\n", "case", "reflect", ".", "Int32", ":", "return", "float32", "(", "v", ".", "(", "int32", ")", ")", ",", "true", "\n", "case", "reflect", ".", "Uint32", ":", "return", "float32", "(", "v", ".", "(", "uint32", ")", ")", ",", "true", "\n", "case", "reflect", ".", "Int64", ":", "return", "float32", "(", "v", ".", "(", "int64", ")", ")", ",", "true", "\n", "case", "reflect", ".", "Uint64", ":", "return", "float32", "(", "v", ".", "(", "uint64", ")", ")", ",", "true", "\n", "case", "reflect", ".", "Float32", ":", "return", "v", ".", "(", "float32", ")", ",", "true", "\n", "case", "reflect", ".", "Float64", ":", "return", "float32", "(", "v", ".", "(", "float64", ")", ")", ",", "true", "\n", "}", "\n\n", "return", "0", ",", "false", "\n", "}" ]
// Float32 converts any number type to an float32. // The second parameter is returned as false if a non-number type was given.
[ "Float32", "converts", "any", "number", "type", "to", "an", "float32", ".", "The", "second", "parameter", "is", "returned", "as", "false", "if", "a", "non", "-", "number", "type", "was", "given", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/treflect/reflection.go#L113-L143
12,004
trivago/tgo
treflect/reflection.go
UnsafeCopy
func UnsafeCopy(dst, src interface{}) { dstValue := reflect.ValueOf(dst) srcValue := reflect.ValueOf(src) UnsafeCopyValue(dstValue, srcValue) }
go
func UnsafeCopy(dst, src interface{}) { dstValue := reflect.ValueOf(dst) srcValue := reflect.ValueOf(src) UnsafeCopyValue(dstValue, srcValue) }
[ "func", "UnsafeCopy", "(", "dst", ",", "src", "interface", "{", "}", ")", "{", "dstValue", ":=", "reflect", ".", "ValueOf", "(", "dst", ")", "\n", "srcValue", ":=", "reflect", ".", "ValueOf", "(", "src", ")", "\n", "UnsafeCopyValue", "(", "dstValue", ",", "srcValue", ")", "\n", "}" ]
// UnsafeCopy will copy data from src to dst while ignoring type information. // Both types need to be of the same size and dst and src have to be pointers. // UnsafeCopy will panic if these requirements are not met.
[ "UnsafeCopy", "will", "copy", "data", "from", "src", "to", "dst", "while", "ignoring", "type", "information", ".", "Both", "types", "need", "to", "be", "of", "the", "same", "size", "and", "dst", "and", "src", "have", "to", "be", "pointers", ".", "UnsafeCopy", "will", "panic", "if", "these", "requirements", "are", "not", "met", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/treflect/reflection.go#L212-L216
12,005
trivago/tgo
treflect/reflection.go
SetMemberByName
func SetMemberByName(ptrToStruct interface{}, name string, data interface{}) { structVal := reflect.Indirect(reflect.ValueOf(ptrToStruct)) member := structVal.FieldByName(name) SetValue(member, data) }
go
func SetMemberByName(ptrToStruct interface{}, name string, data interface{}) { structVal := reflect.Indirect(reflect.ValueOf(ptrToStruct)) member := structVal.FieldByName(name) SetValue(member, data) }
[ "func", "SetMemberByName", "(", "ptrToStruct", "interface", "{", "}", ",", "name", "string", ",", "data", "interface", "{", "}", ")", "{", "structVal", ":=", "reflect", ".", "Indirect", "(", "reflect", ".", "ValueOf", "(", "ptrToStruct", ")", ")", "\n", "member", ":=", "structVal", ".", "FieldByName", "(", "name", ")", "\n\n", "SetValue", "(", "member", ",", "data", ")", "\n", "}" ]
// SetMemberByName sets member name of the given pointer-to-struct to the data // passed to this function. The member may be private, too.
[ "SetMemberByName", "sets", "member", "name", "of", "the", "given", "pointer", "-", "to", "-", "struct", "to", "the", "data", "passed", "to", "this", "function", ".", "The", "member", "may", "be", "private", "too", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/treflect/reflection.go#L258-L263
12,006
trivago/tgo
treflect/reflection.go
SetMemberByIndex
func SetMemberByIndex(ptrToStruct interface{}, idx int, data interface{}) { structVal := reflect.Indirect(reflect.ValueOf(ptrToStruct)) member := structVal.Field(idx) SetValue(member, data) }
go
func SetMemberByIndex(ptrToStruct interface{}, idx int, data interface{}) { structVal := reflect.Indirect(reflect.ValueOf(ptrToStruct)) member := structVal.Field(idx) SetValue(member, data) }
[ "func", "SetMemberByIndex", "(", "ptrToStruct", "interface", "{", "}", ",", "idx", "int", ",", "data", "interface", "{", "}", ")", "{", "structVal", ":=", "reflect", ".", "Indirect", "(", "reflect", ".", "ValueOf", "(", "ptrToStruct", ")", ")", "\n", "member", ":=", "structVal", ".", "Field", "(", "idx", ")", "\n\n", "SetValue", "(", "member", ",", "data", ")", "\n", "}" ]
// SetMemberByIndex sets member idx of the given pointer-to-struct to the data // passed to this function. The member may be private, too.
[ "SetMemberByIndex", "sets", "member", "idx", "of", "the", "given", "pointer", "-", "to", "-", "struct", "to", "the", "data", "passed", "to", "this", "function", ".", "The", "member", "may", "be", "private", "too", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/treflect/reflection.go#L267-L272
12,007
trivago/tgo
tio/bytewriter.go
Write
func (b ByteWriter) Write(data []byte) (int, error) { start := len(*b.buffer) size := len(data) capacity := cap(*b.buffer) if start+size > capacity { size := capacity - start *b.buffer = (*b.buffer)[:capacity] copy((*b.buffer)[start:], data[:size]) return size, io.EOF } *b.buffer = (*b.buffer)[:start+size] copy((*b.buffer)[start:], data) return size, nil }
go
func (b ByteWriter) Write(data []byte) (int, error) { start := len(*b.buffer) size := len(data) capacity := cap(*b.buffer) if start+size > capacity { size := capacity - start *b.buffer = (*b.buffer)[:capacity] copy((*b.buffer)[start:], data[:size]) return size, io.EOF } *b.buffer = (*b.buffer)[:start+size] copy((*b.buffer)[start:], data) return size, nil }
[ "func", "(", "b", "ByteWriter", ")", "Write", "(", "data", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "start", ":=", "len", "(", "*", "b", ".", "buffer", ")", "\n", "size", ":=", "len", "(", "data", ")", "\n", "capacity", ":=", "cap", "(", "*", "b", ".", "buffer", ")", "\n\n", "if", "start", "+", "size", ">", "capacity", "{", "size", ":=", "capacity", "-", "start", "\n", "*", "b", ".", "buffer", "=", "(", "*", "b", ".", "buffer", ")", "[", ":", "capacity", "]", "\n", "copy", "(", "(", "*", "b", ".", "buffer", ")", "[", "start", ":", "]", ",", "data", "[", ":", "size", "]", ")", "\n", "return", "size", ",", "io", ".", "EOF", "\n", "}", "\n\n", "*", "b", ".", "buffer", "=", "(", "*", "b", ".", "buffer", ")", "[", ":", "start", "+", "size", "]", "\n", "copy", "(", "(", "*", "b", ".", "buffer", ")", "[", "start", ":", "]", ",", "data", ")", "\n\n", "return", "size", ",", "nil", "\n", "}" ]
// Write writes data to the wrapped slice if there is enough space available. // If not, data is written until the wrapped slice has reached its capacity // and io.EOF is returned.
[ "Write", "writes", "data", "to", "the", "wrapped", "slice", "if", "there", "is", "enough", "space", "available", ".", "If", "not", "data", "is", "written", "until", "the", "wrapped", "slice", "has", "reached", "its", "capacity", "and", "io", ".", "EOF", "is", "returned", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tio/bytewriter.go#L42-L58
12,008
trivago/tgo
tstrings/parser.go
NewTransition
func NewTransition(nextState ParserStateID, flags ParserFlag, callback ParsedFunc) Transition { return Transition{ nextState: nextState, flags: flags, callback: callback, } }
go
func NewTransition(nextState ParserStateID, flags ParserFlag, callback ParsedFunc) Transition { return Transition{ nextState: nextState, flags: flags, callback: callback, } }
[ "func", "NewTransition", "(", "nextState", "ParserStateID", ",", "flags", "ParserFlag", ",", "callback", "ParsedFunc", ")", "Transition", "{", "return", "Transition", "{", "nextState", ":", "nextState", ",", "flags", ":", "flags", ",", "callback", ":", "callback", ",", "}", "\n", "}" ]
// NewTransition creates a new transition to a given state.
[ "NewTransition", "creates", "a", "new", "transition", "to", "a", "given", "state", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/parser.go#L88-L94
12,009
trivago/tgo
tstrings/parser.go
NewTransitionParser
func NewTransitionParser() TransitionParser { return TransitionParser{ lookup: []string{}, tokens: []*tcontainer.TrieNode{}, stack: []ParserStateID{}, } }
go
func NewTransitionParser() TransitionParser { return TransitionParser{ lookup: []string{}, tokens: []*tcontainer.TrieNode{}, stack: []ParserStateID{}, } }
[ "func", "NewTransitionParser", "(", ")", "TransitionParser", "{", "return", "TransitionParser", "{", "lookup", ":", "[", "]", "string", "{", "}", ",", "tokens", ":", "[", "]", "*", "tcontainer", ".", "TrieNode", "{", "}", ",", "stack", ":", "[", "]", "ParserStateID", "{", "}", ",", "}", "\n", "}" ]
// NewTransitionParser creates a new transition based parser
[ "NewTransitionParser", "creates", "a", "new", "transition", "based", "parser" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/parser.go#L97-L103
12,010
trivago/tgo
tstrings/parser.go
GetStateID
func (parser *TransitionParser) GetStateID(stateName string) ParserStateID { if len(stateName) == 0 { return ParserStateStop } for id, name := range parser.lookup { if name == stateName { return ParserStateID(id) // ### return, found ### } } id := ParserStateID(len(parser.lookup)) parser.lookup = append(parser.lookup, stateName) parser.tokens = append(parser.tokens, nil) return id }
go
func (parser *TransitionParser) GetStateID(stateName string) ParserStateID { if len(stateName) == 0 { return ParserStateStop } for id, name := range parser.lookup { if name == stateName { return ParserStateID(id) // ### return, found ### } } id := ParserStateID(len(parser.lookup)) parser.lookup = append(parser.lookup, stateName) parser.tokens = append(parser.tokens, nil) return id }
[ "func", "(", "parser", "*", "TransitionParser", ")", "GetStateID", "(", "stateName", "string", ")", "ParserStateID", "{", "if", "len", "(", "stateName", ")", "==", "0", "{", "return", "ParserStateStop", "\n", "}", "\n\n", "for", "id", ",", "name", ":=", "range", "parser", ".", "lookup", "{", "if", "name", "==", "stateName", "{", "return", "ParserStateID", "(", "id", ")", "// ### return, found ###", "\n", "}", "\n", "}", "\n\n", "id", ":=", "ParserStateID", "(", "len", "(", "parser", ".", "lookup", ")", ")", "\n", "parser", ".", "lookup", "=", "append", "(", "parser", ".", "lookup", ",", "stateName", ")", "\n", "parser", ".", "tokens", "=", "append", "(", "parser", ".", "tokens", ",", "nil", ")", "\n", "return", "id", "\n", "}" ]
// GetStateID creates a hash from the given state name. // Empty state names will be translated to ParserStateStop.
[ "GetStateID", "creates", "a", "hash", "from", "the", "given", "state", "name", ".", "Empty", "state", "names", "will", "be", "translated", "to", "ParserStateStop", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/parser.go#L172-L187
12,011
trivago/tgo
tstrings/parser.go
GetStateName
func (parser *TransitionParser) GetStateName(id ParserStateID) string { if id < ParserStateID(len(parser.lookup)) { return parser.lookup[id] } return "" }
go
func (parser *TransitionParser) GetStateName(id ParserStateID) string { if id < ParserStateID(len(parser.lookup)) { return parser.lookup[id] } return "" }
[ "func", "(", "parser", "*", "TransitionParser", ")", "GetStateName", "(", "id", "ParserStateID", ")", "string", "{", "if", "id", "<", "ParserStateID", "(", "len", "(", "parser", ".", "lookup", ")", ")", "{", "return", "parser", ".", "lookup", "[", "id", "]", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// GetStateName returns the name for the given state id or an empty string if // the id could not be found.
[ "GetStateName", "returns", "the", "name", "for", "the", "given", "state", "id", "or", "an", "empty", "string", "if", "the", "id", "could", "not", "be", "found", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/parser.go#L191-L196
12,012
trivago/tgo
tstrings/parser.go
AddDirectives
func (parser *TransitionParser) AddDirectives(directives []TransitionDirective) { for _, dir := range directives { parser.Add(dir.State, dir.Token, dir.NextState, dir.Flags, dir.Callback) } }
go
func (parser *TransitionParser) AddDirectives(directives []TransitionDirective) { for _, dir := range directives { parser.Add(dir.State, dir.Token, dir.NextState, dir.Flags, dir.Callback) } }
[ "func", "(", "parser", "*", "TransitionParser", ")", "AddDirectives", "(", "directives", "[", "]", "TransitionDirective", ")", "{", "for", "_", ",", "dir", ":=", "range", "directives", "{", "parser", ".", "Add", "(", "dir", ".", "State", ",", "dir", ".", "Token", ",", "dir", ".", "NextState", ",", "dir", ".", "Flags", ",", "dir", ".", "Callback", ")", "\n", "}", "\n", "}" ]
// AddDirectives is a convenience function to add multiple transitions in as a // batch.
[ "AddDirectives", "is", "a", "convenience", "function", "to", "add", "multiple", "transitions", "in", "as", "a", "batch", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/parser.go#L200-L204
12,013
trivago/tgo
tstrings/parser.go
Add
func (parser *TransitionParser) Add(stateName string, token string, nextStateName string, flags ParserFlag, callback ParsedFunc) { nextStateID := parser.GetStateID(nextStateName) parser.AddTransition(stateName, NewTransition(nextStateID, flags, callback), token) }
go
func (parser *TransitionParser) Add(stateName string, token string, nextStateName string, flags ParserFlag, callback ParsedFunc) { nextStateID := parser.GetStateID(nextStateName) parser.AddTransition(stateName, NewTransition(nextStateID, flags, callback), token) }
[ "func", "(", "parser", "*", "TransitionParser", ")", "Add", "(", "stateName", "string", ",", "token", "string", ",", "nextStateName", "string", ",", "flags", "ParserFlag", ",", "callback", "ParsedFunc", ")", "{", "nextStateID", ":=", "parser", ".", "GetStateID", "(", "nextStateName", ")", "\n", "parser", ".", "AddTransition", "(", "stateName", ",", "NewTransition", "(", "nextStateID", ",", "flags", ",", "callback", ")", ",", "token", ")", "\n", "}" ]
// Add adds a new transition to a given parser state.
[ "Add", "adds", "a", "new", "transition", "to", "a", "given", "parser", "state", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/parser.go#L207-L210
12,014
trivago/tgo
tstrings/parser.go
Stop
func (parser *TransitionParser) Stop(stateName string, token string, flags ParserFlag, callback ParsedFunc) { parser.AddTransition(stateName, NewTransition(ParserStateStop, flags, callback), token) }
go
func (parser *TransitionParser) Stop(stateName string, token string, flags ParserFlag, callback ParsedFunc) { parser.AddTransition(stateName, NewTransition(ParserStateStop, flags, callback), token) }
[ "func", "(", "parser", "*", "TransitionParser", ")", "Stop", "(", "stateName", "string", ",", "token", "string", ",", "flags", "ParserFlag", ",", "callback", "ParsedFunc", ")", "{", "parser", ".", "AddTransition", "(", "stateName", ",", "NewTransition", "(", "ParserStateStop", ",", "flags", ",", "callback", ")", ",", "token", ")", "\n", "}" ]
// Stop adds a stop transition to a given parser state.
[ "Stop", "adds", "a", "stop", "transition", "to", "a", "given", "parser", "state", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/parser.go#L213-L215
12,015
trivago/tgo
tstrings/parser.go
AddTransition
func (parser *TransitionParser) AddTransition(stateName string, newTrans Transition, token string) { stateID := parser.GetStateID(stateName) if state := parser.tokens[stateID]; state == nil { parser.tokens[stateID] = tcontainer.NewTrie([]byte(token), newTrans) } else { parser.tokens[stateID] = state.Add([]byte(token), newTrans) } }
go
func (parser *TransitionParser) AddTransition(stateName string, newTrans Transition, token string) { stateID := parser.GetStateID(stateName) if state := parser.tokens[stateID]; state == nil { parser.tokens[stateID] = tcontainer.NewTrie([]byte(token), newTrans) } else { parser.tokens[stateID] = state.Add([]byte(token), newTrans) } }
[ "func", "(", "parser", "*", "TransitionParser", ")", "AddTransition", "(", "stateName", "string", ",", "newTrans", "Transition", ",", "token", "string", ")", "{", "stateID", ":=", "parser", ".", "GetStateID", "(", "stateName", ")", "\n\n", "if", "state", ":=", "parser", ".", "tokens", "[", "stateID", "]", ";", "state", "==", "nil", "{", "parser", ".", "tokens", "[", "stateID", "]", "=", "tcontainer", ".", "NewTrie", "(", "[", "]", "byte", "(", "token", ")", ",", "newTrans", ")", "\n", "}", "else", "{", "parser", ".", "tokens", "[", "stateID", "]", "=", "state", ".", "Add", "(", "[", "]", "byte", "(", "token", ")", ",", "newTrans", ")", "\n", "}", "\n", "}" ]
// AddTransition adds a transition from a given state to the map
[ "AddTransition", "adds", "a", "transition", "from", "a", "given", "state", "to", "the", "map" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/parser.go#L218-L226
12,016
trivago/tgo
tstrings/parser.go
Parse
func (parser *TransitionParser) Parse(data []byte, state string) ([]byte, ParserStateID) { currentStateID := parser.GetStateID(state) if currentStateID == ParserStateStop { return nil, currentStateID // ### return, immediate stop ### } currentState := parser.tokens[currentStateID] dataLen := len(data) readStartIdx := 0 continueIdx := 0 for parseIdx := 0; parseIdx < dataLen; parseIdx++ { node := currentState.MatchStart(data[parseIdx:]) if node == nil { continue // ### continue, no match ### } t := node.Payload.(Transition) if t.callback != nil { if t.flags&ParserFlagInclude != 0 { t.callback(data[readStartIdx:parseIdx+node.PathLen], currentStateID) } else { t.callback(data[readStartIdx:parseIdx], currentStateID) } } // Move the reader if t.flags&ParserFlagContinue == 0 { parseIdx += node.PathLen - 1 } else { parseIdx-- } continueIdx = parseIdx + 1 if t.flags&ParserFlagAppend == 0 { readStartIdx = continueIdx } nextStateID := t.nextState // Pop before push to allow both at the same time if t.flags&ParserFlagPop != 0 { stackLen := len(parser.stack) if stackLen > 0 { nextStateID = parser.stack[stackLen-1] parser.stack = parser.stack[:stackLen-1] } } if t.flags&ParserFlagPush != 0 { parser.stack = append(parser.stack, currentStateID) } // Transition to next currentStateID = nextStateID if currentStateID == ParserStateStop { break // ### break, stop state ### } currentState = parser.tokens[currentStateID] } if readStartIdx == dataLen { return nil, currentStateID // ### return, everything parsed ### } return data[readStartIdx:], currentStateID }
go
func (parser *TransitionParser) Parse(data []byte, state string) ([]byte, ParserStateID) { currentStateID := parser.GetStateID(state) if currentStateID == ParserStateStop { return nil, currentStateID // ### return, immediate stop ### } currentState := parser.tokens[currentStateID] dataLen := len(data) readStartIdx := 0 continueIdx := 0 for parseIdx := 0; parseIdx < dataLen; parseIdx++ { node := currentState.MatchStart(data[parseIdx:]) if node == nil { continue // ### continue, no match ### } t := node.Payload.(Transition) if t.callback != nil { if t.flags&ParserFlagInclude != 0 { t.callback(data[readStartIdx:parseIdx+node.PathLen], currentStateID) } else { t.callback(data[readStartIdx:parseIdx], currentStateID) } } // Move the reader if t.flags&ParserFlagContinue == 0 { parseIdx += node.PathLen - 1 } else { parseIdx-- } continueIdx = parseIdx + 1 if t.flags&ParserFlagAppend == 0 { readStartIdx = continueIdx } nextStateID := t.nextState // Pop before push to allow both at the same time if t.flags&ParserFlagPop != 0 { stackLen := len(parser.stack) if stackLen > 0 { nextStateID = parser.stack[stackLen-1] parser.stack = parser.stack[:stackLen-1] } } if t.flags&ParserFlagPush != 0 { parser.stack = append(parser.stack, currentStateID) } // Transition to next currentStateID = nextStateID if currentStateID == ParserStateStop { break // ### break, stop state ### } currentState = parser.tokens[currentStateID] } if readStartIdx == dataLen { return nil, currentStateID // ### return, everything parsed ### } return data[readStartIdx:], currentStateID }
[ "func", "(", "parser", "*", "TransitionParser", ")", "Parse", "(", "data", "[", "]", "byte", ",", "state", "string", ")", "(", "[", "]", "byte", ",", "ParserStateID", ")", "{", "currentStateID", ":=", "parser", ".", "GetStateID", "(", "state", ")", "\n\n", "if", "currentStateID", "==", "ParserStateStop", "{", "return", "nil", ",", "currentStateID", "// ### return, immediate stop ###", "\n", "}", "\n\n", "currentState", ":=", "parser", ".", "tokens", "[", "currentStateID", "]", "\n", "dataLen", ":=", "len", "(", "data", ")", "\n", "readStartIdx", ":=", "0", "\n", "continueIdx", ":=", "0", "\n\n", "for", "parseIdx", ":=", "0", ";", "parseIdx", "<", "dataLen", ";", "parseIdx", "++", "{", "node", ":=", "currentState", ".", "MatchStart", "(", "data", "[", "parseIdx", ":", "]", ")", "\n", "if", "node", "==", "nil", "{", "continue", "// ### continue, no match ###", "\n", "}", "\n\n", "t", ":=", "node", ".", "Payload", ".", "(", "Transition", ")", "\n", "if", "t", ".", "callback", "!=", "nil", "{", "if", "t", ".", "flags", "&", "ParserFlagInclude", "!=", "0", "{", "t", ".", "callback", "(", "data", "[", "readStartIdx", ":", "parseIdx", "+", "node", ".", "PathLen", "]", ",", "currentStateID", ")", "\n", "}", "else", "{", "t", ".", "callback", "(", "data", "[", "readStartIdx", ":", "parseIdx", "]", ",", "currentStateID", ")", "\n", "}", "\n", "}", "\n\n", "// Move the reader", "if", "t", ".", "flags", "&", "ParserFlagContinue", "==", "0", "{", "parseIdx", "+=", "node", ".", "PathLen", "-", "1", "\n", "}", "else", "{", "parseIdx", "--", "\n", "}", "\n", "continueIdx", "=", "parseIdx", "+", "1", "\n\n", "if", "t", ".", "flags", "&", "ParserFlagAppend", "==", "0", "{", "readStartIdx", "=", "continueIdx", "\n", "}", "\n\n", "nextStateID", ":=", "t", ".", "nextState", "\n\n", "// Pop before push to allow both at the same time", "if", "t", ".", "flags", "&", "ParserFlagPop", "!=", "0", "{", "stackLen", ":=", "len", "(", "parser", ".", "stack", ")", "\n", "if", "stackLen", ">", "0", "{", "nextStateID", "=", "parser", ".", "stack", "[", "stackLen", "-", "1", "]", "\n", "parser", ".", "stack", "=", "parser", ".", "stack", "[", ":", "stackLen", "-", "1", "]", "\n", "}", "\n", "}", "\n\n", "if", "t", ".", "flags", "&", "ParserFlagPush", "!=", "0", "{", "parser", ".", "stack", "=", "append", "(", "parser", ".", "stack", ",", "currentStateID", ")", "\n", "}", "\n\n", "// Transition to next", "currentStateID", "=", "nextStateID", "\n", "if", "currentStateID", "==", "ParserStateStop", "{", "break", "// ### break, stop state ###", "\n", "}", "\n\n", "currentState", "=", "parser", ".", "tokens", "[", "currentStateID", "]", "\n", "}", "\n\n", "if", "readStartIdx", "==", "dataLen", "{", "return", "nil", ",", "currentStateID", "// ### return, everything parsed ###", "\n", "}", "\n\n", "return", "data", "[", "readStartIdx", ":", "]", ",", "currentStateID", "\n", "}" ]
// Parse starts parsing at a given stateID. // This function returns the remaining parts of data that did not match a // transition as well as the last state the parser has been set to.
[ "Parse", "starts", "parsing", "at", "a", "given", "stateID", ".", "This", "function", "returns", "the", "remaining", "parts", "of", "data", "that", "did", "not", "match", "a", "transition", "as", "well", "as", "the", "last", "state", "the", "parser", "has", "been", "set", "to", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tstrings/parser.go#L231-L299
12,017
trivago/tgo
tnet/network.go
SplitAddressToURI
func SplitAddressToURI(addressString string, defaultProtocol string) (uri URI, err error) { portString := "" uri.Protocol, uri.Address, portString, err = SplitAddress(addressString, defaultProtocol) portNum, _ := strconv.ParseInt(portString, 10, 16) uri.Port = uint16(portNum) return uri, err }
go
func SplitAddressToURI(addressString string, defaultProtocol string) (uri URI, err error) { portString := "" uri.Protocol, uri.Address, portString, err = SplitAddress(addressString, defaultProtocol) portNum, _ := strconv.ParseInt(portString, 10, 16) uri.Port = uint16(portNum) return uri, err }
[ "func", "SplitAddressToURI", "(", "addressString", "string", ",", "defaultProtocol", "string", ")", "(", "uri", "URI", ",", "err", "error", ")", "{", "portString", ":=", "\"", "\"", "\n", "uri", ".", "Protocol", ",", "uri", ".", "Address", ",", "portString", ",", "err", "=", "SplitAddress", "(", "addressString", ",", "defaultProtocol", ")", "\n", "portNum", ",", "_", ":=", "strconv", ".", "ParseInt", "(", "portString", ",", "10", ",", "16", ")", "\n", "uri", ".", "Port", "=", "uint16", "(", "portNum", ")", "\n", "return", "uri", ",", "err", "\n", "}" ]
// SplitAddressToURI acts like SplitAddress but returns an URI struct instead.
[ "SplitAddressToURI", "acts", "like", "SplitAddress", "but", "returns", "an", "URI", "struct", "instead", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tnet/network.go#L72-L78
12,018
trivago/tgo
tnet/network.go
IsDisconnectedError
func IsDisconnectedError(err error) bool { if err == io.EOF { return true // ### return, closed stream ### } netErr, isNetErr := err.(*net.OpError) if isNetErr { errno, isErrno := netErr.Err.(syscall.Errno) if isErrno { switch errno { default: case syscall.ECONNRESET: return true // ### return, close connection ### } } } return false }
go
func IsDisconnectedError(err error) bool { if err == io.EOF { return true // ### return, closed stream ### } netErr, isNetErr := err.(*net.OpError) if isNetErr { errno, isErrno := netErr.Err.(syscall.Errno) if isErrno { switch errno { default: case syscall.ECONNRESET: return true // ### return, close connection ### } } } return false }
[ "func", "IsDisconnectedError", "(", "err", "error", ")", "bool", "{", "if", "err", "==", "io", ".", "EOF", "{", "return", "true", "// ### return, closed stream ###", "\n", "}", "\n\n", "netErr", ",", "isNetErr", ":=", "err", ".", "(", "*", "net", ".", "OpError", ")", "\n", "if", "isNetErr", "{", "errno", ",", "isErrno", ":=", "netErr", ".", "Err", ".", "(", "syscall", ".", "Errno", ")", "\n", "if", "isErrno", "{", "switch", "errno", "{", "default", ":", "case", "syscall", ".", "ECONNRESET", ":", "return", "true", "// ### return, close connection ###", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// IsDisconnectedError returns true if the given error is related to a // disconnected socket.
[ "IsDisconnectedError", "returns", "true", "if", "the", "given", "error", "is", "related", "to", "a", "disconnected", "socket", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tnet/network.go#L82-L100
12,019
trivago/tgo
tfmt/cursor.go
String
func (c CursorPosition) String() string { return "\x1b[" + strconv.Itoa(c.X) + ";" + strconv.Itoa(c.Y) + "H" }
go
func (c CursorPosition) String() string { return "\x1b[" + strconv.Itoa(c.X) + ";" + strconv.Itoa(c.Y) + "H" }
[ "func", "(", "c", "CursorPosition", ")", "String", "(", ")", "string", "{", "return", "\"", "\\x1b", "\"", "+", "strconv", ".", "Itoa", "(", "c", ".", "X", ")", "+", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "c", ".", "Y", ")", "+", "\"", "\"", "\n", "}" ]
// String implements the stringer interface for CursorPosition
[ "String", "implements", "the", "stringer", "interface", "for", "CursorPosition" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tfmt/cursor.go#L71-L73
12,020
trivago/tgo
tsync/waitgroup.go
Add
func (wg *WaitGroup) Add(delta int) { atomic.AddInt32(&wg.counter, int32(delta)) }
go
func (wg *WaitGroup) Add(delta int) { atomic.AddInt32(&wg.counter, int32(delta)) }
[ "func", "(", "wg", "*", "WaitGroup", ")", "Add", "(", "delta", "int", ")", "{", "atomic", ".", "AddInt32", "(", "&", "wg", ".", "counter", ",", "int32", "(", "delta", ")", ")", "\n", "}" ]
// Add increments the waitgroup counter by the given value. // Delta may be negative.
[ "Add", "increments", "the", "waitgroup", "counter", "by", "the", "given", "value", ".", "Delta", "may", "be", "negative", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tsync/waitgroup.go#L42-L44
12,021
trivago/tgo
tsync/waitgroup.go
IncWhenDone
func (wg *WaitGroup) IncWhenDone() { spin := NewSpinner(SpinPriorityHigh) for !atomic.CompareAndSwapInt32(&wg.counter, 0, 1) { spin.Yield() } }
go
func (wg *WaitGroup) IncWhenDone() { spin := NewSpinner(SpinPriorityHigh) for !atomic.CompareAndSwapInt32(&wg.counter, 0, 1) { spin.Yield() } }
[ "func", "(", "wg", "*", "WaitGroup", ")", "IncWhenDone", "(", ")", "{", "spin", ":=", "NewSpinner", "(", "SpinPriorityHigh", ")", "\n", "for", "!", "atomic", ".", "CompareAndSwapInt32", "(", "&", "wg", ".", "counter", ",", "0", ",", "1", ")", "{", "spin", ".", "Yield", "(", ")", "\n", "}", "\n", "}" ]
// IncWhenDone wait until the counter is exactly 0 and triggeres an increment // if this is found to be true
[ "IncWhenDone", "wait", "until", "the", "counter", "is", "exactly", "0", "and", "triggeres", "an", "increment", "if", "this", "is", "found", "to", "be", "true" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tsync/waitgroup.go#L58-L63
12,022
trivago/tgo
tsync/waitgroup.go
Wait
func (wg *WaitGroup) Wait() { spin := NewSpinner(SpinPriorityHigh) for wg.Active() { spin.Yield() } }
go
func (wg *WaitGroup) Wait() { spin := NewSpinner(SpinPriorityHigh) for wg.Active() { spin.Yield() } }
[ "func", "(", "wg", "*", "WaitGroup", ")", "Wait", "(", ")", "{", "spin", ":=", "NewSpinner", "(", "SpinPriorityHigh", ")", "\n", "for", "wg", ".", "Active", "(", ")", "{", "spin", ".", "Yield", "(", ")", "\n", "}", "\n", "}" ]
// Wait blocks until the counter is 0 or less.
[ "Wait", "blocks", "until", "the", "counter", "is", "0", "or", "less", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tsync/waitgroup.go#L66-L71
12,023
trivago/tgo
tsync/waitgroup.go
WaitFor
func (wg *WaitGroup) WaitFor(timeout time.Duration) bool { if timeout == time.Duration(0) { wg.Wait() return true // ### return, always true ### } start := time.Now() spin := NewSpinner(SpinPriorityHigh) for wg.Active() { if time.Since(start) > timeout { return false // ### return, timed out ### } spin.Yield() } return true }
go
func (wg *WaitGroup) WaitFor(timeout time.Duration) bool { if timeout == time.Duration(0) { wg.Wait() return true // ### return, always true ### } start := time.Now() spin := NewSpinner(SpinPriorityHigh) for wg.Active() { if time.Since(start) > timeout { return false // ### return, timed out ### } spin.Yield() } return true }
[ "func", "(", "wg", "*", "WaitGroup", ")", "WaitFor", "(", "timeout", "time", ".", "Duration", ")", "bool", "{", "if", "timeout", "==", "time", ".", "Duration", "(", "0", ")", "{", "wg", ".", "Wait", "(", ")", "\n", "return", "true", "// ### return, always true ###", "\n", "}", "\n\n", "start", ":=", "time", ".", "Now", "(", ")", "\n", "spin", ":=", "NewSpinner", "(", "SpinPriorityHigh", ")", "\n", "for", "wg", ".", "Active", "(", ")", "{", "if", "time", ".", "Since", "(", "start", ")", ">", "timeout", "{", "return", "false", "// ### return, timed out ###", "\n", "}", "\n", "spin", ".", "Yield", "(", ")", "\n", "}", "\n", "return", "true", "\n", "}" ]
// WaitFor blocks until the counter is 0 or less. If the block takes longer than // the given timeout, WaitFor will return false. If duration is 0, Wait is called.
[ "WaitFor", "blocks", "until", "the", "counter", "is", "0", "or", "less", ".", "If", "the", "block", "takes", "longer", "than", "the", "given", "timeout", "WaitFor", "will", "return", "false", ".", "If", "duration", "is", "0", "Wait", "is", "called", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tsync/waitgroup.go#L75-L90
12,024
trivago/tgo
tlog/logcache.go
Write
func (log *logCache) Write(message []byte) (int, error) { log.flushing.Lock() defer log.flushing.Unlock() if len(message) > 0 { messageCopy := make([]byte, len(message)) copy(messageCopy, message) log.messages = append(log.messages, messageCopy) } return len(message), nil }
go
func (log *logCache) Write(message []byte) (int, error) { log.flushing.Lock() defer log.flushing.Unlock() if len(message) > 0 { messageCopy := make([]byte, len(message)) copy(messageCopy, message) log.messages = append(log.messages, messageCopy) } return len(message), nil }
[ "func", "(", "log", "*", "logCache", ")", "Write", "(", "message", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "log", ".", "flushing", ".", "Lock", "(", ")", "\n", "defer", "log", ".", "flushing", ".", "Unlock", "(", ")", "\n\n", "if", "len", "(", "message", ")", ">", "0", "{", "messageCopy", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "message", ")", ")", "\n", "copy", "(", "messageCopy", ",", "message", ")", "\n", "log", ".", "messages", "=", "append", "(", "log", ".", "messages", ",", "messageCopy", ")", "\n", "}", "\n", "return", "len", "(", "message", ")", ",", "nil", "\n", "}" ]
// Write caches the passed message. Blocked by flush function.
[ "Write", "caches", "the", "passed", "message", ".", "Blocked", "by", "flush", "function", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tlog/logcache.go#L28-L38
12,025
trivago/tgo
tlog/logcache.go
Flush
func (log *logCache) Flush(writer io.Writer) { log.flushing.Lock() defer log.flushing.Unlock() for _, message := range log.messages { writer.Write(message) } log.messages = [][]byte{} }
go
func (log *logCache) Flush(writer io.Writer) { log.flushing.Lock() defer log.flushing.Unlock() for _, message := range log.messages { writer.Write(message) } log.messages = [][]byte{} }
[ "func", "(", "log", "*", "logCache", ")", "Flush", "(", "writer", "io", ".", "Writer", ")", "{", "log", ".", "flushing", ".", "Lock", "(", ")", "\n", "defer", "log", ".", "flushing", ".", "Unlock", "(", ")", "\n\n", "for", "_", ",", "message", ":=", "range", "log", ".", "messages", "{", "writer", ".", "Write", "(", "message", ")", "\n", "}", "\n", "log", ".", "messages", "=", "[", "]", "[", "]", "byte", "{", "}", "\n", "}" ]
// Flush writes all messages to the given writer and clears the list // of stored messages. Blocks Write function.
[ "Flush", "writes", "all", "messages", "to", "the", "given", "writer", "and", "clears", "the", "list", "of", "stored", "messages", ".", "Blocks", "Write", "function", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tlog/logcache.go#L42-L50
12,026
trivago/tgo
tcontainer/bytepool.go
Get
func (b *BytePool) Get(size int) []byte { switch { case size == 0: return []byte{} case size <= tiny: return b.tinySlab.getSlice(size) case size <= small: return b.smallSlab.getSlice(size) case size <= medium: return b.mediumSlab.getSlice(size) case size <= large: return b.largeSlab.getSlice(size) case size <= huge: return b.hugeSlab.getSlice(size) default: return make([]byte, size) } }
go
func (b *BytePool) Get(size int) []byte { switch { case size == 0: return []byte{} case size <= tiny: return b.tinySlab.getSlice(size) case size <= small: return b.smallSlab.getSlice(size) case size <= medium: return b.mediumSlab.getSlice(size) case size <= large: return b.largeSlab.getSlice(size) case size <= huge: return b.hugeSlab.getSlice(size) default: return make([]byte, size) } }
[ "func", "(", "b", "*", "BytePool", ")", "Get", "(", "size", "int", ")", "[", "]", "byte", "{", "switch", "{", "case", "size", "==", "0", ":", "return", "[", "]", "byte", "{", "}", "\n\n", "case", "size", "<=", "tiny", ":", "return", "b", ".", "tinySlab", ".", "getSlice", "(", "size", ")", "\n\n", "case", "size", "<=", "small", ":", "return", "b", ".", "smallSlab", ".", "getSlice", "(", "size", ")", "\n\n", "case", "size", "<=", "medium", ":", "return", "b", ".", "mediumSlab", ".", "getSlice", "(", "size", ")", "\n\n", "case", "size", "<=", "large", ":", "return", "b", ".", "largeSlab", ".", "getSlice", "(", "size", ")", "\n\n", "case", "size", "<=", "huge", ":", "return", "b", ".", "hugeSlab", ".", "getSlice", "(", "size", ")", "\n\n", "default", ":", "return", "make", "(", "[", "]", "byte", ",", "size", ")", "\n", "}", "\n", "}" ]
// Get returns a slice allocated to a normalized size. // Sizes are organized in evenly sized buckets so that fragmentation is kept low.
[ "Get", "returns", "a", "slice", "allocated", "to", "a", "normalized", "size", ".", "Sizes", "are", "organized", "in", "evenly", "sized", "buckets", "so", "that", "fragmentation", "is", "kept", "low", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tcontainer/bytepool.go#L134-L157
12,027
trivago/tgo
runtime.go
ReturnAfter
func ReturnAfter(runtimeLimit time.Duration, callback func()) bool { timeout := time.NewTimer(runtimeLimit) callOk := make(chan bool) go func() { callback() timeout.Stop() callOk <- true }() select { case <-timeout.C: return false case <-callOk: return true } }
go
func ReturnAfter(runtimeLimit time.Duration, callback func()) bool { timeout := time.NewTimer(runtimeLimit) callOk := make(chan bool) go func() { callback() timeout.Stop() callOk <- true }() select { case <-timeout.C: return false case <-callOk: return true } }
[ "func", "ReturnAfter", "(", "runtimeLimit", "time", ".", "Duration", ",", "callback", "func", "(", ")", ")", "bool", "{", "timeout", ":=", "time", ".", "NewTimer", "(", "runtimeLimit", ")", "\n", "callOk", ":=", "make", "(", "chan", "bool", ")", "\n\n", "go", "func", "(", ")", "{", "callback", "(", ")", "\n", "timeout", ".", "Stop", "(", ")", "\n", "callOk", "<-", "true", "\n", "}", "(", ")", "\n\n", "select", "{", "case", "<-", "timeout", ".", "C", ":", "return", "false", "\n\n", "case", "<-", "callOk", ":", "return", "true", "\n", "}", "\n", "}" ]
// ReturnAfter calls a function. If that function does not return after the // given limit, the function returns regardless of the callback being done or // not. This guarantees the call to finish before or at the given limit.
[ "ReturnAfter", "calls", "a", "function", ".", "If", "that", "function", "does", "not", "return", "after", "the", "given", "limit", "the", "function", "returns", "regardless", "of", "the", "callback", "being", "done", "or", "not", ".", "This", "guarantees", "the", "call", "to", "finish", "before", "or", "at", "the", "given", "limit", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/runtime.go#L35-L52
12,028
trivago/tgo
tos/user.go
GetUid
func GetUid(name string) (int, error) { switch name { case "nobody": return NobodyUid, nil case "root": return RootUid, nil default: userInfo, err := user.Lookup(name) if err != nil { return 0, err } return strconv.Atoi(userInfo.Uid) } }
go
func GetUid(name string) (int, error) { switch name { case "nobody": return NobodyUid, nil case "root": return RootUid, nil default: userInfo, err := user.Lookup(name) if err != nil { return 0, err } return strconv.Atoi(userInfo.Uid) } }
[ "func", "GetUid", "(", "name", "string", ")", "(", "int", ",", "error", ")", "{", "switch", "name", "{", "case", "\"", "\"", ":", "return", "NobodyUid", ",", "nil", "\n\n", "case", "\"", "\"", ":", "return", "RootUid", ",", "nil", "\n\n", "default", ":", "userInfo", ",", "err", ":=", "user", ".", "Lookup", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "return", "strconv", ".", "Atoi", "(", "userInfo", ".", "Uid", ")", "\n", "}", "\n", "}" ]
// GetUid returns the user id for a given user name
[ "GetUid", "returns", "the", "user", "id", "for", "a", "given", "user", "name" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tos/user.go#L23-L39
12,029
trivago/tgo
tos/user.go
GetGid
func GetGid(name string) (int, error) { switch name { case "nobody": return NobodyGid, nil case "root": return RootGid, nil default: groupInfo, err := user.LookupGroup(name) if err != nil { return 0, err } return strconv.Atoi(groupInfo.Gid) } }
go
func GetGid(name string) (int, error) { switch name { case "nobody": return NobodyGid, nil case "root": return RootGid, nil default: groupInfo, err := user.LookupGroup(name) if err != nil { return 0, err } return strconv.Atoi(groupInfo.Gid) } }
[ "func", "GetGid", "(", "name", "string", ")", "(", "int", ",", "error", ")", "{", "switch", "name", "{", "case", "\"", "\"", ":", "return", "NobodyGid", ",", "nil", "\n\n", "case", "\"", "\"", ":", "return", "RootGid", ",", "nil", "\n\n", "default", ":", "groupInfo", ",", "err", ":=", "user", ".", "LookupGroup", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "return", "strconv", ".", "Atoi", "(", "groupInfo", ".", "Gid", ")", "\n", "}", "\n", "}" ]
// GetGid returns the group id for a given group name
[ "GetGid", "returns", "the", "group", "id", "for", "a", "given", "group", "name" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tos/user.go#L42-L58
12,030
trivago/tgo
tsync/fuse.go
NewFuse
func NewFuse() *Fuse { return &Fuse{ signal: sync.NewCond(new(sync.Mutex)), burned: new(int32), } }
go
func NewFuse() *Fuse { return &Fuse{ signal: sync.NewCond(new(sync.Mutex)), burned: new(int32), } }
[ "func", "NewFuse", "(", ")", "*", "Fuse", "{", "return", "&", "Fuse", "{", "signal", ":", "sync", ".", "NewCond", "(", "new", "(", "sync", ".", "Mutex", ")", ")", ",", "burned", ":", "new", "(", "int32", ")", ",", "}", "\n", "}" ]
// NewFuse creates a new Fuse and returns it. // A new fuse is always active.
[ "NewFuse", "creates", "a", "new", "Fuse", "and", "returns", "it", ".", "A", "new", "fuse", "is", "always", "active", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tsync/fuse.go#L34-L39
12,031
trivago/tgo
tsync/fuse.go
Wait
func (fuse Fuse) Wait() { fuse.signal.L.Lock() defer fuse.signal.L.Unlock() if fuse.IsBurned() { fuse.signal.Wait() } }
go
func (fuse Fuse) Wait() { fuse.signal.L.Lock() defer fuse.signal.L.Unlock() if fuse.IsBurned() { fuse.signal.Wait() } }
[ "func", "(", "fuse", "Fuse", ")", "Wait", "(", ")", "{", "fuse", ".", "signal", ".", "L", ".", "Lock", "(", ")", "\n", "defer", "fuse", ".", "signal", ".", "L", ".", "Unlock", "(", ")", "\n", "if", "fuse", ".", "IsBurned", "(", ")", "{", "fuse", ".", "signal", ".", "Wait", "(", ")", "\n", "}", "\n", "}" ]
// Wait blocks until the fuse enters active state. // Multiple go routines may wait on the same fuse.
[ "Wait", "blocks", "until", "the", "fuse", "enters", "active", "state", ".", "Multiple", "go", "routines", "may", "wait", "on", "the", "same", "fuse", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tsync/fuse.go#L62-L68
12,032
trivago/tgo
tmath/math.go
Max3I
func Max3I(a, b, c int) int { max := a if b > max { max = b } if c > max { max = c } return max }
go
func Max3I(a, b, c int) int { max := a if b > max { max = b } if c > max { max = c } return max }
[ "func", "Max3I", "(", "a", ",", "b", ",", "c", "int", ")", "int", "{", "max", ":=", "a", "\n", "if", "b", ">", "max", "{", "max", "=", "b", "\n", "}", "\n", "if", "c", ">", "max", "{", "max", "=", "c", "\n", "}", "\n", "return", "max", "\n", "}" ]
// Max3I returns the maximum out of three integers
[ "Max3I", "returns", "the", "maximum", "out", "of", "three", "integers" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tmath/math.go#L42-L51
12,033
trivago/tgo
tmath/math.go
Max3Int64
func Max3Int64(a, b, c int64) int64 { max := a if b > max { max = b } if c > max { max = c } return max }
go
func Max3Int64(a, b, c int64) int64 { max := a if b > max { max = b } if c > max { max = c } return max }
[ "func", "Max3Int64", "(", "a", ",", "b", ",", "c", "int64", ")", "int64", "{", "max", ":=", "a", "\n", "if", "b", ">", "max", "{", "max", "=", "b", "\n", "}", "\n", "if", "c", ">", "max", "{", "max", "=", "c", "\n", "}", "\n", "return", "max", "\n", "}" ]
// Max3Int64 returns the maximum out of three signed 64-bit integers
[ "Max3Int64", "returns", "the", "maximum", "out", "of", "three", "signed", "64", "-", "bit", "integers" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tmath/math.go#L54-L63
12,034
trivago/tgo
tmath/math.go
Max3Uint64
func Max3Uint64(a, b, c uint64) uint64 { max := a if b > max { max = b } if c > max { max = c } return max }
go
func Max3Uint64(a, b, c uint64) uint64 { max := a if b > max { max = b } if c > max { max = c } return max }
[ "func", "Max3Uint64", "(", "a", ",", "b", ",", "c", "uint64", ")", "uint64", "{", "max", ":=", "a", "\n", "if", "b", ">", "max", "{", "max", "=", "b", "\n", "}", "\n", "if", "c", ">", "max", "{", "max", "=", "c", "\n", "}", "\n", "return", "max", "\n", "}" ]
// Max3Uint64 returns the maximum out of three unsigned 64-bit integers
[ "Max3Uint64", "returns", "the", "maximum", "out", "of", "three", "unsigned", "64", "-", "bit", "integers" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tmath/math.go#L66-L75
12,035
trivago/tgo
tmath/math.go
Min3I
func Min3I(a, b, c int) int { min := a if b < min { min = b } if c < min { min = c } return min }
go
func Min3I(a, b, c int) int { min := a if b < min { min = b } if c < min { min = c } return min }
[ "func", "Min3I", "(", "a", ",", "b", ",", "c", "int", ")", "int", "{", "min", ":=", "a", "\n", "if", "b", "<", "min", "{", "min", "=", "b", "\n", "}", "\n", "if", "c", "<", "min", "{", "min", "=", "c", "\n", "}", "\n", "return", "min", "\n", "}" ]
// Min3I returns the minimum out of three integers
[ "Min3I", "returns", "the", "minimum", "out", "of", "three", "integers" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tmath/math.go#L102-L111
12,036
trivago/tgo
tmath/math.go
Min3Int64
func Min3Int64(a, b, c int64) int64 { min := a if b < min { min = b } if c < min { min = c } return min }
go
func Min3Int64(a, b, c int64) int64 { min := a if b < min { min = b } if c < min { min = c } return min }
[ "func", "Min3Int64", "(", "a", ",", "b", ",", "c", "int64", ")", "int64", "{", "min", ":=", "a", "\n", "if", "b", "<", "min", "{", "min", "=", "b", "\n", "}", "\n", "if", "c", "<", "min", "{", "min", "=", "c", "\n", "}", "\n", "return", "min", "\n", "}" ]
// Min3Int64 returns the minimum out of three signed 64-bit integers
[ "Min3Int64", "returns", "the", "minimum", "out", "of", "three", "signed", "64", "-", "bit", "integers" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tmath/math.go#L114-L123
12,037
trivago/tgo
tmath/math.go
Min3Uint64
func Min3Uint64(a, b, c uint64) uint64 { min := a if b < min { min = b } if c < min { min = c } return min }
go
func Min3Uint64(a, b, c uint64) uint64 { min := a if b < min { min = b } if c < min { min = c } return min }
[ "func", "Min3Uint64", "(", "a", ",", "b", ",", "c", "uint64", ")", "uint64", "{", "min", ":=", "a", "\n", "if", "b", "<", "min", "{", "min", "=", "b", "\n", "}", "\n", "if", "c", "<", "min", "{", "min", "=", "c", "\n", "}", "\n", "return", "min", "\n", "}" ]
// Min3Uint64 returns the minimum out of three unsigned 64-bit integers
[ "Min3Uint64", "returns", "the", "minimum", "out", "of", "three", "unsigned", "64", "-", "bit", "integers" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tmath/math.go#L126-L135
12,038
trivago/tgo
tcontainer/marshalmap.go
TryConvertToMarshalMap
func TryConvertToMarshalMap(value interface{}, formatKey func(string) string) interface{} { valueMeta := reflect.ValueOf(value) switch valueMeta.Kind() { default: return value case reflect.Array, reflect.Slice: arrayLen := valueMeta.Len() converted := make([]interface{}, arrayLen) for i := 0; i < arrayLen; i++ { converted[i] = TryConvertToMarshalMap(valueMeta.Index(i).Interface(), formatKey) } return converted case reflect.Map: converted := NewMarshalMap() keys := valueMeta.MapKeys() for _, keyMeta := range keys { strKey, isString := keyMeta.Interface().(string) if !isString { continue } if formatKey != nil { strKey = formatKey(strKey) } val := valueMeta.MapIndex(keyMeta).Interface() converted[strKey] = TryConvertToMarshalMap(val, formatKey) } return converted // ### return, converted MarshalMap ### } }
go
func TryConvertToMarshalMap(value interface{}, formatKey func(string) string) interface{} { valueMeta := reflect.ValueOf(value) switch valueMeta.Kind() { default: return value case reflect.Array, reflect.Slice: arrayLen := valueMeta.Len() converted := make([]interface{}, arrayLen) for i := 0; i < arrayLen; i++ { converted[i] = TryConvertToMarshalMap(valueMeta.Index(i).Interface(), formatKey) } return converted case reflect.Map: converted := NewMarshalMap() keys := valueMeta.MapKeys() for _, keyMeta := range keys { strKey, isString := keyMeta.Interface().(string) if !isString { continue } if formatKey != nil { strKey = formatKey(strKey) } val := valueMeta.MapIndex(keyMeta).Interface() converted[strKey] = TryConvertToMarshalMap(val, formatKey) } return converted // ### return, converted MarshalMap ### } }
[ "func", "TryConvertToMarshalMap", "(", "value", "interface", "{", "}", ",", "formatKey", "func", "(", "string", ")", "string", ")", "interface", "{", "}", "{", "valueMeta", ":=", "reflect", ".", "ValueOf", "(", "value", ")", "\n", "switch", "valueMeta", ".", "Kind", "(", ")", "{", "default", ":", "return", "value", "\n\n", "case", "reflect", ".", "Array", ",", "reflect", ".", "Slice", ":", "arrayLen", ":=", "valueMeta", ".", "Len", "(", ")", "\n", "converted", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "arrayLen", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "arrayLen", ";", "i", "++", "{", "converted", "[", "i", "]", "=", "TryConvertToMarshalMap", "(", "valueMeta", ".", "Index", "(", "i", ")", ".", "Interface", "(", ")", ",", "formatKey", ")", "\n", "}", "\n", "return", "converted", "\n\n", "case", "reflect", ".", "Map", ":", "converted", ":=", "NewMarshalMap", "(", ")", "\n", "keys", ":=", "valueMeta", ".", "MapKeys", "(", ")", "\n\n", "for", "_", ",", "keyMeta", ":=", "range", "keys", "{", "strKey", ",", "isString", ":=", "keyMeta", ".", "Interface", "(", ")", ".", "(", "string", ")", "\n", "if", "!", "isString", "{", "continue", "\n", "}", "\n", "if", "formatKey", "!=", "nil", "{", "strKey", "=", "formatKey", "(", "strKey", ")", "\n", "}", "\n", "val", ":=", "valueMeta", ".", "MapIndex", "(", "keyMeta", ")", ".", "Interface", "(", ")", "\n", "converted", "[", "strKey", "]", "=", "TryConvertToMarshalMap", "(", "val", ",", "formatKey", ")", "\n", "}", "\n", "return", "converted", "// ### return, converted MarshalMap ###", "\n", "}", "\n", "}" ]
// TryConvertToMarshalMap converts collections to MarshalMap if possible. // This is a deep conversion, i.e. each element in the collection will be // traversed. You can pass a formatKey function that will be applied to all // string keys that are detected.
[ "TryConvertToMarshalMap", "converts", "collections", "to", "MarshalMap", "if", "possible", ".", "This", "is", "a", "deep", "conversion", "i", ".", "e", ".", "each", "element", "in", "the", "collection", "will", "be", "traversed", ".", "You", "can", "pass", "a", "formatKey", "function", "that", "will", "be", "applied", "to", "all", "string", "keys", "that", "are", "detected", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tcontainer/marshalmap.go#L52-L83
12,039
trivago/tgo
tcontainer/marshalmap.go
Clone
func (mmap MarshalMap) Clone() MarshalMap { clone := cloneMap(reflect.ValueOf(mmap)) return clone.Interface().(MarshalMap) }
go
func (mmap MarshalMap) Clone() MarshalMap { clone := cloneMap(reflect.ValueOf(mmap)) return clone.Interface().(MarshalMap) }
[ "func", "(", "mmap", "MarshalMap", ")", "Clone", "(", ")", "MarshalMap", "{", "clone", ":=", "cloneMap", "(", "reflect", ".", "ValueOf", "(", "mmap", ")", ")", "\n", "return", "clone", ".", "Interface", "(", ")", ".", "(", "MarshalMap", ")", "\n", "}" ]
// Clone creates a copy of the given MarshalMap.
[ "Clone", "creates", "a", "copy", "of", "the", "given", "MarshalMap", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tcontainer/marshalmap.go#L97-L100
12,040
trivago/tgo
tcontainer/marshalmap.go
Bool
func (mmap MarshalMap) Bool(key string) (bool, error) { val, exists := mmap.Value(key) if !exists { return false, fmt.Errorf(`"%s" is not set`, key) } boolValue, isBool := val.(bool) if !isBool { return false, fmt.Errorf(`"%s" is expected to be a boolean`, key) } return boolValue, nil }
go
func (mmap MarshalMap) Bool(key string) (bool, error) { val, exists := mmap.Value(key) if !exists { return false, fmt.Errorf(`"%s" is not set`, key) } boolValue, isBool := val.(bool) if !isBool { return false, fmt.Errorf(`"%s" is expected to be a boolean`, key) } return boolValue, nil }
[ "func", "(", "mmap", "MarshalMap", ")", "Bool", "(", "key", "string", ")", "(", "bool", ",", "error", ")", "{", "val", ",", "exists", ":=", "mmap", ".", "Value", "(", "key", ")", "\n", "if", "!", "exists", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "`\"%s\" is not set`", ",", "key", ")", "\n", "}", "\n\n", "boolValue", ",", "isBool", ":=", "val", ".", "(", "bool", ")", "\n", "if", "!", "isBool", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "`\"%s\" is expected to be a boolean`", ",", "key", ")", "\n", "}", "\n", "return", "boolValue", ",", "nil", "\n", "}" ]
// Bool returns a value at key that is expected to be a boolean
[ "Bool", "returns", "a", "value", "at", "key", "that", "is", "expected", "to", "be", "a", "boolean" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tcontainer/marshalmap.go#L135-L146
12,041
trivago/tgo
tcontainer/marshalmap.go
Uint
func (mmap MarshalMap) Uint(key string) (uint64, error) { val, exists := mmap.Value(key) if !exists { return 0, fmt.Errorf(`"%s" is not set`, key) } if intVal, isNumber := treflect.Uint64(val); isNumber { return intVal, nil } return 0, fmt.Errorf(`"%s" is expected to be an unsigned number type`, key) }
go
func (mmap MarshalMap) Uint(key string) (uint64, error) { val, exists := mmap.Value(key) if !exists { return 0, fmt.Errorf(`"%s" is not set`, key) } if intVal, isNumber := treflect.Uint64(val); isNumber { return intVal, nil } return 0, fmt.Errorf(`"%s" is expected to be an unsigned number type`, key) }
[ "func", "(", "mmap", "MarshalMap", ")", "Uint", "(", "key", "string", ")", "(", "uint64", ",", "error", ")", "{", "val", ",", "exists", ":=", "mmap", ".", "Value", "(", "key", ")", "\n", "if", "!", "exists", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "`\"%s\" is not set`", ",", "key", ")", "\n", "}", "\n\n", "if", "intVal", ",", "isNumber", ":=", "treflect", ".", "Uint64", "(", "val", ")", ";", "isNumber", "{", "return", "intVal", ",", "nil", "\n", "}", "\n\n", "return", "0", ",", "fmt", ".", "Errorf", "(", "`\"%s\" is expected to be an unsigned number type`", ",", "key", ")", "\n", "}" ]
// Uint returns a value at key that is expected to be an uint64 or compatible // integer value.
[ "Uint", "returns", "a", "value", "at", "key", "that", "is", "expected", "to", "be", "an", "uint64", "or", "compatible", "integer", "value", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tcontainer/marshalmap.go#L150-L161
12,042
trivago/tgo
tcontainer/marshalmap.go
Int
func (mmap MarshalMap) Int(key string) (int64, error) { val, exists := mmap.Value(key) if !exists { return 0, fmt.Errorf(`"%s" is not set`, key) } if intVal, isNumber := treflect.Int64(val); isNumber { return intVal, nil } return 0, fmt.Errorf(`"%s" is expected to be a signed number type`, key) }
go
func (mmap MarshalMap) Int(key string) (int64, error) { val, exists := mmap.Value(key) if !exists { return 0, fmt.Errorf(`"%s" is not set`, key) } if intVal, isNumber := treflect.Int64(val); isNumber { return intVal, nil } return 0, fmt.Errorf(`"%s" is expected to be a signed number type`, key) }
[ "func", "(", "mmap", "MarshalMap", ")", "Int", "(", "key", "string", ")", "(", "int64", ",", "error", ")", "{", "val", ",", "exists", ":=", "mmap", ".", "Value", "(", "key", ")", "\n", "if", "!", "exists", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "`\"%s\" is not set`", ",", "key", ")", "\n", "}", "\n\n", "if", "intVal", ",", "isNumber", ":=", "treflect", ".", "Int64", "(", "val", ")", ";", "isNumber", "{", "return", "intVal", ",", "nil", "\n", "}", "\n\n", "return", "0", ",", "fmt", ".", "Errorf", "(", "`\"%s\" is expected to be a signed number type`", ",", "key", ")", "\n", "}" ]
// Int returns a value at key that is expected to be an int64 or compatible // integer value.
[ "Int", "returns", "a", "value", "at", "key", "that", "is", "expected", "to", "be", "an", "int64", "or", "compatible", "integer", "value", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tcontainer/marshalmap.go#L165-L176
12,043
trivago/tgo
tcontainer/marshalmap.go
Float
func (mmap MarshalMap) Float(key string) (float64, error) { val, exists := mmap.Value(key) if !exists { return 0, fmt.Errorf(`"%s" is not set`, key) } if floatVal, isNumber := treflect.Float64(val); isNumber { return floatVal, nil } return 0, fmt.Errorf(`"%s" is expected to be a signed number type`, key) }
go
func (mmap MarshalMap) Float(key string) (float64, error) { val, exists := mmap.Value(key) if !exists { return 0, fmt.Errorf(`"%s" is not set`, key) } if floatVal, isNumber := treflect.Float64(val); isNumber { return floatVal, nil } return 0, fmt.Errorf(`"%s" is expected to be a signed number type`, key) }
[ "func", "(", "mmap", "MarshalMap", ")", "Float", "(", "key", "string", ")", "(", "float64", ",", "error", ")", "{", "val", ",", "exists", ":=", "mmap", ".", "Value", "(", "key", ")", "\n", "if", "!", "exists", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "`\"%s\" is not set`", ",", "key", ")", "\n", "}", "\n\n", "if", "floatVal", ",", "isNumber", ":=", "treflect", ".", "Float64", "(", "val", ")", ";", "isNumber", "{", "return", "floatVal", ",", "nil", "\n", "}", "\n\n", "return", "0", ",", "fmt", ".", "Errorf", "(", "`\"%s\" is expected to be a signed number type`", ",", "key", ")", "\n", "}" ]
// Float returns a value at key that is expected to be a float64 or compatible // float value.
[ "Float", "returns", "a", "value", "at", "key", "that", "is", "expected", "to", "be", "a", "float64", "or", "compatible", "float", "value", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tcontainer/marshalmap.go#L180-L191
12,044
trivago/tgo
tcontainer/marshalmap.go
Duration
func (mmap MarshalMap) Duration(key string) (time.Duration, error) { val, exists := mmap.Value(key) if !exists { return time.Duration(0), fmt.Errorf(`"%s" is not set`, key) } switch val.(type) { case time.Duration: return val.(time.Duration), nil case string: return time.ParseDuration(val.(string)) } return time.Duration(0), fmt.Errorf(`"%s" is expected to be a duration or string`, key) }
go
func (mmap MarshalMap) Duration(key string) (time.Duration, error) { val, exists := mmap.Value(key) if !exists { return time.Duration(0), fmt.Errorf(`"%s" is not set`, key) } switch val.(type) { case time.Duration: return val.(time.Duration), nil case string: return time.ParseDuration(val.(string)) } return time.Duration(0), fmt.Errorf(`"%s" is expected to be a duration or string`, key) }
[ "func", "(", "mmap", "MarshalMap", ")", "Duration", "(", "key", "string", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "val", ",", "exists", ":=", "mmap", ".", "Value", "(", "key", ")", "\n", "if", "!", "exists", "{", "return", "time", ".", "Duration", "(", "0", ")", ",", "fmt", ".", "Errorf", "(", "`\"%s\" is not set`", ",", "key", ")", "\n", "}", "\n\n", "switch", "val", ".", "(", "type", ")", "{", "case", "time", ".", "Duration", ":", "return", "val", ".", "(", "time", ".", "Duration", ")", ",", "nil", "\n", "case", "string", ":", "return", "time", ".", "ParseDuration", "(", "val", ".", "(", "string", ")", ")", "\n", "}", "\n\n", "return", "time", ".", "Duration", "(", "0", ")", ",", "fmt", ".", "Errorf", "(", "`\"%s\" is expected to be a duration or string`", ",", "key", ")", "\n", "}" ]
// Duration returns a value at key that is expected to be a string
[ "Duration", "returns", "a", "value", "at", "key", "that", "is", "expected", "to", "be", "a", "string" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tcontainer/marshalmap.go#L194-L208
12,045
trivago/tgo
tcontainer/marshalmap.go
String
func (mmap MarshalMap) String(key string) (string, error) { val, exists := mmap.Value(key) if !exists { return "", fmt.Errorf(`"%s" is not set`, key) } strValue, isString := val.(string) if !isString { return "", fmt.Errorf(`"%s" is expected to be a string`, key) } return strValue, nil }
go
func (mmap MarshalMap) String(key string) (string, error) { val, exists := mmap.Value(key) if !exists { return "", fmt.Errorf(`"%s" is not set`, key) } strValue, isString := val.(string) if !isString { return "", fmt.Errorf(`"%s" is expected to be a string`, key) } return strValue, nil }
[ "func", "(", "mmap", "MarshalMap", ")", "String", "(", "key", "string", ")", "(", "string", ",", "error", ")", "{", "val", ",", "exists", ":=", "mmap", ".", "Value", "(", "key", ")", "\n", "if", "!", "exists", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "`\"%s\" is not set`", ",", "key", ")", "\n", "}", "\n\n", "strValue", ",", "isString", ":=", "val", ".", "(", "string", ")", "\n", "if", "!", "isString", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "`\"%s\" is expected to be a string`", ",", "key", ")", "\n", "}", "\n", "return", "strValue", ",", "nil", "\n", "}" ]
// String returns a value at key that is expected to be a string
[ "String", "returns", "a", "value", "at", "key", "that", "is", "expected", "to", "be", "a", "string" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tcontainer/marshalmap.go#L211-L222
12,046
trivago/tgo
tcontainer/marshalmap.go
StringSlice
func (mmap MarshalMap) StringSlice(key string) ([]string, error) { return mmap.StringArray(key) }
go
func (mmap MarshalMap) StringSlice(key string) ([]string, error) { return mmap.StringArray(key) }
[ "func", "(", "mmap", "MarshalMap", ")", "StringSlice", "(", "key", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "return", "mmap", ".", "StringArray", "(", "key", ")", "\n", "}" ]
// StringSlice is an alias for StringArray
[ "StringSlice", "is", "an", "alias", "for", "StringArray" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tcontainer/marshalmap.go#L299-L301
12,047
trivago/tgo
tcontainer/marshalmap.go
Int64Slice
func (mmap MarshalMap) Int64Slice(key string) ([]int64, error) { return mmap.Int64Array(key) }
go
func (mmap MarshalMap) Int64Slice(key string) ([]int64, error) { return mmap.Int64Array(key) }
[ "func", "(", "mmap", "MarshalMap", ")", "Int64Slice", "(", "key", "string", ")", "(", "[", "]", "int64", ",", "error", ")", "{", "return", "mmap", ".", "Int64Array", "(", "key", ")", "\n", "}" ]
// Int64Slice is an alias for Int64Array
[ "Int64Slice", "is", "an", "alias", "for", "Int64Array" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tcontainer/marshalmap.go#L342-L344
12,048
trivago/tgo
tcontainer/marshalmap.go
StringSliceMap
func (mmap MarshalMap) StringSliceMap(key string) (map[string][]string, error) { return mmap.StringArrayMap(key) }
go
func (mmap MarshalMap) StringSliceMap(key string) (map[string][]string, error) { return mmap.StringArrayMap(key) }
[ "func", "(", "mmap", "MarshalMap", ")", "StringSliceMap", "(", "key", "string", ")", "(", "map", "[", "string", "]", "[", "]", "string", ",", "error", ")", "{", "return", "mmap", ".", "StringArrayMap", "(", "key", ")", "\n", "}" ]
// StringSliceMap is an alias for StringArrayMap
[ "StringSliceMap", "is", "an", "alias", "for", "StringArrayMap" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tcontainer/marshalmap.go#L399-L401
12,049
trivago/tgo
tcontainer/marshalmap.go
Delete
func (mmap MarshalMap) Delete(key string) { mmap.resolvePath(key, mmap, func(p, k reflect.Value, v interface{}) { if v != nil { p.SetMapIndex(k, reflect.Value{}) } }) }
go
func (mmap MarshalMap) Delete(key string) { mmap.resolvePath(key, mmap, func(p, k reflect.Value, v interface{}) { if v != nil { p.SetMapIndex(k, reflect.Value{}) } }) }
[ "func", "(", "mmap", "MarshalMap", ")", "Delete", "(", "key", "string", ")", "{", "mmap", ".", "resolvePath", "(", "key", ",", "mmap", ",", "func", "(", "p", ",", "k", "reflect", ".", "Value", ",", "v", "interface", "{", "}", ")", "{", "if", "v", "!=", "nil", "{", "p", ".", "SetMapIndex", "(", "k", ",", "reflect", ".", "Value", "{", "}", ")", "\n", "}", "\n", "}", ")", "\n", "}" ]
// Delete a value from a given path. // The path must point to a map key. Deleting from arrays is not supported.
[ "Delete", "a", "value", "from", "a", "given", "path", ".", "The", "path", "must", "point", "to", "a", "map", "key", ".", "Deleting", "from", "arrays", "is", "not", "supported", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tcontainer/marshalmap.go#L474-L480
12,050
trivago/tgo
tcontainer/marshalmap.go
Set
func (mmap MarshalMap) Set(key string, val interface{}) { mmap.resolvePath(key, mmap, func(p, k reflect.Value, v interface{}) { p.SetMapIndex(k, reflect.ValueOf(val)) }) }
go
func (mmap MarshalMap) Set(key string, val interface{}) { mmap.resolvePath(key, mmap, func(p, k reflect.Value, v interface{}) { p.SetMapIndex(k, reflect.ValueOf(val)) }) }
[ "func", "(", "mmap", "MarshalMap", ")", "Set", "(", "key", "string", ",", "val", "interface", "{", "}", ")", "{", "mmap", ".", "resolvePath", "(", "key", ",", "mmap", ",", "func", "(", "p", ",", "k", "reflect", ".", "Value", ",", "v", "interface", "{", "}", ")", "{", "p", ".", "SetMapIndex", "(", "k", ",", "reflect", ".", "ValueOf", "(", "val", ")", ")", "\n", "}", ")", "\n", "}" ]
// Set a value for a given path. // The path must point to a map key. Setting array elements is not supported.
[ "Set", "a", "value", "for", "a", "given", "path", ".", "The", "path", "must", "point", "to", "a", "map", "key", ".", "Setting", "array", "elements", "is", "not", "supported", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tcontainer/marshalmap.go#L484-L488
12,051
trivago/tgo
treflect/clone.go
Clone
func Clone(v interface{}) interface{} { value := reflect.ValueOf(v) copy := clone(value) return copy.Interface() }
go
func Clone(v interface{}) interface{} { value := reflect.ValueOf(v) copy := clone(value) return copy.Interface() }
[ "func", "Clone", "(", "v", "interface", "{", "}", ")", "interface", "{", "}", "{", "value", ":=", "reflect", ".", "ValueOf", "(", "v", ")", "\n", "copy", ":=", "clone", "(", "value", ")", "\n", "return", "copy", ".", "Interface", "(", ")", "\n", "}" ]
// Clone does a deep copy of the given value. // Please note that field have to be public in order to be copied. // Private fields will be ignored.
[ "Clone", "does", "a", "deep", "copy", "of", "the", "given", "value", ".", "Please", "note", "that", "field", "have", "to", "be", "public", "in", "order", "to", "be", "copied", ".", "Private", "fields", "will", "be", "ignored", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/treflect/clone.go#L24-L28
12,052
trivago/tgo
tflag/flag.go
SwitchVar
func SwitchVar(flagVar *bool, short string, long string, usage string) *bool { return BoolVar(flagVar, short, long, false, usage) }
go
func SwitchVar(flagVar *bool, short string, long string, usage string) *bool { return BoolVar(flagVar, short, long, false, usage) }
[ "func", "SwitchVar", "(", "flagVar", "*", "bool", ",", "short", "string", ",", "long", "string", ",", "usage", "string", ")", "*", "bool", "{", "return", "BoolVar", "(", "flagVar", ",", "short", ",", "long", ",", "false", ",", "usage", ")", "\n", "}" ]
// SwitchVar adds a boolean flag that is meant to be used without value. If it // is given the value is true, otherwise false.
[ "SwitchVar", "adds", "a", "boolean", "flag", "that", "is", "meant", "to", "be", "used", "without", "value", ".", "If", "it", "is", "given", "the", "value", "is", "true", "otherwise", "false", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tflag/flag.go#L63-L65
12,053
trivago/tgo
tflag/flag.go
BoolVar
func BoolVar(flagVar *bool, short string, long string, value bool, usage string) *bool { flag.BoolVar(flagVar, short, value, usage) flag.BoolVar(flagVar, long, value, usage) addKeyDescription(short, long, value, usage) return flagVar }
go
func BoolVar(flagVar *bool, short string, long string, value bool, usage string) *bool { flag.BoolVar(flagVar, short, value, usage) flag.BoolVar(flagVar, long, value, usage) addKeyDescription(short, long, value, usage) return flagVar }
[ "func", "BoolVar", "(", "flagVar", "*", "bool", ",", "short", "string", ",", "long", "string", ",", "value", "bool", ",", "usage", "string", ")", "*", "bool", "{", "flag", ".", "BoolVar", "(", "flagVar", ",", "short", ",", "value", ",", "usage", ")", "\n", "flag", ".", "BoolVar", "(", "flagVar", ",", "long", ",", "value", ",", "usage", ")", "\n", "addKeyDescription", "(", "short", ",", "long", ",", "value", ",", "usage", ")", "\n", "return", "flagVar", "\n", "}" ]
// BoolVar adds a boolean flag to the parameters list. This is using the golang // flag package internally.
[ "BoolVar", "adds", "a", "boolean", "flag", "to", "the", "parameters", "list", ".", "This", "is", "using", "the", "golang", "flag", "package", "internally", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tflag/flag.go#L69-L74
12,054
trivago/tgo
tflag/flag.go
IntVar
func IntVar(flagVar *int, short string, long string, value int, usage string) *int { flag.IntVar(flagVar, short, value, usage) flag.IntVar(flagVar, long, value, usage) addKeyDescription(short, long, value, usage) return flagVar }
go
func IntVar(flagVar *int, short string, long string, value int, usage string) *int { flag.IntVar(flagVar, short, value, usage) flag.IntVar(flagVar, long, value, usage) addKeyDescription(short, long, value, usage) return flagVar }
[ "func", "IntVar", "(", "flagVar", "*", "int", ",", "short", "string", ",", "long", "string", ",", "value", "int", ",", "usage", "string", ")", "*", "int", "{", "flag", ".", "IntVar", "(", "flagVar", ",", "short", ",", "value", ",", "usage", ")", "\n", "flag", ".", "IntVar", "(", "flagVar", ",", "long", ",", "value", ",", "usage", ")", "\n", "addKeyDescription", "(", "short", ",", "long", ",", "value", ",", "usage", ")", "\n", "return", "flagVar", "\n", "}" ]
// IntVar adds an integer flag to the parameters list. This is using the golang // flag package internally.
[ "IntVar", "adds", "an", "integer", "flag", "to", "the", "parameters", "list", ".", "This", "is", "using", "the", "golang", "flag", "package", "internally", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tflag/flag.go#L78-L83
12,055
trivago/tgo
tflag/flag.go
Int64Var
func Int64Var(flagVar *int64, short string, long string, value int64, usage string) *int64 { flag.Int64Var(flagVar, short, value, usage) flag.Int64Var(flagVar, long, value, usage) addKeyDescription(short, long, value, usage) return flagVar }
go
func Int64Var(flagVar *int64, short string, long string, value int64, usage string) *int64 { flag.Int64Var(flagVar, short, value, usage) flag.Int64Var(flagVar, long, value, usage) addKeyDescription(short, long, value, usage) return flagVar }
[ "func", "Int64Var", "(", "flagVar", "*", "int64", ",", "short", "string", ",", "long", "string", ",", "value", "int64", ",", "usage", "string", ")", "*", "int64", "{", "flag", ".", "Int64Var", "(", "flagVar", ",", "short", ",", "value", ",", "usage", ")", "\n", "flag", ".", "Int64Var", "(", "flagVar", ",", "long", ",", "value", ",", "usage", ")", "\n", "addKeyDescription", "(", "short", ",", "long", ",", "value", ",", "usage", ")", "\n", "return", "flagVar", "\n", "}" ]
// Int64Var adds am int64 flag to the parameters list. This is using the golang // flag package internally.
[ "Int64Var", "adds", "am", "int64", "flag", "to", "the", "parameters", "list", ".", "This", "is", "using", "the", "golang", "flag", "package", "internally", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tflag/flag.go#L87-L92
12,056
trivago/tgo
tflag/flag.go
Float64Var
func Float64Var(flagVar *float64, short string, long string, value float64, usage string) *float64 { flag.Float64Var(flagVar, short, value, usage) flag.Float64Var(flagVar, long, value, usage) addKeyDescription(short, long, value, usage) return flagVar }
go
func Float64Var(flagVar *float64, short string, long string, value float64, usage string) *float64 { flag.Float64Var(flagVar, short, value, usage) flag.Float64Var(flagVar, long, value, usage) addKeyDescription(short, long, value, usage) return flagVar }
[ "func", "Float64Var", "(", "flagVar", "*", "float64", ",", "short", "string", ",", "long", "string", ",", "value", "float64", ",", "usage", "string", ")", "*", "float64", "{", "flag", ".", "Float64Var", "(", "flagVar", ",", "short", ",", "value", ",", "usage", ")", "\n", "flag", ".", "Float64Var", "(", "flagVar", ",", "long", ",", "value", ",", "usage", ")", "\n", "addKeyDescription", "(", "short", ",", "long", ",", "value", ",", "usage", ")", "\n", "return", "flagVar", "\n", "}" ]
// Float64Var adds a float flag to the parameters list. This is using the golang // flag package internally.
[ "Float64Var", "adds", "a", "float", "flag", "to", "the", "parameters", "list", ".", "This", "is", "using", "the", "golang", "flag", "package", "internally", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tflag/flag.go#L96-L101
12,057
trivago/tgo
tflag/flag.go
StringVar
func StringVar(flagVar *string, short string, long string, value string, usage string) *string { flag.StringVar(flagVar, short, value, usage) flag.StringVar(flagVar, long, value, usage) addKeyDescription(short, long, value, usage) return flagVar }
go
func StringVar(flagVar *string, short string, long string, value string, usage string) *string { flag.StringVar(flagVar, short, value, usage) flag.StringVar(flagVar, long, value, usage) addKeyDescription(short, long, value, usage) return flagVar }
[ "func", "StringVar", "(", "flagVar", "*", "string", ",", "short", "string", ",", "long", "string", ",", "value", "string", ",", "usage", "string", ")", "*", "string", "{", "flag", ".", "StringVar", "(", "flagVar", ",", "short", ",", "value", ",", "usage", ")", "\n", "flag", ".", "StringVar", "(", "flagVar", ",", "long", ",", "value", ",", "usage", ")", "\n", "addKeyDescription", "(", "short", ",", "long", ",", "value", ",", "usage", ")", "\n", "return", "flagVar", "\n", "}" ]
// StringVar adds a string flag to the parameters list. This is using the golang // flag package internally.
[ "StringVar", "adds", "a", "string", "flag", "to", "the", "parameters", "list", ".", "This", "is", "using", "the", "golang", "flag", "package", "internally", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tflag/flag.go#L105-L110
12,058
trivago/tgo
tflag/flag.go
Switch
func Switch(short string, long string, usage string) *bool { var flagVar bool return SwitchVar(&flagVar, short, long, usage) }
go
func Switch(short string, long string, usage string) *bool { var flagVar bool return SwitchVar(&flagVar, short, long, usage) }
[ "func", "Switch", "(", "short", "string", ",", "long", "string", ",", "usage", "string", ")", "*", "bool", "{", "var", "flagVar", "bool", "\n", "return", "SwitchVar", "(", "&", "flagVar", ",", "short", ",", "long", ",", "usage", ")", "\n", "}" ]
// Switch is a convenience wrapper for SwitchVar
[ "Switch", "is", "a", "convenience", "wrapper", "for", "SwitchVar" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tflag/flag.go#L113-L116
12,059
trivago/tgo
tflag/flag.go
Bool
func Bool(short string, long string, value bool, usage string) *bool { flagVar := value return BoolVar(&flagVar, short, long, value, usage) }
go
func Bool(short string, long string, value bool, usage string) *bool { flagVar := value return BoolVar(&flagVar, short, long, value, usage) }
[ "func", "Bool", "(", "short", "string", ",", "long", "string", ",", "value", "bool", ",", "usage", "string", ")", "*", "bool", "{", "flagVar", ":=", "value", "\n", "return", "BoolVar", "(", "&", "flagVar", ",", "short", ",", "long", ",", "value", ",", "usage", ")", "\n", "}" ]
// Bool is a convenience wrapper for BoolVar
[ "Bool", "is", "a", "convenience", "wrapper", "for", "BoolVar" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tflag/flag.go#L119-L122
12,060
trivago/tgo
tflag/flag.go
Int
func Int(short string, long string, value int, usage string) *int { flagVar := value return IntVar(&flagVar, short, long, value, usage) }
go
func Int(short string, long string, value int, usage string) *int { flagVar := value return IntVar(&flagVar, short, long, value, usage) }
[ "func", "Int", "(", "short", "string", ",", "long", "string", ",", "value", "int", ",", "usage", "string", ")", "*", "int", "{", "flagVar", ":=", "value", "\n", "return", "IntVar", "(", "&", "flagVar", ",", "short", ",", "long", ",", "value", ",", "usage", ")", "\n", "}" ]
// Int is a convenience wrapper for IntVar
[ "Int", "is", "a", "convenience", "wrapper", "for", "IntVar" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tflag/flag.go#L125-L128
12,061
trivago/tgo
tflag/flag.go
Int64
func Int64(short string, long string, value int64, usage string) *int64 { flagVar := value return Int64Var(&flagVar, short, long, value, usage) }
go
func Int64(short string, long string, value int64, usage string) *int64 { flagVar := value return Int64Var(&flagVar, short, long, value, usage) }
[ "func", "Int64", "(", "short", "string", ",", "long", "string", ",", "value", "int64", ",", "usage", "string", ")", "*", "int64", "{", "flagVar", ":=", "value", "\n", "return", "Int64Var", "(", "&", "flagVar", ",", "short", ",", "long", ",", "value", ",", "usage", ")", "\n", "}" ]
// Int64 is a convenience wrapper for Int64Var
[ "Int64", "is", "a", "convenience", "wrapper", "for", "Int64Var" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tflag/flag.go#L131-L134
12,062
trivago/tgo
tflag/flag.go
Float64
func Float64(short string, long string, value float64, usage string) *float64 { flagVar := value return Float64Var(&flagVar, short, long, value, usage) }
go
func Float64(short string, long string, value float64, usage string) *float64 { flagVar := value return Float64Var(&flagVar, short, long, value, usage) }
[ "func", "Float64", "(", "short", "string", ",", "long", "string", ",", "value", "float64", ",", "usage", "string", ")", "*", "float64", "{", "flagVar", ":=", "value", "\n", "return", "Float64Var", "(", "&", "flagVar", ",", "short", ",", "long", ",", "value", ",", "usage", ")", "\n", "}" ]
// Float64 is a convenience wrapper for Float64Var
[ "Float64", "is", "a", "convenience", "wrapper", "for", "Float64Var" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tflag/flag.go#L137-L140
12,063
trivago/tgo
tflag/flag.go
String
func String(short string, long string, value string, usage string) *string { flagVar := value return StringVar(&flagVar, short, long, value, usage) }
go
func String(short string, long string, value string, usage string) *string { flagVar := value return StringVar(&flagVar, short, long, value, usage) }
[ "func", "String", "(", "short", "string", ",", "long", "string", ",", "value", "string", ",", "usage", "string", ")", "*", "string", "{", "flagVar", ":=", "value", "\n", "return", "StringVar", "(", "&", "flagVar", ",", "short", ",", "long", ",", "value", ",", "usage", ")", "\n", "}" ]
// String is a convenience wrapper for StringVar
[ "String", "is", "a", "convenience", "wrapper", "for", "StringVar" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tflag/flag.go#L143-L146
12,064
trivago/tgo
tflag/flag.go
PrintFlags
func PrintFlags(header string) { fmt.Println(header) valueFmt := fmt.Sprintf("%%-%ds\tdefault: %%-%ds\t%%-%ds\n", tabWidth[tabKey], tabWidth[tabValue], tabWidth[tabUsage]) for _, desc := range descriptions { fmt.Printf(valueFmt, desc.flagKey, desc.value, desc.usage) } }
go
func PrintFlags(header string) { fmt.Println(header) valueFmt := fmt.Sprintf("%%-%ds\tdefault: %%-%ds\t%%-%ds\n", tabWidth[tabKey], tabWidth[tabValue], tabWidth[tabUsage]) for _, desc := range descriptions { fmt.Printf(valueFmt, desc.flagKey, desc.value, desc.usage) } }
[ "func", "PrintFlags", "(", "header", "string", ")", "{", "fmt", ".", "Println", "(", "header", ")", "\n", "valueFmt", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\t", "\\t", "\\n", "\"", ",", "tabWidth", "[", "tabKey", "]", ",", "tabWidth", "[", "tabValue", "]", ",", "tabWidth", "[", "tabUsage", "]", ")", "\n\n", "for", "_", ",", "desc", ":=", "range", "descriptions", "{", "fmt", ".", "Printf", "(", "valueFmt", ",", "desc", ".", "flagKey", ",", "desc", ".", "value", ",", "desc", ".", "usage", ")", "\n", "}", "\n", "}" ]
// PrintFlags prints information about the flags set for this application
[ "PrintFlags", "prints", "information", "about", "the", "flags", "set", "for", "this", "application" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tflag/flag.go#L154-L161
12,065
trivago/tgo
tio/bufferedreader.go
Reset
func (buffer *BufferedReader) Reset(sequence uint64) { buffer.end = 0 buffer.incomplete = true }
go
func (buffer *BufferedReader) Reset(sequence uint64) { buffer.end = 0 buffer.incomplete = true }
[ "func", "(", "buffer", "*", "BufferedReader", ")", "Reset", "(", "sequence", "uint64", ")", "{", "buffer", ".", "end", "=", "0", "\n", "buffer", ".", "incomplete", "=", "true", "\n", "}" ]
// Reset clears the buffer by resetting its internal state
[ "Reset", "clears", "the", "buffer", "by", "resetting", "its", "internal", "state" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tio/bufferedreader.go#L170-L173
12,066
trivago/tgo
tio/bufferedreader.go
ResetGetIncomplete
func (buffer *BufferedReader) ResetGetIncomplete() []byte { remains := buffer.data[:buffer.end] buffer.Reset(0) return remains }
go
func (buffer *BufferedReader) ResetGetIncomplete() []byte { remains := buffer.data[:buffer.end] buffer.Reset(0) return remains }
[ "func", "(", "buffer", "*", "BufferedReader", ")", "ResetGetIncomplete", "(", ")", "[", "]", "byte", "{", "remains", ":=", "buffer", ".", "data", "[", ":", "buffer", ".", "end", "]", "\n", "buffer", ".", "Reset", "(", "0", ")", "\n", "return", "remains", "\n", "}" ]
// ResetGetIncomplete works like Reset but returns any incomplete contents // left in the buffer. Note that the data in the buffer returned is overwritten // with the next read call.
[ "ResetGetIncomplete", "works", "like", "Reset", "but", "returns", "any", "incomplete", "contents", "left", "in", "the", "buffer", ".", "Note", "that", "the", "data", "in", "the", "buffer", "returned", "is", "overwritten", "with", "the", "next", "read", "call", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tio/bufferedreader.go#L178-L182
12,067
trivago/tgo
tio/bufferedreader.go
extractMessage
func (buffer *BufferedReader) extractMessage(messageLen int, msgStartIdx int) ([]byte, int) { nextMsgIdx := msgStartIdx + messageLen if nextMsgIdx > buffer.end { return nil, 0 // ### return, incomplete ### } if buffer.flags&BufferedReaderFlagEverything != 0 { msgStartIdx = 0 } return buffer.data[msgStartIdx:nextMsgIdx], nextMsgIdx }
go
func (buffer *BufferedReader) extractMessage(messageLen int, msgStartIdx int) ([]byte, int) { nextMsgIdx := msgStartIdx + messageLen if nextMsgIdx > buffer.end { return nil, 0 // ### return, incomplete ### } if buffer.flags&BufferedReaderFlagEverything != 0 { msgStartIdx = 0 } return buffer.data[msgStartIdx:nextMsgIdx], nextMsgIdx }
[ "func", "(", "buffer", "*", "BufferedReader", ")", "extractMessage", "(", "messageLen", "int", ",", "msgStartIdx", "int", ")", "(", "[", "]", "byte", ",", "int", ")", "{", "nextMsgIdx", ":=", "msgStartIdx", "+", "messageLen", "\n", "if", "nextMsgIdx", ">", "buffer", ".", "end", "{", "return", "nil", ",", "0", "// ### return, incomplete ###", "\n", "}", "\n", "if", "buffer", ".", "flags", "&", "BufferedReaderFlagEverything", "!=", "0", "{", "msgStartIdx", "=", "0", "\n", "}", "\n", "return", "buffer", ".", "data", "[", "msgStartIdx", ":", "nextMsgIdx", "]", ",", "nextMsgIdx", "\n", "}" ]
// general message extraction part of all parser methods
[ "general", "message", "extraction", "part", "of", "all", "parser", "methods" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tio/bufferedreader.go#L190-L199
12,068
trivago/tgo
tio/bufferedreader.go
parseDelimiter
func (buffer *BufferedReader) parseDelimiter() ([]byte, int) { delimiterIdx := bytes.Index(buffer.data[:buffer.end], buffer.delimiter) if delimiterIdx == -1 { return nil, 0 // ### return, incomplete ### } messageLen := delimiterIdx if buffer.flags&BufferedReaderFlagEverything != 0 { messageLen += len(buffer.delimiter) } data, nextMsgIdx := buffer.extractMessage(messageLen, 0) if data != nil && buffer.flags&BufferedReaderFlagEverything == 0 { nextMsgIdx += len(buffer.delimiter) } return data, nextMsgIdx }
go
func (buffer *BufferedReader) parseDelimiter() ([]byte, int) { delimiterIdx := bytes.Index(buffer.data[:buffer.end], buffer.delimiter) if delimiterIdx == -1 { return nil, 0 // ### return, incomplete ### } messageLen := delimiterIdx if buffer.flags&BufferedReaderFlagEverything != 0 { messageLen += len(buffer.delimiter) } data, nextMsgIdx := buffer.extractMessage(messageLen, 0) if data != nil && buffer.flags&BufferedReaderFlagEverything == 0 { nextMsgIdx += len(buffer.delimiter) } return data, nextMsgIdx }
[ "func", "(", "buffer", "*", "BufferedReader", ")", "parseDelimiter", "(", ")", "(", "[", "]", "byte", ",", "int", ")", "{", "delimiterIdx", ":=", "bytes", ".", "Index", "(", "buffer", ".", "data", "[", ":", "buffer", ".", "end", "]", ",", "buffer", ".", "delimiter", ")", "\n", "if", "delimiterIdx", "==", "-", "1", "{", "return", "nil", ",", "0", "// ### return, incomplete ###", "\n", "}", "\n\n", "messageLen", ":=", "delimiterIdx", "\n", "if", "buffer", ".", "flags", "&", "BufferedReaderFlagEverything", "!=", "0", "{", "messageLen", "+=", "len", "(", "buffer", ".", "delimiter", ")", "\n", "}", "\n\n", "data", ",", "nextMsgIdx", ":=", "buffer", ".", "extractMessage", "(", "messageLen", ",", "0", ")", "\n\n", "if", "data", "!=", "nil", "&&", "buffer", ".", "flags", "&", "BufferedReaderFlagEverything", "==", "0", "{", "nextMsgIdx", "+=", "len", "(", "buffer", ".", "delimiter", ")", "\n", "}", "\n", "return", "data", ",", "nextMsgIdx", "\n", "}" ]
// messages are separated by a delimiter string
[ "messages", "are", "separated", "by", "a", "delimiter", "string" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tio/bufferedreader.go#L207-L224
12,069
trivago/tgo
tio/bufferedreader.go
parseMLE16
func (buffer *BufferedReader) parseMLE16() ([]byte, int) { var messageLen uint16 reader := bytes.NewReader(buffer.data[buffer.paramMLE:buffer.end]) err := binary.Read(reader, buffer.encoding, &messageLen) if err != nil { return nil, -1 // ### return, malformed ### } return buffer.extractMessage(int(messageLen), buffer.paramMLE+2) }
go
func (buffer *BufferedReader) parseMLE16() ([]byte, int) { var messageLen uint16 reader := bytes.NewReader(buffer.data[buffer.paramMLE:buffer.end]) err := binary.Read(reader, buffer.encoding, &messageLen) if err != nil { return nil, -1 // ### return, malformed ### } return buffer.extractMessage(int(messageLen), buffer.paramMLE+2) }
[ "func", "(", "buffer", "*", "BufferedReader", ")", "parseMLE16", "(", ")", "(", "[", "]", "byte", ",", "int", ")", "{", "var", "messageLen", "uint16", "\n", "reader", ":=", "bytes", ".", "NewReader", "(", "buffer", ".", "data", "[", "buffer", ".", "paramMLE", ":", "buffer", ".", "end", "]", ")", "\n", "err", ":=", "binary", ".", "Read", "(", "reader", ",", "buffer", ".", "encoding", ",", "&", "messageLen", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "-", "1", "// ### return, malformed ###", "\n", "}", "\n", "return", "buffer", ".", "extractMessage", "(", "int", "(", "messageLen", ")", ",", "buffer", ".", "paramMLE", "+", "2", ")", "\n", "}" ]
// messages are separated binary length encoded
[ "messages", "are", "separated", "binary", "length", "encoded" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tio/bufferedreader.go#L261-L269
12,070
trivago/tgo
tio/bufferedreader.go
parseDelimiterRegex
func (buffer *BufferedReader) parseDelimiterRegex() ([]byte, int) { startOffset := 0 for { delimiterIdx := buffer.delimiterRegexp.FindIndex(buffer.data[startOffset:buffer.end]) if delimiterIdx == nil { return nil, 0 // ### return, incomplete ### } // If we do end of message parsing, we're done if buffer.flags&BufferedReaderFlagRegexStart != BufferedReaderFlagRegexStart { return buffer.extractMessage(delimiterIdx[1], 0) // ### done, end of line ### } // We're done if this is the second pass (start offset > 0) // We're done if we have data before the match (incomplete message) if startOffset > 0 || delimiterIdx[0] > 0 { return buffer.extractMessage(delimiterIdx[0]+startOffset, 0) // ### done, start of line ### } // Found delimiter at start of data, look for the start of a second message. // We don't need to add startOffset here as we never reach this if startOffset != 0 startOffset = delimiterIdx[1] } }
go
func (buffer *BufferedReader) parseDelimiterRegex() ([]byte, int) { startOffset := 0 for { delimiterIdx := buffer.delimiterRegexp.FindIndex(buffer.data[startOffset:buffer.end]) if delimiterIdx == nil { return nil, 0 // ### return, incomplete ### } // If we do end of message parsing, we're done if buffer.flags&BufferedReaderFlagRegexStart != BufferedReaderFlagRegexStart { return buffer.extractMessage(delimiterIdx[1], 0) // ### done, end of line ### } // We're done if this is the second pass (start offset > 0) // We're done if we have data before the match (incomplete message) if startOffset > 0 || delimiterIdx[0] > 0 { return buffer.extractMessage(delimiterIdx[0]+startOffset, 0) // ### done, start of line ### } // Found delimiter at start of data, look for the start of a second message. // We don't need to add startOffset here as we never reach this if startOffset != 0 startOffset = delimiterIdx[1] } }
[ "func", "(", "buffer", "*", "BufferedReader", ")", "parseDelimiterRegex", "(", ")", "(", "[", "]", "byte", ",", "int", ")", "{", "startOffset", ":=", "0", "\n\n", "for", "{", "delimiterIdx", ":=", "buffer", ".", "delimiterRegexp", ".", "FindIndex", "(", "buffer", ".", "data", "[", "startOffset", ":", "buffer", ".", "end", "]", ")", "\n", "if", "delimiterIdx", "==", "nil", "{", "return", "nil", ",", "0", "// ### return, incomplete ###", "\n", "}", "\n\n", "// If we do end of message parsing, we're done", "if", "buffer", ".", "flags", "&", "BufferedReaderFlagRegexStart", "!=", "BufferedReaderFlagRegexStart", "{", "return", "buffer", ".", "extractMessage", "(", "delimiterIdx", "[", "1", "]", ",", "0", ")", "// ### done, end of line ###", "\n", "}", "\n\n", "// We're done if this is the second pass (start offset > 0)", "// We're done if we have data before the match (incomplete message)", "if", "startOffset", ">", "0", "||", "delimiterIdx", "[", "0", "]", ">", "0", "{", "return", "buffer", ".", "extractMessage", "(", "delimiterIdx", "[", "0", "]", "+", "startOffset", ",", "0", ")", "// ### done, start of line ###", "\n", "}", "\n\n", "// Found delimiter at start of data, look for the start of a second message.", "// We don't need to add startOffset here as we never reach this if startOffset != 0", "startOffset", "=", "delimiterIdx", "[", "1", "]", "\n", "}", "\n", "}" ]
// messages are separated by regexp
[ "messages", "are", "separated", "by", "regexp" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tio/bufferedreader.go#L294-L318
12,071
trivago/tgo
tio/bufferedreader.go
ReadAll
func (buffer *BufferedReader) ReadAll(reader io.Reader, callback BufferReadCallback) error { for { data, more, err := buffer.ReadOne(reader) if data != nil && callback != nil { callback(data) } if err != nil { return err // ### return, error ### } if !more { return nil // ### return, done ### } } }
go
func (buffer *BufferedReader) ReadAll(reader io.Reader, callback BufferReadCallback) error { for { data, more, err := buffer.ReadOne(reader) if data != nil && callback != nil { callback(data) } if err != nil { return err // ### return, error ### } if !more { return nil // ### return, done ### } } }
[ "func", "(", "buffer", "*", "BufferedReader", ")", "ReadAll", "(", "reader", "io", ".", "Reader", ",", "callback", "BufferReadCallback", ")", "error", "{", "for", "{", "data", ",", "more", ",", "err", ":=", "buffer", ".", "ReadOne", "(", "reader", ")", "\n", "if", "data", "!=", "nil", "&&", "callback", "!=", "nil", "{", "callback", "(", "data", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "// ### return, error ###", "\n", "}", "\n\n", "if", "!", "more", "{", "return", "nil", "// ### return, done ###", "\n", "}", "\n", "}", "\n", "}" ]
// ReadAll calls ReadOne as long as there are messages in the stream. // Messages will be send to the given write callback. // If callback is nil, data will be read and discarded.
[ "ReadAll", "calls", "ReadOne", "as", "long", "as", "there", "are", "messages", "in", "the", "stream", ".", "Messages", "will", "be", "send", "to", "the", "given", "write", "callback", ".", "If", "callback", "is", "nil", "data", "will", "be", "read", "and", "discarded", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tio/bufferedreader.go#L323-L338
12,072
trivago/tgo
tlog/log.go
NewLogScope
func NewLogScope(name string) LogScope { scopeMarker := tfmt.Colorizef(tfmt.DarkGray, tfmt.NoBackground, "[%s] ", name) return LogScope{ name: name, Error: log.New(logLogger{Error}, scopeMarker, 0), Warning: log.New(logLogger{Warning}, scopeMarker, 0), Note: log.New(logLogger{Note}, scopeMarker, 0), Debug: log.New(logLogger{Debug}, scopeMarker, 0), } }
go
func NewLogScope(name string) LogScope { scopeMarker := tfmt.Colorizef(tfmt.DarkGray, tfmt.NoBackground, "[%s] ", name) return LogScope{ name: name, Error: log.New(logLogger{Error}, scopeMarker, 0), Warning: log.New(logLogger{Warning}, scopeMarker, 0), Note: log.New(logLogger{Note}, scopeMarker, 0), Debug: log.New(logLogger{Debug}, scopeMarker, 0), } }
[ "func", "NewLogScope", "(", "name", "string", ")", "LogScope", "{", "scopeMarker", ":=", "tfmt", ".", "Colorizef", "(", "tfmt", ".", "DarkGray", ",", "tfmt", ".", "NoBackground", ",", "\"", "\"", ",", "name", ")", "\n\n", "return", "LogScope", "{", "name", ":", "name", ",", "Error", ":", "log", ".", "New", "(", "logLogger", "{", "Error", "}", ",", "scopeMarker", ",", "0", ")", ",", "Warning", ":", "log", ".", "New", "(", "logLogger", "{", "Warning", "}", ",", "scopeMarker", ",", "0", ")", ",", "Note", ":", "log", ".", "New", "(", "logLogger", "{", "Note", "}", ",", "scopeMarker", ",", "0", ")", ",", "Debug", ":", "log", ".", "New", "(", "logLogger", "{", "Debug", "}", ",", "scopeMarker", ",", "0", ")", ",", "}", "\n", "}" ]
// NewLogScope creates a new LogScope with the given prefix string.
[ "NewLogScope", "creates", "a", "new", "LogScope", "with", "the", "given", "prefix", "string", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tlog/log.go#L68-L78
12,073
trivago/tgo
tlog/log.go
SetVerbosity
func SetVerbosity(loglevel Verbosity) { Error = log.New(logDisabled, "", 0) Warning = log.New(logDisabled, "", 0) Note = log.New(logDisabled, "", 0) Debug = log.New(logDisabled, "", 0) switch loglevel { default: fallthrough case VerbosityDebug: Debug = log.New(&logEnabled, tfmt.Colorize(tfmt.Cyan, tfmt.NoBackground, "Debug: "), 0) fallthrough case VerbosityNote: Note = log.New(&logEnabled, "", 0) fallthrough case VerbosityWarning: Warning = log.New(&logEnabled, tfmt.Colorize(tfmt.Yellow, tfmt.NoBackground, "Warning: "), 0) fallthrough case VerbosityError: Error = log.New(&logEnabled, tfmt.Colorize(tfmt.Red, tfmt.NoBackground, "ERROR: "), log.Lshortfile) } }
go
func SetVerbosity(loglevel Verbosity) { Error = log.New(logDisabled, "", 0) Warning = log.New(logDisabled, "", 0) Note = log.New(logDisabled, "", 0) Debug = log.New(logDisabled, "", 0) switch loglevel { default: fallthrough case VerbosityDebug: Debug = log.New(&logEnabled, tfmt.Colorize(tfmt.Cyan, tfmt.NoBackground, "Debug: "), 0) fallthrough case VerbosityNote: Note = log.New(&logEnabled, "", 0) fallthrough case VerbosityWarning: Warning = log.New(&logEnabled, tfmt.Colorize(tfmt.Yellow, tfmt.NoBackground, "Warning: "), 0) fallthrough case VerbosityError: Error = log.New(&logEnabled, tfmt.Colorize(tfmt.Red, tfmt.NoBackground, "ERROR: "), log.Lshortfile) } }
[ "func", "SetVerbosity", "(", "loglevel", "Verbosity", ")", "{", "Error", "=", "log", ".", "New", "(", "logDisabled", ",", "\"", "\"", ",", "0", ")", "\n", "Warning", "=", "log", ".", "New", "(", "logDisabled", ",", "\"", "\"", ",", "0", ")", "\n", "Note", "=", "log", ".", "New", "(", "logDisabled", ",", "\"", "\"", ",", "0", ")", "\n", "Debug", "=", "log", ".", "New", "(", "logDisabled", ",", "\"", "\"", ",", "0", ")", "\n\n", "switch", "loglevel", "{", "default", ":", "fallthrough", "\n\n", "case", "VerbosityDebug", ":", "Debug", "=", "log", ".", "New", "(", "&", "logEnabled", ",", "tfmt", ".", "Colorize", "(", "tfmt", ".", "Cyan", ",", "tfmt", ".", "NoBackground", ",", "\"", "\"", ")", ",", "0", ")", "\n", "fallthrough", "\n\n", "case", "VerbosityNote", ":", "Note", "=", "log", ".", "New", "(", "&", "logEnabled", ",", "\"", "\"", ",", "0", ")", "\n", "fallthrough", "\n\n", "case", "VerbosityWarning", ":", "Warning", "=", "log", ".", "New", "(", "&", "logEnabled", ",", "tfmt", ".", "Colorize", "(", "tfmt", ".", "Yellow", ",", "tfmt", ".", "NoBackground", ",", "\"", "\"", ")", ",", "0", ")", "\n", "fallthrough", "\n\n", "case", "VerbosityError", ":", "Error", "=", "log", ".", "New", "(", "&", "logEnabled", ",", "tfmt", ".", "Colorize", "(", "tfmt", ".", "Red", ",", "tfmt", ".", "NoBackground", ",", "\"", "\"", ")", ",", "log", ".", "Lshortfile", ")", "\n", "}", "\n", "}" ]
// SetVerbosity defines the type of messages to be processed. // High level verobosities contain lower levels, i.e. log level warning will // contain error messages, too.
[ "SetVerbosity", "defines", "the", "type", "of", "messages", "to", "be", "processed", ".", "High", "level", "verobosities", "contain", "lower", "levels", "i", ".", "e", ".", "log", "level", "warning", "will", "contain", "error", "messages", "too", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tlog/log.go#L102-L127
12,074
trivago/tgo
tlog/log.go
SetCacheWriter
func SetCacheWriter() { if _, isCache := logEnabled.writer.(*logCache); !isCache { logEnabled.writer = new(logCache) } }
go
func SetCacheWriter() { if _, isCache := logEnabled.writer.(*logCache); !isCache { logEnabled.writer = new(logCache) } }
[ "func", "SetCacheWriter", "(", ")", "{", "if", "_", ",", "isCache", ":=", "logEnabled", ".", "writer", ".", "(", "*", "logCache", ")", ";", "!", "isCache", "{", "logEnabled", ".", "writer", "=", "new", "(", "logCache", ")", "\n", "}", "\n", "}" ]
// SetCacheWriter will force all logs to be cached until another writer is set
[ "SetCacheWriter", "will", "force", "all", "logs", "to", "be", "cached", "until", "another", "writer", "is", "set" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tlog/log.go#L130-L134
12,075
trivago/tgo
tnet/thttp/sockettransport.go
RoundTrip
func (s SocketRoundtripper) RoundTrip(req *http.Request) (*http.Response, error) { if req.Body != nil { defer req.Body.Close() } socket, err := net.Dial("unix", s.path) if err != nil { return nil, err } defer socket.Close() socket.SetWriteDeadline(time.Now().Add(5 * time.Second)) if err := req.Write(socket); err != nil { return nil, err } socket.SetReadDeadline(time.Now().Add(5 * time.Second)) reader := bufio.NewReader(socket) return http.ReadResponse(reader, req) }
go
func (s SocketRoundtripper) RoundTrip(req *http.Request) (*http.Response, error) { if req.Body != nil { defer req.Body.Close() } socket, err := net.Dial("unix", s.path) if err != nil { return nil, err } defer socket.Close() socket.SetWriteDeadline(time.Now().Add(5 * time.Second)) if err := req.Write(socket); err != nil { return nil, err } socket.SetReadDeadline(time.Now().Add(5 * time.Second)) reader := bufio.NewReader(socket) return http.ReadResponse(reader, req) }
[ "func", "(", "s", "SocketRoundtripper", ")", "RoundTrip", "(", "req", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "if", "req", ".", "Body", "!=", "nil", "{", "defer", "req", ".", "Body", ".", "Close", "(", ")", "\n", "}", "\n", "socket", ",", "err", ":=", "net", ".", "Dial", "(", "\"", "\"", ",", "s", ".", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "socket", ".", "Close", "(", ")", "\n\n", "socket", ".", "SetWriteDeadline", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "5", "*", "time", ".", "Second", ")", ")", "\n", "if", "err", ":=", "req", ".", "Write", "(", "socket", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "socket", ".", "SetReadDeadline", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "5", "*", "time", ".", "Second", ")", ")", "\n", "reader", ":=", "bufio", ".", "NewReader", "(", "socket", ")", "\n", "return", "http", ".", "ReadResponse", "(", "reader", ",", "req", ")", "\n", "}" ]
// RoundTrip dials the unix domain socket, sends the request and processes the // response.
[ "RoundTrip", "dials", "the", "unix", "domain", "socket", "sends", "the", "request", "and", "processes", "the", "response", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tnet/thttp/sockettransport.go#L48-L66
12,076
trivago/tgo
metric.go
NewMetrics
func NewMetrics() *Metrics { return &Metrics{ store: make(map[string]*int64), rates: make(map[string]*rate), storeGuard: new(sync.RWMutex), rateGuard: new(sync.RWMutex), } }
go
func NewMetrics() *Metrics { return &Metrics{ store: make(map[string]*int64), rates: make(map[string]*rate), storeGuard: new(sync.RWMutex), rateGuard: new(sync.RWMutex), } }
[ "func", "NewMetrics", "(", ")", "*", "Metrics", "{", "return", "&", "Metrics", "{", "store", ":", "make", "(", "map", "[", "string", "]", "*", "int64", ")", ",", "rates", ":", "make", "(", "map", "[", "string", "]", "*", "rate", ")", ",", "storeGuard", ":", "new", "(", "sync", ".", "RWMutex", ")", ",", "rateGuard", ":", "new", "(", "sync", ".", "RWMutex", ")", ",", "}", "\n", "}" ]
// NewMetrics creates a new metrics container. // To initialize the global Metrics variable use EnableGlobalMetrics.
[ "NewMetrics", "creates", "a", "new", "metrics", "container", ".", "To", "initialize", "the", "global", "Metrics", "variable", "use", "EnableGlobalMetrics", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/metric.go#L92-L99
12,077
trivago/tgo
metric.go
Set
func (met *Metrics) Set(name string, value int64) { atomic.StoreInt64(met.get(name), value) }
go
func (met *Metrics) Set(name string, value int64) { atomic.StoreInt64(met.get(name), value) }
[ "func", "(", "met", "*", "Metrics", ")", "Set", "(", "name", "string", ",", "value", "int64", ")", "{", "atomic", ".", "StoreInt64", "(", "met", ".", "get", "(", "name", ")", ",", "value", ")", "\n", "}" ]
// Set sets a given metric to a given value.
[ "Set", "sets", "a", "given", "metric", "to", "a", "given", "value", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/metric.go#L194-L196
12,078
trivago/tgo
metric.go
Inc
func (met *Metrics) Inc(name string) { atomic.AddInt64(met.get(name), 1) }
go
func (met *Metrics) Inc(name string) { atomic.AddInt64(met.get(name), 1) }
[ "func", "(", "met", "*", "Metrics", ")", "Inc", "(", "name", "string", ")", "{", "atomic", ".", "AddInt64", "(", "met", ".", "get", "(", "name", ")", ",", "1", ")", "\n", "}" ]
// Inc adds 1 to a given metric.
[ "Inc", "adds", "1", "to", "a", "given", "metric", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/metric.go#L219-L221
12,079
trivago/tgo
metric.go
Dec
func (met *Metrics) Dec(name string) { atomic.AddInt64(met.get(name), -1) }
go
func (met *Metrics) Dec(name string) { atomic.AddInt64(met.get(name), -1) }
[ "func", "(", "met", "*", "Metrics", ")", "Dec", "(", "name", "string", ")", "{", "atomic", ".", "AddInt64", "(", "met", ".", "get", "(", "name", ")", ",", "-", "1", ")", "\n", "}" ]
// Dec subtracts 1 from a given metric.
[ "Dec", "subtracts", "1", "from", "a", "given", "metric", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/metric.go#L224-L226
12,080
trivago/tgo
metric.go
Add
func (met *Metrics) Add(name string, value int64) { atomic.AddInt64(met.get(name), value) }
go
func (met *Metrics) Add(name string, value int64) { atomic.AddInt64(met.get(name), value) }
[ "func", "(", "met", "*", "Metrics", ")", "Add", "(", "name", "string", ",", "value", "int64", ")", "{", "atomic", ".", "AddInt64", "(", "met", ".", "get", "(", "name", ")", ",", "value", ")", "\n", "}" ]
// Add adds a number to a given metric.
[ "Add", "adds", "a", "number", "to", "a", "given", "metric", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/metric.go#L229-L231
12,081
trivago/tgo
metric.go
Get
func (met *Metrics) Get(name string) (int64, error) { if metric := met.tryGetMetric(name); metric != nil { return atomic.LoadInt64(metric), nil } if rate := met.tryGetRate(name); rate != nil { return *rate, nil } // Neither rate nor metric found return 0, fmt.Errorf("Metric %s not found", name) }
go
func (met *Metrics) Get(name string) (int64, error) { if metric := met.tryGetMetric(name); metric != nil { return atomic.LoadInt64(metric), nil } if rate := met.tryGetRate(name); rate != nil { return *rate, nil } // Neither rate nor metric found return 0, fmt.Errorf("Metric %s not found", name) }
[ "func", "(", "met", "*", "Metrics", ")", "Get", "(", "name", "string", ")", "(", "int64", ",", "error", ")", "{", "if", "metric", ":=", "met", ".", "tryGetMetric", "(", "name", ")", ";", "metric", "!=", "nil", "{", "return", "atomic", ".", "LoadInt64", "(", "metric", ")", ",", "nil", "\n", "}", "\n\n", "if", "rate", ":=", "met", ".", "tryGetRate", "(", "name", ")", ";", "rate", "!=", "nil", "{", "return", "*", "rate", ",", "nil", "\n", "}", "\n\n", "// Neither rate nor metric found", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}" ]
// Get returns the value of a given metric or rate. // If the value does not exists error is non-nil and the returned value is 0.
[ "Get", "returns", "the", "value", "of", "a", "given", "metric", "or", "rate", ".", "If", "the", "value", "does", "not", "exists", "error", "is", "non", "-", "nil", "and", "the", "returned", "value", "is", "0", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/metric.go#L262-L273
12,082
trivago/tgo
metric.go
Dump
func (met *Metrics) Dump() ([]byte, error) { snapshot := make(map[string]int64) met.storeGuard.RLock() for key, value := range met.store { snapshot[key] = atomic.LoadInt64(value) } met.storeGuard.RUnlock() met.rateGuard.RLock() for key, rate := range met.rates { snapshot[key] = rate.value } met.rateGuard.RUnlock() return json.Marshal(snapshot) }
go
func (met *Metrics) Dump() ([]byte, error) { snapshot := make(map[string]int64) met.storeGuard.RLock() for key, value := range met.store { snapshot[key] = atomic.LoadInt64(value) } met.storeGuard.RUnlock() met.rateGuard.RLock() for key, rate := range met.rates { snapshot[key] = rate.value } met.rateGuard.RUnlock() return json.Marshal(snapshot) }
[ "func", "(", "met", "*", "Metrics", ")", "Dump", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "snapshot", ":=", "make", "(", "map", "[", "string", "]", "int64", ")", "\n\n", "met", ".", "storeGuard", ".", "RLock", "(", ")", "\n", "for", "key", ",", "value", ":=", "range", "met", ".", "store", "{", "snapshot", "[", "key", "]", "=", "atomic", ".", "LoadInt64", "(", "value", ")", "\n", "}", "\n", "met", ".", "storeGuard", ".", "RUnlock", "(", ")", "\n\n", "met", ".", "rateGuard", ".", "RLock", "(", ")", "\n", "for", "key", ",", "rate", ":=", "range", "met", ".", "rates", "{", "snapshot", "[", "key", "]", "=", "rate", ".", "value", "\n", "}", "\n", "met", ".", "rateGuard", ".", "RUnlock", "(", ")", "\n\n", "return", "json", ".", "Marshal", "(", "snapshot", ")", "\n", "}" ]
// Dump creates a JSON string from all stored metrics.
[ "Dump", "creates", "a", "JSON", "string", "from", "all", "stored", "metrics", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/metric.go#L276-L292
12,083
trivago/tgo
metric.go
ResetMetrics
func (met *Metrics) ResetMetrics() { met.storeGuard.Lock() for key := range met.store { switch key { case MetricProcessStart, MetricGoRoutines, MetricGoVersion: // ignore default: *met.store[key] = 0 } } met.storeGuard.Unlock() met.rateGuard.Lock() for _, rate := range met.rates { rate.lastSample = 0 rate.value = 0 rate.index = 0 rate.samples.Set(0) } met.rateGuard.Unlock() }
go
func (met *Metrics) ResetMetrics() { met.storeGuard.Lock() for key := range met.store { switch key { case MetricProcessStart, MetricGoRoutines, MetricGoVersion: // ignore default: *met.store[key] = 0 } } met.storeGuard.Unlock() met.rateGuard.Lock() for _, rate := range met.rates { rate.lastSample = 0 rate.value = 0 rate.index = 0 rate.samples.Set(0) } met.rateGuard.Unlock() }
[ "func", "(", "met", "*", "Metrics", ")", "ResetMetrics", "(", ")", "{", "met", ".", "storeGuard", ".", "Lock", "(", ")", "\n", "for", "key", ":=", "range", "met", ".", "store", "{", "switch", "key", "{", "case", "MetricProcessStart", ",", "MetricGoRoutines", ",", "MetricGoVersion", ":", "// ignore", "default", ":", "*", "met", ".", "store", "[", "key", "]", "=", "0", "\n", "}", "\n", "}", "\n", "met", ".", "storeGuard", ".", "Unlock", "(", ")", "\n\n", "met", ".", "rateGuard", ".", "Lock", "(", ")", "\n", "for", "_", ",", "rate", ":=", "range", "met", ".", "rates", "{", "rate", ".", "lastSample", "=", "0", "\n", "rate", ".", "value", "=", "0", "\n", "rate", ".", "index", "=", "0", "\n", "rate", ".", "samples", ".", "Set", "(", "0", ")", "\n", "}", "\n", "met", ".", "rateGuard", ".", "Unlock", "(", ")", "\n", "}" ]
// ResetMetrics resets all registered key values to 0 expect for system Metrics. // This locks all writes in the process.
[ "ResetMetrics", "resets", "all", "registered", "key", "values", "to", "0", "expect", "for", "system", "Metrics", ".", "This", "locks", "all", "writes", "in", "the", "process", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/metric.go#L296-L316
12,084
trivago/tgo
metric.go
FetchAndReset
func (met *Metrics) FetchAndReset(keys ...string) map[string]int64 { state := make(map[string]int64) met.storeGuard.Lock() for _, key := range keys { if val, exists := met.store[key]; exists { state[key] = *val *val = 0 } } met.storeGuard.Unlock() met.rateGuard.Lock() for _, key := range keys { if rate, exists := met.rates[key]; exists { rate.lastSample = 0 rate.value = 0 rate.index = 0 rate.samples.Set(0) } } met.rateGuard.Unlock() return state }
go
func (met *Metrics) FetchAndReset(keys ...string) map[string]int64 { state := make(map[string]int64) met.storeGuard.Lock() for _, key := range keys { if val, exists := met.store[key]; exists { state[key] = *val *val = 0 } } met.storeGuard.Unlock() met.rateGuard.Lock() for _, key := range keys { if rate, exists := met.rates[key]; exists { rate.lastSample = 0 rate.value = 0 rate.index = 0 rate.samples.Set(0) } } met.rateGuard.Unlock() return state }
[ "func", "(", "met", "*", "Metrics", ")", "FetchAndReset", "(", "keys", "...", "string", ")", "map", "[", "string", "]", "int64", "{", "state", ":=", "make", "(", "map", "[", "string", "]", "int64", ")", "\n\n", "met", ".", "storeGuard", ".", "Lock", "(", ")", "\n", "for", "_", ",", "key", ":=", "range", "keys", "{", "if", "val", ",", "exists", ":=", "met", ".", "store", "[", "key", "]", ";", "exists", "{", "state", "[", "key", "]", "=", "*", "val", "\n", "*", "val", "=", "0", "\n", "}", "\n", "}", "\n", "met", ".", "storeGuard", ".", "Unlock", "(", ")", "\n\n", "met", ".", "rateGuard", ".", "Lock", "(", ")", "\n", "for", "_", ",", "key", ":=", "range", "keys", "{", "if", "rate", ",", "exists", ":=", "met", ".", "rates", "[", "key", "]", ";", "exists", "{", "rate", ".", "lastSample", "=", "0", "\n", "rate", ".", "value", "=", "0", "\n", "rate", ".", "index", "=", "0", "\n", "rate", ".", "samples", ".", "Set", "(", "0", ")", "\n", "}", "\n", "}", "\n", "met", ".", "rateGuard", ".", "Unlock", "(", ")", "\n\n", "return", "state", "\n", "}" ]
// FetchAndReset resets all of the given keys to 0 and returns the // value before the reset as array. If a given metric does not exist // it is ignored. This locks all writes in the process.
[ "FetchAndReset", "resets", "all", "of", "the", "given", "keys", "to", "0", "and", "returns", "the", "value", "before", "the", "reset", "as", "array", ".", "If", "a", "given", "metric", "does", "not", "exist", "it", "is", "ignored", ".", "This", "locks", "all", "writes", "in", "the", "process", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/metric.go#L321-L345
12,085
trivago/tgo
metric.go
UpdateSystemMetrics
func (met *Metrics) UpdateSystemMetrics() { stats := new(runtime.MemStats) runtime.ReadMemStats(stats) met.SetI(MetricGoRoutines, runtime.NumGoroutine()) met.Set(MetricMemoryAllocated, int64(stats.Alloc)) met.SetB(MetricMemoryGCEnabled, stats.EnableGC) met.Set(MetricMemoryNumObjects, int64(stats.HeapObjects)) }
go
func (met *Metrics) UpdateSystemMetrics() { stats := new(runtime.MemStats) runtime.ReadMemStats(stats) met.SetI(MetricGoRoutines, runtime.NumGoroutine()) met.Set(MetricMemoryAllocated, int64(stats.Alloc)) met.SetB(MetricMemoryGCEnabled, stats.EnableGC) met.Set(MetricMemoryNumObjects, int64(stats.HeapObjects)) }
[ "func", "(", "met", "*", "Metrics", ")", "UpdateSystemMetrics", "(", ")", "{", "stats", ":=", "new", "(", "runtime", ".", "MemStats", ")", "\n", "runtime", ".", "ReadMemStats", "(", "stats", ")", "\n\n", "met", ".", "SetI", "(", "MetricGoRoutines", ",", "runtime", ".", "NumGoroutine", "(", ")", ")", "\n", "met", ".", "Set", "(", "MetricMemoryAllocated", ",", "int64", "(", "stats", ".", "Alloc", ")", ")", "\n", "met", ".", "SetB", "(", "MetricMemoryGCEnabled", ",", "stats", ".", "EnableGC", ")", "\n", "met", ".", "Set", "(", "MetricMemoryNumObjects", ",", "int64", "(", "stats", ".", "HeapObjects", ")", ")", "\n", "}" ]
// UpdateSystemMetrics updates all default or system based metrics like memory // consumption and number of go routines. This function is not called // automatically.
[ "UpdateSystemMetrics", "updates", "all", "default", "or", "system", "based", "metrics", "like", "memory", "consumption", "and", "number", "of", "go", "routines", ".", "This", "function", "is", "not", "called", "automatically", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/metric.go#L350-L358
12,086
trivago/tgo
tcontainer/trie.go
NewTrie
func NewTrie(data []byte, payload interface{}) *TrieNode { return &TrieNode{ suffix: data, children: []*TrieNode{}, longestPath: len(data), PathLen: len(data), Payload: payload, } }
go
func NewTrie(data []byte, payload interface{}) *TrieNode { return &TrieNode{ suffix: data, children: []*TrieNode{}, longestPath: len(data), PathLen: len(data), Payload: payload, } }
[ "func", "NewTrie", "(", "data", "[", "]", "byte", ",", "payload", "interface", "{", "}", ")", "*", "TrieNode", "{", "return", "&", "TrieNode", "{", "suffix", ":", "data", ",", "children", ":", "[", "]", "*", "TrieNode", "{", "}", ",", "longestPath", ":", "len", "(", "data", ")", ",", "PathLen", ":", "len", "(", "data", ")", ",", "Payload", ":", "payload", ",", "}", "\n", "}" ]
// NewTrie creates a new root TrieNode
[ "NewTrie", "creates", "a", "new", "root", "TrieNode" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tcontainer/trie.go#L29-L37
12,087
trivago/tgo
tcontainer/trie.go
ForEach
func (node *TrieNode) ForEach(callback func(*TrieNode)) { callback(node) for _, child := range node.children { child.ForEach(callback) } }
go
func (node *TrieNode) ForEach(callback func(*TrieNode)) { callback(node) for _, child := range node.children { child.ForEach(callback) } }
[ "func", "(", "node", "*", "TrieNode", ")", "ForEach", "(", "callback", "func", "(", "*", "TrieNode", ")", ")", "{", "callback", "(", "node", ")", "\n", "for", "_", ",", "child", ":=", "range", "node", ".", "children", "{", "child", ".", "ForEach", "(", "callback", ")", "\n", "}", "\n", "}" ]
// ForEach applies a function to each node in the tree including and below the // passed node.
[ "ForEach", "applies", "a", "function", "to", "each", "node", "in", "the", "tree", "including", "and", "below", "the", "passed", "node", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tcontainer/trie.go#L76-L81
12,088
trivago/tgo
tcontainer/trie.go
Match
func (node *TrieNode) Match(data []byte) *TrieNode { dataLen := len(data) suffixLen := len(node.suffix) if dataLen < suffixLen { return nil // ### return, cannot be fully matched ### } for i := 0; i < suffixLen; i++ { if data[i] != node.suffix[i] { return nil // ### return, no match ### } } if dataLen == suffixLen { if node.PathLen > 0 { return node // ### return, full match ### } return nil // ### return, invalid match ### } data = data[suffixLen:] numChildren := len(node.children) for i := 0; i < numChildren; i++ { matchedNode := node.children[i].Match(data) if matchedNode != nil { return matchedNode // ### return, match found ### } } return nil // ### return, no valid path ### }
go
func (node *TrieNode) Match(data []byte) *TrieNode { dataLen := len(data) suffixLen := len(node.suffix) if dataLen < suffixLen { return nil // ### return, cannot be fully matched ### } for i := 0; i < suffixLen; i++ { if data[i] != node.suffix[i] { return nil // ### return, no match ### } } if dataLen == suffixLen { if node.PathLen > 0 { return node // ### return, full match ### } return nil // ### return, invalid match ### } data = data[suffixLen:] numChildren := len(node.children) for i := 0; i < numChildren; i++ { matchedNode := node.children[i].Match(data) if matchedNode != nil { return matchedNode // ### return, match found ### } } return nil // ### return, no valid path ### }
[ "func", "(", "node", "*", "TrieNode", ")", "Match", "(", "data", "[", "]", "byte", ")", "*", "TrieNode", "{", "dataLen", ":=", "len", "(", "data", ")", "\n", "suffixLen", ":=", "len", "(", "node", ".", "suffix", ")", "\n", "if", "dataLen", "<", "suffixLen", "{", "return", "nil", "// ### return, cannot be fully matched ###", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "suffixLen", ";", "i", "++", "{", "if", "data", "[", "i", "]", "!=", "node", ".", "suffix", "[", "i", "]", "{", "return", "nil", "// ### return, no match ###", "\n", "}", "\n", "}", "\n\n", "if", "dataLen", "==", "suffixLen", "{", "if", "node", ".", "PathLen", ">", "0", "{", "return", "node", "// ### return, full match ###", "\n", "}", "\n", "return", "nil", "// ### return, invalid match ###", "\n", "}", "\n\n", "data", "=", "data", "[", "suffixLen", ":", "]", "\n", "numChildren", ":=", "len", "(", "node", ".", "children", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "numChildren", ";", "i", "++", "{", "matchedNode", ":=", "node", ".", "children", "[", "i", "]", ".", "Match", "(", "data", ")", "\n", "if", "matchedNode", "!=", "nil", "{", "return", "matchedNode", "// ### return, match found ###", "\n", "}", "\n", "}", "\n\n", "return", "nil", "// ### return, no valid path ###", "\n", "}" ]
// Match compares the trie to the given data stream. // Match returns true if data can be completely matched to the trie.
[ "Match", "compares", "the", "trie", "to", "the", "given", "data", "stream", ".", "Match", "returns", "true", "if", "data", "can", "be", "completely", "matched", "to", "the", "trie", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tcontainer/trie.go#L163-L193
12,089
trivago/tgo
errorstack.go
Push
func (stack *ErrorStack) Push(err error) bool { if err != nil { stack.errors = append(stack.errors, err) return true } return false }
go
func (stack *ErrorStack) Push(err error) bool { if err != nil { stack.errors = append(stack.errors, err) return true } return false }
[ "func", "(", "stack", "*", "ErrorStack", ")", "Push", "(", "err", "error", ")", "bool", "{", "if", "err", "!=", "nil", "{", "stack", ".", "errors", "=", "append", "(", "stack", ".", "errors", ",", "err", ")", "\n", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Push adds a new error to the top of the error stack. // Returns if err != nil.
[ "Push", "adds", "a", "new", "error", "to", "the", "top", "of", "the", "error", "stack", ".", "Returns", "if", "err", "!", "=", "nil", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/errorstack.go#L48-L54
12,090
trivago/tgo
errorstack.go
Pushf
func (stack *ErrorStack) Pushf(message string, args ...interface{}) { stack.errors = append(stack.errors, fmt.Errorf(message, args...)) }
go
func (stack *ErrorStack) Pushf(message string, args ...interface{}) { stack.errors = append(stack.errors, fmt.Errorf(message, args...)) }
[ "func", "(", "stack", "*", "ErrorStack", ")", "Pushf", "(", "message", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "stack", ".", "errors", "=", "append", "(", "stack", ".", "errors", ",", "fmt", ".", "Errorf", "(", "message", ",", "args", "...", ")", ")", "\n", "}" ]
// Pushf adds a new error message to the top of the error stack
[ "Pushf", "adds", "a", "new", "error", "message", "to", "the", "top", "of", "the", "error", "stack" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/errorstack.go#L57-L59
12,091
trivago/tgo
errorstack.go
PushAndDescribe
func (stack *ErrorStack) PushAndDescribe(message string, err error) bool { if err != nil { stack.errors = append(stack.errors, fmt.Errorf(message+" %s", err.Error())) return true } return false }
go
func (stack *ErrorStack) PushAndDescribe(message string, err error) bool { if err != nil { stack.errors = append(stack.errors, fmt.Errorf(message+" %s", err.Error())) return true } return false }
[ "func", "(", "stack", "*", "ErrorStack", ")", "PushAndDescribe", "(", "message", "string", ",", "err", "error", ")", "bool", "{", "if", "err", "!=", "nil", "{", "stack", ".", "errors", "=", "append", "(", "stack", ".", "errors", ",", "fmt", ".", "Errorf", "(", "message", "+", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", ")", "\n", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// PushAndDescribe behaves like Push but allows to prepend a text before // the error messages returned by err. The type of err will be lost.
[ "PushAndDescribe", "behaves", "like", "Push", "but", "allows", "to", "prepend", "a", "text", "before", "the", "error", "messages", "returned", "by", "err", ".", "The", "type", "of", "err", "will", "be", "lost", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/errorstack.go#L63-L69
12,092
trivago/tgo
errorstack.go
Pop
func (stack *ErrorStack) Pop() error { if len(stack.errors) == 0 { return nil } err := stack.errors[len(stack.errors)-1] stack.errors = stack.errors[:len(stack.errors)-1] return err }
go
func (stack *ErrorStack) Pop() error { if len(stack.errors) == 0 { return nil } err := stack.errors[len(stack.errors)-1] stack.errors = stack.errors[:len(stack.errors)-1] return err }
[ "func", "(", "stack", "*", "ErrorStack", ")", "Pop", "(", ")", "error", "{", "if", "len", "(", "stack", ".", "errors", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "err", ":=", "stack", ".", "errors", "[", "len", "(", "stack", ".", "errors", ")", "-", "1", "]", "\n", "stack", ".", "errors", "=", "stack", ".", "errors", "[", ":", "len", "(", "stack", ".", "errors", ")", "-", "1", "]", "\n", "return", "err", "\n", "}" ]
// Pop removes an error from the top of the stack and returns it
[ "Pop", "removes", "an", "error", "from", "the", "top", "of", "the", "stack", "and", "returns", "it" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/errorstack.go#L72-L79
12,093
trivago/tgo
errorstack.go
Error
func (stack ErrorStack) Error() string { if len(stack.errors) == 0 { return "" } return stack.formatter(stack.errors) }
go
func (stack ErrorStack) Error() string { if len(stack.errors) == 0 { return "" } return stack.formatter(stack.errors) }
[ "func", "(", "stack", "ErrorStack", ")", "Error", "(", ")", "string", "{", "if", "len", "(", "stack", ".", "errors", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "return", "stack", ".", "formatter", "(", "stack", ".", "errors", ")", "\n", "}" ]
// Error implements the Error interface
[ "Error", "implements", "the", "Error", "interface" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/errorstack.go#L90-L96
12,094
trivago/tgo
errorstack.go
ErrorStackFormatNumbered
func ErrorStackFormatNumbered(errors []error) string { errString := "" lastIdx := len(errors) - 1 for i := 0; i < lastIdx; i++ { errString = fmt.Sprintf("%s%d: %s\n", errString, i+1, errors[i].Error()) } errString = fmt.Sprintf("%s%d: %s", errString, lastIdx+1, errors[lastIdx].Error()) return errString }
go
func ErrorStackFormatNumbered(errors []error) string { errString := "" lastIdx := len(errors) - 1 for i := 0; i < lastIdx; i++ { errString = fmt.Sprintf("%s%d: %s\n", errString, i+1, errors[i].Error()) } errString = fmt.Sprintf("%s%d: %s", errString, lastIdx+1, errors[lastIdx].Error()) return errString }
[ "func", "ErrorStackFormatNumbered", "(", "errors", "[", "]", "error", ")", "string", "{", "errString", ":=", "\"", "\"", "\n", "lastIdx", ":=", "len", "(", "errors", ")", "-", "1", "\n", "for", "i", ":=", "0", ";", "i", "<", "lastIdx", ";", "i", "++", "{", "errString", "=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "errString", ",", "i", "+", "1", ",", "errors", "[", "i", "]", ".", "Error", "(", ")", ")", "\n", "}", "\n", "errString", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "errString", ",", "lastIdx", "+", "1", ",", "errors", "[", "lastIdx", "]", ".", "Error", "(", ")", ")", "\n", "return", "errString", "\n", "}" ]
// ErrorStackFormatNumbered returns errors with a number prefix, separated by // newline.
[ "ErrorStackFormatNumbered", "returns", "errors", "with", "a", "number", "prefix", "separated", "by", "newline", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/errorstack.go#L123-L131
12,095
trivago/tgo
metricserver.go
NewMetricServer
func NewMetricServer() *MetricServer { return &MetricServer{ metrics: Metric, running: false, updates: time.NewTicker(time.Second), } }
go
func NewMetricServer() *MetricServer { return &MetricServer{ metrics: Metric, running: false, updates: time.NewTicker(time.Second), } }
[ "func", "NewMetricServer", "(", ")", "*", "MetricServer", "{", "return", "&", "MetricServer", "{", "metrics", ":", "Metric", ",", "running", ":", "false", ",", "updates", ":", "time", ".", "NewTicker", "(", "time", ".", "Second", ")", ",", "}", "\n", "}" ]
// NewMetricServer creates a new server state for a metric server based on // the global Metric variable.
[ "NewMetricServer", "creates", "a", "new", "server", "state", "for", "a", "metric", "server", "based", "on", "the", "global", "Metric", "variable", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/metricserver.go#L33-L39
12,096
trivago/tgo
metricserver.go
NewMetricServerFor
func NewMetricServerFor(m *Metrics) *MetricServer { return &MetricServer{ metrics: m, running: false, updates: time.NewTicker(time.Second), } }
go
func NewMetricServerFor(m *Metrics) *MetricServer { return &MetricServer{ metrics: m, running: false, updates: time.NewTicker(time.Second), } }
[ "func", "NewMetricServerFor", "(", "m", "*", "Metrics", ")", "*", "MetricServer", "{", "return", "&", "MetricServer", "{", "metrics", ":", "m", ",", "running", ":", "false", ",", "updates", ":", "time", ".", "NewTicker", "(", "time", ".", "Second", ")", ",", "}", "\n", "}" ]
// NewMetricServerFor creates a new server state for a metric server based // on a custom Metrics variable
[ "NewMetricServerFor", "creates", "a", "new", "server", "state", "for", "a", "metric", "server", "based", "on", "a", "custom", "Metrics", "variable" ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/metricserver.go#L43-L49
12,097
trivago/tgo
metricserver.go
Stop
func (server *MetricServer) Stop() { server.running = false server.updates.Stop() if server.listen != nil { if err := server.listen.Close(); err != nil { log.Print("Metrics: ", err) } } }
go
func (server *MetricServer) Stop() { server.running = false server.updates.Stop() if server.listen != nil { if err := server.listen.Close(); err != nil { log.Print("Metrics: ", err) } } }
[ "func", "(", "server", "*", "MetricServer", ")", "Stop", "(", ")", "{", "server", ".", "running", "=", "false", "\n", "server", ".", "updates", ".", "Stop", "(", ")", "\n", "if", "server", ".", "listen", "!=", "nil", "{", "if", "err", ":=", "server", ".", "listen", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Print", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Stop notifies the metric server to halt.
[ "Stop", "notifies", "the", "metric", "server", "to", "halt", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/metricserver.go#L109-L117
12,098
trivago/tgo
tsync/queue.go
NewQueueWithSpinner
func NewQueueWithSpinner(capacity uint32, spinner Spinner) Queue { return Queue{ items: make([]interface{}, capacity), read: newQueueAccess(), write: newQueueAccess(), locked: new(int32), capacity: uint64(capacity), spin: spinner, } }
go
func NewQueueWithSpinner(capacity uint32, spinner Spinner) Queue { return Queue{ items: make([]interface{}, capacity), read: newQueueAccess(), write: newQueueAccess(), locked: new(int32), capacity: uint64(capacity), spin: spinner, } }
[ "func", "NewQueueWithSpinner", "(", "capacity", "uint32", ",", "spinner", "Spinner", ")", "Queue", "{", "return", "Queue", "{", "items", ":", "make", "(", "[", "]", "interface", "{", "}", ",", "capacity", ")", ",", "read", ":", "newQueueAccess", "(", ")", ",", "write", ":", "newQueueAccess", "(", ")", ",", "locked", ":", "new", "(", "int32", ")", ",", "capacity", ":", "uint64", "(", "capacity", ")", ",", "spin", ":", "spinner", ",", "}", "\n", "}" ]
// NewQueueWithSpinner allows to set the spinning priority of the queue to // be created.
[ "NewQueueWithSpinner", "allows", "to", "set", "the", "spinning", "priority", "of", "the", "queue", "to", "be", "created", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tsync/queue.go#L61-L70
12,099
trivago/tgo
tsync/queue.go
Push
func (q *Queue) Push(item interface{}) error { if atomic.LoadInt32(q.locked) == 1 { return LockedError{"Queue is locked"} // ### return, closed ### } // Get ticket and slot ticket := atomic.AddUint64(q.write.next, 1) - 1 slot := ticket % q.capacity spin := q.spin // Wait for pending reads on slot for ticket-atomic.LoadUint64(q.read.processing) >= q.capacity { spin.Yield() } q.items[slot] = item // Wait for previous writers to finish writing for ticket != atomic.LoadUint64(q.write.processing) { spin.Yield() } atomic.AddUint64(q.write.processing, 1) return nil }
go
func (q *Queue) Push(item interface{}) error { if atomic.LoadInt32(q.locked) == 1 { return LockedError{"Queue is locked"} // ### return, closed ### } // Get ticket and slot ticket := atomic.AddUint64(q.write.next, 1) - 1 slot := ticket % q.capacity spin := q.spin // Wait for pending reads on slot for ticket-atomic.LoadUint64(q.read.processing) >= q.capacity { spin.Yield() } q.items[slot] = item // Wait for previous writers to finish writing for ticket != atomic.LoadUint64(q.write.processing) { spin.Yield() } atomic.AddUint64(q.write.processing, 1) return nil }
[ "func", "(", "q", "*", "Queue", ")", "Push", "(", "item", "interface", "{", "}", ")", "error", "{", "if", "atomic", ".", "LoadInt32", "(", "q", ".", "locked", ")", "==", "1", "{", "return", "LockedError", "{", "\"", "\"", "}", "// ### return, closed ###", "\n", "}", "\n\n", "// Get ticket and slot", "ticket", ":=", "atomic", ".", "AddUint64", "(", "q", ".", "write", ".", "next", ",", "1", ")", "-", "1", "\n", "slot", ":=", "ticket", "%", "q", ".", "capacity", "\n", "spin", ":=", "q", ".", "spin", "\n\n", "// Wait for pending reads on slot", "for", "ticket", "-", "atomic", ".", "LoadUint64", "(", "q", ".", "read", ".", "processing", ")", ">=", "q", ".", "capacity", "{", "spin", ".", "Yield", "(", ")", "\n", "}", "\n\n", "q", ".", "items", "[", "slot", "]", "=", "item", "\n\n", "// Wait for previous writers to finish writing", "for", "ticket", "!=", "atomic", ".", "LoadUint64", "(", "q", ".", "write", ".", "processing", ")", "{", "spin", ".", "Yield", "(", ")", "\n", "}", "\n", "atomic", ".", "AddUint64", "(", "q", ".", "write", ".", "processing", ",", "1", ")", "\n", "return", "nil", "\n", "}" ]
// Push adds an item to the queue. This call may block if the queue is full. // An error is returned when the queue is locked.
[ "Push", "adds", "an", "item", "to", "the", "queue", ".", "This", "call", "may", "block", "if", "the", "queue", "is", "full", ".", "An", "error", "is", "returned", "when", "the", "queue", "is", "locked", "." ]
efdb64f40efe6e7cd3f50415710e7af6a7c316ad
https://github.com/trivago/tgo/blob/efdb64f40efe6e7cd3f50415710e7af6a7c316ad/tsync/queue.go#L74-L97