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
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
900
paulmach/go.geojson
feature_collection.go
AddFeature
func (fc *FeatureCollection) AddFeature(feature *Feature) *FeatureCollection { fc.Features = append(fc.Features, feature) return fc }
go
func (fc *FeatureCollection) AddFeature(feature *Feature) *FeatureCollection { fc.Features = append(fc.Features, feature) return fc }
[ "func", "(", "fc", "*", "FeatureCollection", ")", "AddFeature", "(", "feature", "*", "Feature", ")", "*", "FeatureCollection", "{", "fc", ".", "Features", "=", "append", "(", "fc", ".", "Features", ",", "feature", ")", "\n", "return", "fc", "\n", "}" ]
// AddFeature appends a feature to the collection.
[ "AddFeature", "appends", "a", "feature", "to", "the", "collection", "." ]
a5c451da2d9c67c590ae6be92565b67698286a1a
https://github.com/paulmach/go.geojson/blob/a5c451da2d9c67c590ae6be92565b67698286a1a/feature_collection.go#L29-L32
901
paulmach/go.geojson
geometry.go
MarshalJSON
func (g Geometry) MarshalJSON() ([]byte, error) { // defining a struct here lets us define the order of the JSON elements. type geometry struct { Type GeometryType `json:"type"` BoundingBox []float64 `json:"bbox,omitempty"` Coordinates interface{} `json:"coordinates,omitempty"` Geometries interface{} `json:"geometries,omitempty"` CRS map[string]interface{} `json:"crs,omitempty"` } geo := &geometry{ Type: g.Type, } if g.BoundingBox != nil && len(g.BoundingBox) != 0 { geo.BoundingBox = g.BoundingBox } switch g.Type { case GeometryPoint: geo.Coordinates = g.Point case GeometryMultiPoint: geo.Coordinates = g.MultiPoint case GeometryLineString: geo.Coordinates = g.LineString case GeometryMultiLineString: geo.Coordinates = g.MultiLineString case GeometryPolygon: geo.Coordinates = g.Polygon case GeometryMultiPolygon: geo.Coordinates = g.MultiPolygon case GeometryCollection: geo.Geometries = g.Geometries } return json.Marshal(geo) }
go
func (g Geometry) MarshalJSON() ([]byte, error) { // defining a struct here lets us define the order of the JSON elements. type geometry struct { Type GeometryType `json:"type"` BoundingBox []float64 `json:"bbox,omitempty"` Coordinates interface{} `json:"coordinates,omitempty"` Geometries interface{} `json:"geometries,omitempty"` CRS map[string]interface{} `json:"crs,omitempty"` } geo := &geometry{ Type: g.Type, } if g.BoundingBox != nil && len(g.BoundingBox) != 0 { geo.BoundingBox = g.BoundingBox } switch g.Type { case GeometryPoint: geo.Coordinates = g.Point case GeometryMultiPoint: geo.Coordinates = g.MultiPoint case GeometryLineString: geo.Coordinates = g.LineString case GeometryMultiLineString: geo.Coordinates = g.MultiLineString case GeometryPolygon: geo.Coordinates = g.Polygon case GeometryMultiPolygon: geo.Coordinates = g.MultiPolygon case GeometryCollection: geo.Geometries = g.Geometries } return json.Marshal(geo) }
[ "func", "(", "g", "Geometry", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// defining a struct here lets us define the order of the JSON elements.", "type", "geometry", "struct", "{", "Type", "GeometryType", "`json:\"type\"`", "\n", "BoundingBox", "[", "]", "float64", "`json:\"bbox,omitempty\"`", "\n", "Coordinates", "interface", "{", "}", "`json:\"coordinates,omitempty\"`", "\n", "Geometries", "interface", "{", "}", "`json:\"geometries,omitempty\"`", "\n", "CRS", "map", "[", "string", "]", "interface", "{", "}", "`json:\"crs,omitempty\"`", "\n", "}", "\n\n", "geo", ":=", "&", "geometry", "{", "Type", ":", "g", ".", "Type", ",", "}", "\n\n", "if", "g", ".", "BoundingBox", "!=", "nil", "&&", "len", "(", "g", ".", "BoundingBox", ")", "!=", "0", "{", "geo", ".", "BoundingBox", "=", "g", ".", "BoundingBox", "\n", "}", "\n\n", "switch", "g", ".", "Type", "{", "case", "GeometryPoint", ":", "geo", ".", "Coordinates", "=", "g", ".", "Point", "\n", "case", "GeometryMultiPoint", ":", "geo", ".", "Coordinates", "=", "g", ".", "MultiPoint", "\n", "case", "GeometryLineString", ":", "geo", ".", "Coordinates", "=", "g", ".", "LineString", "\n", "case", "GeometryMultiLineString", ":", "geo", ".", "Coordinates", "=", "g", ".", "MultiLineString", "\n", "case", "GeometryPolygon", ":", "geo", ".", "Coordinates", "=", "g", ".", "Polygon", "\n", "case", "GeometryMultiPolygon", ":", "geo", ".", "Coordinates", "=", "g", ".", "MultiPolygon", "\n", "case", "GeometryCollection", ":", "geo", ".", "Geometries", "=", "g", ".", "Geometries", "\n", "}", "\n\n", "return", "json", ".", "Marshal", "(", "geo", ")", "\n", "}" ]
// MarshalJSON converts the geometry object into the correct JSON. // This fulfills the json.Marshaler interface.
[ "MarshalJSON", "converts", "the", "geometry", "object", "into", "the", "correct", "JSON", ".", "This", "fulfills", "the", "json", ".", "Marshaler", "interface", "." ]
a5c451da2d9c67c590ae6be92565b67698286a1a
https://github.com/paulmach/go.geojson/blob/a5c451da2d9c67c590ae6be92565b67698286a1a/geometry.go#L95-L131
902
paulmach/go.geojson
geometry.go
UnmarshalJSON
func (g *Geometry) UnmarshalJSON(data []byte) error { var object map[string]interface{} err := json.Unmarshal(data, &object) if err != nil { return err } return decodeGeometry(g, object) }
go
func (g *Geometry) UnmarshalJSON(data []byte) error { var object map[string]interface{} err := json.Unmarshal(data, &object) if err != nil { return err } return decodeGeometry(g, object) }
[ "func", "(", "g", "*", "Geometry", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "var", "object", "map", "[", "string", "]", "interface", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "object", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "decodeGeometry", "(", "g", ",", "object", ")", "\n", "}" ]
// UnmarshalJSON decodes the data into a GeoJSON geometry. // This fulfills the json.Unmarshaler interface.
[ "UnmarshalJSON", "decodes", "the", "data", "into", "a", "GeoJSON", "geometry", ".", "This", "fulfills", "the", "json", ".", "Unmarshaler", "interface", "." ]
a5c451da2d9c67c590ae6be92565b67698286a1a
https://github.com/paulmach/go.geojson/blob/a5c451da2d9c67c590ae6be92565b67698286a1a/geometry.go#L147-L155
903
howeyc/gopass
pass.go
getPasswd
func getPasswd(prompt string, masked bool, r FdReader, w io.Writer) ([]byte, error) { var err error var pass, bs, mask []byte if masked { bs = []byte("\b \b") mask = []byte("*") } if isTerminal(r.Fd()) { if oldState, err := makeRaw(r.Fd()); err != nil { return pass, err } else { defer func() { restore(r.Fd(), oldState) fmt.Fprintln(w) }() } } if prompt != "" { fmt.Fprint(w, prompt) } // Track total bytes read, not just bytes in the password. This ensures any // errors that might flood the console with nil or -1 bytes infinitely are // capped. var counter int for counter = 0; counter <= maxLength; counter++ { if v, e := getch(r); e != nil { err = e break } else if v == 127 || v == 8 { if l := len(pass); l > 0 { pass = pass[:l-1] fmt.Fprint(w, string(bs)) } } else if v == 13 || v == 10 { break } else if v == 3 { err = ErrInterrupted break } else if v != 0 { pass = append(pass, v) fmt.Fprint(w, string(mask)) } } if counter > maxLength { err = ErrMaxLengthExceeded } return pass, err }
go
func getPasswd(prompt string, masked bool, r FdReader, w io.Writer) ([]byte, error) { var err error var pass, bs, mask []byte if masked { bs = []byte("\b \b") mask = []byte("*") } if isTerminal(r.Fd()) { if oldState, err := makeRaw(r.Fd()); err != nil { return pass, err } else { defer func() { restore(r.Fd(), oldState) fmt.Fprintln(w) }() } } if prompt != "" { fmt.Fprint(w, prompt) } // Track total bytes read, not just bytes in the password. This ensures any // errors that might flood the console with nil or -1 bytes infinitely are // capped. var counter int for counter = 0; counter <= maxLength; counter++ { if v, e := getch(r); e != nil { err = e break } else if v == 127 || v == 8 { if l := len(pass); l > 0 { pass = pass[:l-1] fmt.Fprint(w, string(bs)) } } else if v == 13 || v == 10 { break } else if v == 3 { err = ErrInterrupted break } else if v != 0 { pass = append(pass, v) fmt.Fprint(w, string(mask)) } } if counter > maxLength { err = ErrMaxLengthExceeded } return pass, err }
[ "func", "getPasswd", "(", "prompt", "string", ",", "masked", "bool", ",", "r", "FdReader", ",", "w", "io", ".", "Writer", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "pass", ",", "bs", ",", "mask", "[", "]", "byte", "\n", "if", "masked", "{", "bs", "=", "[", "]", "byte", "(", "\"", "\\b", "\\b", "\"", ")", "\n", "mask", "=", "[", "]", "byte", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "isTerminal", "(", "r", ".", "Fd", "(", ")", ")", "{", "if", "oldState", ",", "err", ":=", "makeRaw", "(", "r", ".", "Fd", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "pass", ",", "err", "\n", "}", "else", "{", "defer", "func", "(", ")", "{", "restore", "(", "r", ".", "Fd", "(", ")", ",", "oldState", ")", "\n", "fmt", ".", "Fprintln", "(", "w", ")", "\n", "}", "(", ")", "\n", "}", "\n", "}", "\n\n", "if", "prompt", "!=", "\"", "\"", "{", "fmt", ".", "Fprint", "(", "w", ",", "prompt", ")", "\n", "}", "\n\n", "// Track total bytes read, not just bytes in the password. This ensures any", "// errors that might flood the console with nil or -1 bytes infinitely are", "// capped.", "var", "counter", "int", "\n", "for", "counter", "=", "0", ";", "counter", "<=", "maxLength", ";", "counter", "++", "{", "if", "v", ",", "e", ":=", "getch", "(", "r", ")", ";", "e", "!=", "nil", "{", "err", "=", "e", "\n", "break", "\n", "}", "else", "if", "v", "==", "127", "||", "v", "==", "8", "{", "if", "l", ":=", "len", "(", "pass", ")", ";", "l", ">", "0", "{", "pass", "=", "pass", "[", ":", "l", "-", "1", "]", "\n", "fmt", ".", "Fprint", "(", "w", ",", "string", "(", "bs", ")", ")", "\n", "}", "\n", "}", "else", "if", "v", "==", "13", "||", "v", "==", "10", "{", "break", "\n", "}", "else", "if", "v", "==", "3", "{", "err", "=", "ErrInterrupted", "\n", "break", "\n", "}", "else", "if", "v", "!=", "0", "{", "pass", "=", "append", "(", "pass", ",", "v", ")", "\n", "fmt", ".", "Fprint", "(", "w", ",", "string", "(", "mask", ")", ")", "\n", "}", "\n", "}", "\n\n", "if", "counter", ">", "maxLength", "{", "err", "=", "ErrMaxLengthExceeded", "\n", "}", "\n\n", "return", "pass", ",", "err", "\n", "}" ]
// getPasswd returns the input read from terminal. // If prompt is not empty, it will be output as a prompt to the user // If masked is true, typing will be matched by asterisks on the screen. // Otherwise, typing will echo nothing.
[ "getPasswd", "returns", "the", "input", "read", "from", "terminal", ".", "If", "prompt", "is", "not", "empty", "it", "will", "be", "output", "as", "a", "prompt", "to", "the", "user", "If", "masked", "is", "true", "typing", "will", "be", "matched", "by", "asterisks", "on", "the", "screen", ".", "Otherwise", "typing", "will", "echo", "nothing", "." ]
bf9dde6d0d2c004a008c27aaee91170c786f6db8
https://github.com/howeyc/gopass/blob/bf9dde6d0d2c004a008c27aaee91170c786f6db8/pass.go#L39-L91
904
howeyc/gopass
pass.go
GetPasswdPrompt
func GetPasswdPrompt(prompt string, mask bool, r FdReader, w io.Writer) ([]byte, error) { return getPasswd(prompt, mask, r, w) }
go
func GetPasswdPrompt(prompt string, mask bool, r FdReader, w io.Writer) ([]byte, error) { return getPasswd(prompt, mask, r, w) }
[ "func", "GetPasswdPrompt", "(", "prompt", "string", ",", "mask", "bool", ",", "r", "FdReader", ",", "w", "io", ".", "Writer", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "getPasswd", "(", "prompt", ",", "mask", ",", "r", ",", "w", ")", "\n", "}" ]
// GetPasswdPrompt prompts the user and returns the password read from the terminal. // If mask is true, then asterisks are echoed. // The returned byte array does not include end-of-line characters.
[ "GetPasswdPrompt", "prompts", "the", "user", "and", "returns", "the", "password", "read", "from", "the", "terminal", ".", "If", "mask", "is", "true", "then", "asterisks", "are", "echoed", ".", "The", "returned", "byte", "array", "does", "not", "include", "end", "-", "of", "-", "line", "characters", "." ]
bf9dde6d0d2c004a008c27aaee91170c786f6db8
https://github.com/howeyc/gopass/blob/bf9dde6d0d2c004a008c27aaee91170c786f6db8/pass.go#L108-L110
905
dimiro1/banner
banner.go
Init
func Init(out io.Writer, isEnabled, isColorEnabled bool, in io.Reader) { if !isEnabled { logger.Println("The banner is not enabled.") return } if in == nil { logger.Println("The input is nil") return } banner, err := ioutil.ReadAll(in) if err != nil { logger.Printf("Error trying to read the banner, err: %v", err) return } show(out, isColorEnabled, string(banner)) }
go
func Init(out io.Writer, isEnabled, isColorEnabled bool, in io.Reader) { if !isEnabled { logger.Println("The banner is not enabled.") return } if in == nil { logger.Println("The input is nil") return } banner, err := ioutil.ReadAll(in) if err != nil { logger.Printf("Error trying to read the banner, err: %v", err) return } show(out, isColorEnabled, string(banner)) }
[ "func", "Init", "(", "out", "io", ".", "Writer", ",", "isEnabled", ",", "isColorEnabled", "bool", ",", "in", "io", ".", "Reader", ")", "{", "if", "!", "isEnabled", "{", "logger", ".", "Println", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "if", "in", "==", "nil", "{", "logger", ".", "Println", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "banner", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "in", ")", "\n\n", "if", "err", "!=", "nil", "{", "logger", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "show", "(", "out", ",", "isColorEnabled", ",", "string", "(", "banner", ")", ")", "\n", "}" ]
// Init load the banner and prints it to output // All errors are ignored, the application will not print the banner in case of error.
[ "Init", "load", "the", "banner", "and", "prints", "it", "to", "output", "All", "errors", "are", "ignored", "the", "application", "will", "not", "print", "the", "banner", "in", "case", "of", "error", "." ]
c2f858997d49ffd03f84818bef3c25c2fcc67e16
https://github.com/dimiro1/banner/blob/c2f858997d49ffd03f84818bef3c25c2fcc67e16/banner.go#L50-L69
906
leekchan/timeutil
timedelta.go
Add
func (t *Timedelta) Add(t2 *Timedelta) Timedelta { return Timedelta{ Days: t.Days + t2.Days, Seconds: t.Seconds + t2.Seconds, Microseconds: t.Microseconds + t2.Microseconds, Milliseconds: t.Milliseconds + t2.Milliseconds, Minutes: t.Minutes + t2.Minutes, Hours: t.Hours + t2.Hours, Weeks: t.Weeks + t2.Weeks, } }
go
func (t *Timedelta) Add(t2 *Timedelta) Timedelta { return Timedelta{ Days: t.Days + t2.Days, Seconds: t.Seconds + t2.Seconds, Microseconds: t.Microseconds + t2.Microseconds, Milliseconds: t.Milliseconds + t2.Milliseconds, Minutes: t.Minutes + t2.Minutes, Hours: t.Hours + t2.Hours, Weeks: t.Weeks + t2.Weeks, } }
[ "func", "(", "t", "*", "Timedelta", ")", "Add", "(", "t2", "*", "Timedelta", ")", "Timedelta", "{", "return", "Timedelta", "{", "Days", ":", "t", ".", "Days", "+", "t2", ".", "Days", ",", "Seconds", ":", "t", ".", "Seconds", "+", "t2", ".", "Seconds", ",", "Microseconds", ":", "t", ".", "Microseconds", "+", "t2", ".", "Microseconds", ",", "Milliseconds", ":", "t", ".", "Milliseconds", "+", "t2", ".", "Milliseconds", ",", "Minutes", ":", "t", ".", "Minutes", "+", "t2", ".", "Minutes", ",", "Hours", ":", "t", ".", "Hours", "+", "t2", ".", "Hours", ",", "Weeks", ":", "t", ".", "Weeks", "+", "t2", ".", "Weeks", ",", "}", "\n", "}" ]
// Add returns the Timedelta t+t2.
[ "Add", "returns", "the", "Timedelta", "t", "+", "t2", "." ]
28917288c48df3d2c1cfe468c273e0b2adda0aa5
https://github.com/leekchan/timeutil/blob/28917288c48df3d2c1cfe468c273e0b2adda0aa5/timedelta.go#L21-L31
907
leekchan/timeutil
timedelta.go
Abs
func (t *Timedelta) Abs() Timedelta { return Timedelta{ Days: abs(t.Days), Seconds: abs(t.Seconds), Microseconds: abs(t.Microseconds), Milliseconds: abs(t.Milliseconds), Minutes: abs(t.Minutes), Hours: abs(t.Hours), Weeks: abs(t.Weeks), } }
go
func (t *Timedelta) Abs() Timedelta { return Timedelta{ Days: abs(t.Days), Seconds: abs(t.Seconds), Microseconds: abs(t.Microseconds), Milliseconds: abs(t.Milliseconds), Minutes: abs(t.Minutes), Hours: abs(t.Hours), Weeks: abs(t.Weeks), } }
[ "func", "(", "t", "*", "Timedelta", ")", "Abs", "(", ")", "Timedelta", "{", "return", "Timedelta", "{", "Days", ":", "abs", "(", "t", ".", "Days", ")", ",", "Seconds", ":", "abs", "(", "t", ".", "Seconds", ")", ",", "Microseconds", ":", "abs", "(", "t", ".", "Microseconds", ")", ",", "Milliseconds", ":", "abs", "(", "t", ".", "Milliseconds", ")", ",", "Minutes", ":", "abs", "(", "t", ".", "Minutes", ")", ",", "Hours", ":", "abs", "(", "t", ".", "Hours", ")", ",", "Weeks", ":", "abs", "(", "t", ".", "Weeks", ")", ",", "}", "\n", "}" ]
// Abs returns the absolute value of t
[ "Abs", "returns", "the", "absolute", "value", "of", "t" ]
28917288c48df3d2c1cfe468c273e0b2adda0aa5
https://github.com/leekchan/timeutil/blob/28917288c48df3d2c1cfe468c273e0b2adda0aa5/timedelta.go#L47-L57
908
armon/circbuf
circbuf.go
NewBuffer
func NewBuffer(size int64) (*Buffer, error) { if size <= 0 { return nil, fmt.Errorf("Size must be positive") } b := &Buffer{ size: size, data: make([]byte, size), } return b, nil }
go
func NewBuffer(size int64) (*Buffer, error) { if size <= 0 { return nil, fmt.Errorf("Size must be positive") } b := &Buffer{ size: size, data: make([]byte, size), } return b, nil }
[ "func", "NewBuffer", "(", "size", "int64", ")", "(", "*", "Buffer", ",", "error", ")", "{", "if", "size", "<=", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "b", ":=", "&", "Buffer", "{", "size", ":", "size", ",", "data", ":", "make", "(", "[", "]", "byte", ",", "size", ")", ",", "}", "\n", "return", "b", ",", "nil", "\n", "}" ]
// NewBuffer creates a new buffer of a given size. The size // must be greater than 0.
[ "NewBuffer", "creates", "a", "new", "buffer", "of", "a", "given", "size", ".", "The", "size", "must", "be", "greater", "than", "0", "." ]
5111143e8da2e98b4ea6a8f32b9065ea1821c191
https://github.com/armon/circbuf/blob/5111143e8da2e98b4ea6a8f32b9065ea1821c191/circbuf.go#L20-L30
909
armon/circbuf
circbuf.go
Bytes
func (b *Buffer) Bytes() []byte { switch { case b.written >= b.size && b.writeCursor == 0: return b.data case b.written > b.size: out := make([]byte, b.size) copy(out, b.data[b.writeCursor:]) copy(out[b.size-b.writeCursor:], b.data[:b.writeCursor]) return out default: return b.data[:b.writeCursor] } }
go
func (b *Buffer) Bytes() []byte { switch { case b.written >= b.size && b.writeCursor == 0: return b.data case b.written > b.size: out := make([]byte, b.size) copy(out, b.data[b.writeCursor:]) copy(out[b.size-b.writeCursor:], b.data[:b.writeCursor]) return out default: return b.data[:b.writeCursor] } }
[ "func", "(", "b", "*", "Buffer", ")", "Bytes", "(", ")", "[", "]", "byte", "{", "switch", "{", "case", "b", ".", "written", ">=", "b", ".", "size", "&&", "b", ".", "writeCursor", "==", "0", ":", "return", "b", ".", "data", "\n", "case", "b", ".", "written", ">", "b", ".", "size", ":", "out", ":=", "make", "(", "[", "]", "byte", ",", "b", ".", "size", ")", "\n", "copy", "(", "out", ",", "b", ".", "data", "[", "b", ".", "writeCursor", ":", "]", ")", "\n", "copy", "(", "out", "[", "b", ".", "size", "-", "b", ".", "writeCursor", ":", "]", ",", "b", ".", "data", "[", ":", "b", ".", "writeCursor", "]", ")", "\n", "return", "out", "\n", "default", ":", "return", "b", ".", "data", "[", ":", "b", ".", "writeCursor", "]", "\n", "}", "\n", "}" ]
// Bytes provides a slice of the bytes written. This // slice should not be written to.
[ "Bytes", "provides", "a", "slice", "of", "the", "bytes", "written", ".", "This", "slice", "should", "not", "be", "written", "to", "." ]
5111143e8da2e98b4ea6a8f32b9065ea1821c191
https://github.com/armon/circbuf/blob/5111143e8da2e98b4ea6a8f32b9065ea1821c191/circbuf.go#L69-L81
910
go-playground/universal-translator
translator.go
T
func (t *translator) T(key interface{}, params ...string) (string, error) { trans, ok := t.translations[key] if !ok { return unknownTranslation, ErrUnknowTranslation } b := make([]byte, 0, 64) var start, end, count int for i := 0; i < len(trans.indexes); i++ { end = trans.indexes[i] b = append(b, trans.text[start:end]...) b = append(b, params[count]...) i++ start = trans.indexes[i] count++ } b = append(b, trans.text[start:]...) return string(b), nil }
go
func (t *translator) T(key interface{}, params ...string) (string, error) { trans, ok := t.translations[key] if !ok { return unknownTranslation, ErrUnknowTranslation } b := make([]byte, 0, 64) var start, end, count int for i := 0; i < len(trans.indexes); i++ { end = trans.indexes[i] b = append(b, trans.text[start:end]...) b = append(b, params[count]...) i++ start = trans.indexes[i] count++ } b = append(b, trans.text[start:]...) return string(b), nil }
[ "func", "(", "t", "*", "translator", ")", "T", "(", "key", "interface", "{", "}", ",", "params", "...", "string", ")", "(", "string", ",", "error", ")", "{", "trans", ",", "ok", ":=", "t", ".", "translations", "[", "key", "]", "\n", "if", "!", "ok", "{", "return", "unknownTranslation", ",", "ErrUnknowTranslation", "\n", "}", "\n\n", "b", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "64", ")", "\n\n", "var", "start", ",", "end", ",", "count", "int", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "trans", ".", "indexes", ")", ";", "i", "++", "{", "end", "=", "trans", ".", "indexes", "[", "i", "]", "\n", "b", "=", "append", "(", "b", ",", "trans", ".", "text", "[", "start", ":", "end", "]", "...", ")", "\n", "b", "=", "append", "(", "b", ",", "params", "[", "count", "]", "...", ")", "\n", "i", "++", "\n", "start", "=", "trans", ".", "indexes", "[", "i", "]", "\n", "count", "++", "\n", "}", "\n\n", "b", "=", "append", "(", "b", ",", "trans", ".", "text", "[", "start", ":", "]", "...", ")", "\n\n", "return", "string", "(", "b", ")", ",", "nil", "\n", "}" ]
// T creates the translation for the locale given the 'key' and params passed in
[ "T", "creates", "the", "translation", "for", "the", "locale", "given", "the", "key", "and", "params", "passed", "in" ]
71201497bace774495daed26a3874fd339e0b538
https://github.com/go-playground/universal-translator/blob/71201497bace774495daed26a3874fd339e0b538/translator.go#L297-L320
911
go-playground/universal-translator
translator.go
C
func (t *translator) C(key interface{}, num float64, digits uint64, param string) (string, error) { tarr, ok := t.cardinalTanslations[key] if !ok { return unknownTranslation, ErrUnknowTranslation } rule := t.CardinalPluralRule(num, digits) trans := tarr[rule] b := make([]byte, 0, 64) b = append(b, trans.text[:trans.indexes[0]]...) b = append(b, param...) b = append(b, trans.text[trans.indexes[1]:]...) return string(b), nil }
go
func (t *translator) C(key interface{}, num float64, digits uint64, param string) (string, error) { tarr, ok := t.cardinalTanslations[key] if !ok { return unknownTranslation, ErrUnknowTranslation } rule := t.CardinalPluralRule(num, digits) trans := tarr[rule] b := make([]byte, 0, 64) b = append(b, trans.text[:trans.indexes[0]]...) b = append(b, param...) b = append(b, trans.text[trans.indexes[1]:]...) return string(b), nil }
[ "func", "(", "t", "*", "translator", ")", "C", "(", "key", "interface", "{", "}", ",", "num", "float64", ",", "digits", "uint64", ",", "param", "string", ")", "(", "string", ",", "error", ")", "{", "tarr", ",", "ok", ":=", "t", ".", "cardinalTanslations", "[", "key", "]", "\n", "if", "!", "ok", "{", "return", "unknownTranslation", ",", "ErrUnknowTranslation", "\n", "}", "\n\n", "rule", ":=", "t", ".", "CardinalPluralRule", "(", "num", ",", "digits", ")", "\n\n", "trans", ":=", "tarr", "[", "rule", "]", "\n\n", "b", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "64", ")", "\n", "b", "=", "append", "(", "b", ",", "trans", ".", "text", "[", ":", "trans", ".", "indexes", "[", "0", "]", "]", "...", ")", "\n", "b", "=", "append", "(", "b", ",", "param", "...", ")", "\n", "b", "=", "append", "(", "b", ",", "trans", ".", "text", "[", "trans", ".", "indexes", "[", "1", "]", ":", "]", "...", ")", "\n\n", "return", "string", "(", "b", ")", ",", "nil", "\n", "}" ]
// C creates the cardinal translation for the locale given the 'key', 'num' and 'digit' arguments and param passed in
[ "C", "creates", "the", "cardinal", "translation", "for", "the", "locale", "given", "the", "key", "num", "and", "digit", "arguments", "and", "param", "passed", "in" ]
71201497bace774495daed26a3874fd339e0b538
https://github.com/go-playground/universal-translator/blob/71201497bace774495daed26a3874fd339e0b538/translator.go#L323-L340
912
go-playground/universal-translator
translator.go
O
func (t *translator) O(key interface{}, num float64, digits uint64, param string) (string, error) { tarr, ok := t.ordinalTanslations[key] if !ok { return unknownTranslation, ErrUnknowTranslation } rule := t.OrdinalPluralRule(num, digits) trans := tarr[rule] b := make([]byte, 0, 64) b = append(b, trans.text[:trans.indexes[0]]...) b = append(b, param...) b = append(b, trans.text[trans.indexes[1]:]...) return string(b), nil }
go
func (t *translator) O(key interface{}, num float64, digits uint64, param string) (string, error) { tarr, ok := t.ordinalTanslations[key] if !ok { return unknownTranslation, ErrUnknowTranslation } rule := t.OrdinalPluralRule(num, digits) trans := tarr[rule] b := make([]byte, 0, 64) b = append(b, trans.text[:trans.indexes[0]]...) b = append(b, param...) b = append(b, trans.text[trans.indexes[1]:]...) return string(b), nil }
[ "func", "(", "t", "*", "translator", ")", "O", "(", "key", "interface", "{", "}", ",", "num", "float64", ",", "digits", "uint64", ",", "param", "string", ")", "(", "string", ",", "error", ")", "{", "tarr", ",", "ok", ":=", "t", ".", "ordinalTanslations", "[", "key", "]", "\n", "if", "!", "ok", "{", "return", "unknownTranslation", ",", "ErrUnknowTranslation", "\n", "}", "\n\n", "rule", ":=", "t", ".", "OrdinalPluralRule", "(", "num", ",", "digits", ")", "\n\n", "trans", ":=", "tarr", "[", "rule", "]", "\n\n", "b", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "64", ")", "\n", "b", "=", "append", "(", "b", ",", "trans", ".", "text", "[", ":", "trans", ".", "indexes", "[", "0", "]", "]", "...", ")", "\n", "b", "=", "append", "(", "b", ",", "param", "...", ")", "\n", "b", "=", "append", "(", "b", ",", "trans", ".", "text", "[", "trans", ".", "indexes", "[", "1", "]", ":", "]", "...", ")", "\n\n", "return", "string", "(", "b", ")", ",", "nil", "\n", "}" ]
// O creates the ordinal translation for the locale given the 'key', 'num' and 'digit' arguments and param passed in
[ "O", "creates", "the", "ordinal", "translation", "for", "the", "locale", "given", "the", "key", "num", "and", "digit", "arguments", "and", "param", "passed", "in" ]
71201497bace774495daed26a3874fd339e0b538
https://github.com/go-playground/universal-translator/blob/71201497bace774495daed26a3874fd339e0b538/translator.go#L343-L360
913
go-playground/universal-translator
translator.go
R
func (t *translator) R(key interface{}, num1 float64, digits1 uint64, num2 float64, digits2 uint64, param1, param2 string) (string, error) { tarr, ok := t.rangeTanslations[key] if !ok { return unknownTranslation, ErrUnknowTranslation } rule := t.RangePluralRule(num1, digits1, num2, digits2) trans := tarr[rule] b := make([]byte, 0, 64) b = append(b, trans.text[:trans.indexes[0]]...) b = append(b, param1...) b = append(b, trans.text[trans.indexes[1]:trans.indexes[2]]...) b = append(b, param2...) b = append(b, trans.text[trans.indexes[3]:]...) return string(b), nil }
go
func (t *translator) R(key interface{}, num1 float64, digits1 uint64, num2 float64, digits2 uint64, param1, param2 string) (string, error) { tarr, ok := t.rangeTanslations[key] if !ok { return unknownTranslation, ErrUnknowTranslation } rule := t.RangePluralRule(num1, digits1, num2, digits2) trans := tarr[rule] b := make([]byte, 0, 64) b = append(b, trans.text[:trans.indexes[0]]...) b = append(b, param1...) b = append(b, trans.text[trans.indexes[1]:trans.indexes[2]]...) b = append(b, param2...) b = append(b, trans.text[trans.indexes[3]:]...) return string(b), nil }
[ "func", "(", "t", "*", "translator", ")", "R", "(", "key", "interface", "{", "}", ",", "num1", "float64", ",", "digits1", "uint64", ",", "num2", "float64", ",", "digits2", "uint64", ",", "param1", ",", "param2", "string", ")", "(", "string", ",", "error", ")", "{", "tarr", ",", "ok", ":=", "t", ".", "rangeTanslations", "[", "key", "]", "\n", "if", "!", "ok", "{", "return", "unknownTranslation", ",", "ErrUnknowTranslation", "\n", "}", "\n\n", "rule", ":=", "t", ".", "RangePluralRule", "(", "num1", ",", "digits1", ",", "num2", ",", "digits2", ")", "\n\n", "trans", ":=", "tarr", "[", "rule", "]", "\n\n", "b", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "64", ")", "\n", "b", "=", "append", "(", "b", ",", "trans", ".", "text", "[", ":", "trans", ".", "indexes", "[", "0", "]", "]", "...", ")", "\n", "b", "=", "append", "(", "b", ",", "param1", "...", ")", "\n", "b", "=", "append", "(", "b", ",", "trans", ".", "text", "[", "trans", ".", "indexes", "[", "1", "]", ":", "trans", ".", "indexes", "[", "2", "]", "]", "...", ")", "\n", "b", "=", "append", "(", "b", ",", "param2", "...", ")", "\n", "b", "=", "append", "(", "b", ",", "trans", ".", "text", "[", "trans", ".", "indexes", "[", "3", "]", ":", "]", "...", ")", "\n\n", "return", "string", "(", "b", ")", ",", "nil", "\n", "}" ]
// R creates the range translation for the locale given the 'key', 'num1', 'digit1', 'num2' and 'digit2' arguments // and 'param1' and 'param2' passed in
[ "R", "creates", "the", "range", "translation", "for", "the", "locale", "given", "the", "key", "num1", "digit1", "num2", "and", "digit2", "arguments", "and", "param1", "and", "param2", "passed", "in" ]
71201497bace774495daed26a3874fd339e0b538
https://github.com/go-playground/universal-translator/blob/71201497bace774495daed26a3874fd339e0b538/translator.go#L364-L383
914
go-playground/universal-translator
translator.go
VerifyTranslations
func (t *translator) VerifyTranslations() error { for k, v := range t.cardinalTanslations { for _, rule := range t.PluralsCardinal() { if v[rule] == nil { return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "plural", rule: rule, key: k} } } } for k, v := range t.ordinalTanslations { for _, rule := range t.PluralsOrdinal() { if v[rule] == nil { return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "ordinal", rule: rule, key: k} } } } for k, v := range t.rangeTanslations { for _, rule := range t.PluralsRange() { if v[rule] == nil { return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "range", rule: rule, key: k} } } } return nil }
go
func (t *translator) VerifyTranslations() error { for k, v := range t.cardinalTanslations { for _, rule := range t.PluralsCardinal() { if v[rule] == nil { return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "plural", rule: rule, key: k} } } } for k, v := range t.ordinalTanslations { for _, rule := range t.PluralsOrdinal() { if v[rule] == nil { return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "ordinal", rule: rule, key: k} } } } for k, v := range t.rangeTanslations { for _, rule := range t.PluralsRange() { if v[rule] == nil { return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "range", rule: rule, key: k} } } } return nil }
[ "func", "(", "t", "*", "translator", ")", "VerifyTranslations", "(", ")", "error", "{", "for", "k", ",", "v", ":=", "range", "t", ".", "cardinalTanslations", "{", "for", "_", ",", "rule", ":=", "range", "t", ".", "PluralsCardinal", "(", ")", "{", "if", "v", "[", "rule", "]", "==", "nil", "{", "return", "&", "ErrMissingPluralTranslation", "{", "locale", ":", "t", ".", "Locale", "(", ")", ",", "translationType", ":", "\"", "\"", ",", "rule", ":", "rule", ",", "key", ":", "k", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "for", "k", ",", "v", ":=", "range", "t", ".", "ordinalTanslations", "{", "for", "_", ",", "rule", ":=", "range", "t", ".", "PluralsOrdinal", "(", ")", "{", "if", "v", "[", "rule", "]", "==", "nil", "{", "return", "&", "ErrMissingPluralTranslation", "{", "locale", ":", "t", ".", "Locale", "(", ")", ",", "translationType", ":", "\"", "\"", ",", "rule", ":", "rule", ",", "key", ":", "k", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "for", "k", ",", "v", ":=", "range", "t", ".", "rangeTanslations", "{", "for", "_", ",", "rule", ":=", "range", "t", ".", "PluralsRange", "(", ")", "{", "if", "v", "[", "rule", "]", "==", "nil", "{", "return", "&", "ErrMissingPluralTranslation", "{", "locale", ":", "t", ".", "Locale", "(", ")", ",", "translationType", ":", "\"", "\"", ",", "rule", ":", "rule", ",", "key", ":", "k", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// VerifyTranslations checks to ensures that no plural rules have been // missed within the translations.
[ "VerifyTranslations", "checks", "to", "ensures", "that", "no", "plural", "rules", "have", "been", "missed", "within", "the", "translations", "." ]
71201497bace774495daed26a3874fd339e0b538
https://github.com/go-playground/universal-translator/blob/71201497bace774495daed26a3874fd339e0b538/translator.go#L387-L420
915
go-playground/universal-translator
universal_translator.go
New
func New(fallback locales.Translator, supportedLocales ...locales.Translator) *UniversalTranslator { t := &UniversalTranslator{ translators: make(map[string]Translator), } for _, v := range supportedLocales { trans := newTranslator(v) t.translators[strings.ToLower(trans.Locale())] = trans if fallback.Locale() == v.Locale() { t.fallback = trans } } if t.fallback == nil && fallback != nil { t.fallback = newTranslator(fallback) } return t }
go
func New(fallback locales.Translator, supportedLocales ...locales.Translator) *UniversalTranslator { t := &UniversalTranslator{ translators: make(map[string]Translator), } for _, v := range supportedLocales { trans := newTranslator(v) t.translators[strings.ToLower(trans.Locale())] = trans if fallback.Locale() == v.Locale() { t.fallback = trans } } if t.fallback == nil && fallback != nil { t.fallback = newTranslator(fallback) } return t }
[ "func", "New", "(", "fallback", "locales", ".", "Translator", ",", "supportedLocales", "...", "locales", ".", "Translator", ")", "*", "UniversalTranslator", "{", "t", ":=", "&", "UniversalTranslator", "{", "translators", ":", "make", "(", "map", "[", "string", "]", "Translator", ")", ",", "}", "\n\n", "for", "_", ",", "v", ":=", "range", "supportedLocales", "{", "trans", ":=", "newTranslator", "(", "v", ")", "\n", "t", ".", "translators", "[", "strings", ".", "ToLower", "(", "trans", ".", "Locale", "(", ")", ")", "]", "=", "trans", "\n\n", "if", "fallback", ".", "Locale", "(", ")", "==", "v", ".", "Locale", "(", ")", "{", "t", ".", "fallback", "=", "trans", "\n", "}", "\n", "}", "\n\n", "if", "t", ".", "fallback", "==", "nil", "&&", "fallback", "!=", "nil", "{", "t", ".", "fallback", "=", "newTranslator", "(", "fallback", ")", "\n", "}", "\n\n", "return", "t", "\n", "}" ]
// New returns a new UniversalTranslator instance set with // the fallback locale and locales it should support
[ "New", "returns", "a", "new", "UniversalTranslator", "instance", "set", "with", "the", "fallback", "locale", "and", "locales", "it", "should", "support" ]
71201497bace774495daed26a3874fd339e0b538
https://github.com/go-playground/universal-translator/blob/71201497bace774495daed26a3874fd339e0b538/universal_translator.go#L17-L38
916
go-playground/universal-translator
universal_translator.go
FindTranslator
func (t *UniversalTranslator) FindTranslator(locales ...string) (trans Translator, found bool) { for _, locale := range locales { if trans, found = t.translators[strings.ToLower(locale)]; found { return } } return t.fallback, false }
go
func (t *UniversalTranslator) FindTranslator(locales ...string) (trans Translator, found bool) { for _, locale := range locales { if trans, found = t.translators[strings.ToLower(locale)]; found { return } } return t.fallback, false }
[ "func", "(", "t", "*", "UniversalTranslator", ")", "FindTranslator", "(", "locales", "...", "string", ")", "(", "trans", "Translator", ",", "found", "bool", ")", "{", "for", "_", ",", "locale", ":=", "range", "locales", "{", "if", "trans", ",", "found", "=", "t", ".", "translators", "[", "strings", ".", "ToLower", "(", "locale", ")", "]", ";", "found", "{", "return", "\n", "}", "\n", "}", "\n\n", "return", "t", ".", "fallback", ",", "false", "\n", "}" ]
// FindTranslator trys to find a Translator based on an array of locales // and returns the first one it can find, otherwise returns the // fallback translator.
[ "FindTranslator", "trys", "to", "find", "a", "Translator", "based", "on", "an", "array", "of", "locales", "and", "returns", "the", "first", "one", "it", "can", "find", "otherwise", "returns", "the", "fallback", "translator", "." ]
71201497bace774495daed26a3874fd339e0b538
https://github.com/go-playground/universal-translator/blob/71201497bace774495daed26a3874fd339e0b538/universal_translator.go#L43-L53
917
go-playground/universal-translator
universal_translator.go
GetTranslator
func (t *UniversalTranslator) GetTranslator(locale string) (trans Translator, found bool) { if trans, found = t.translators[strings.ToLower(locale)]; found { return } return t.fallback, false }
go
func (t *UniversalTranslator) GetTranslator(locale string) (trans Translator, found bool) { if trans, found = t.translators[strings.ToLower(locale)]; found { return } return t.fallback, false }
[ "func", "(", "t", "*", "UniversalTranslator", ")", "GetTranslator", "(", "locale", "string", ")", "(", "trans", "Translator", ",", "found", "bool", ")", "{", "if", "trans", ",", "found", "=", "t", ".", "translators", "[", "strings", ".", "ToLower", "(", "locale", ")", "]", ";", "found", "{", "return", "\n", "}", "\n\n", "return", "t", ".", "fallback", ",", "false", "\n", "}" ]
// GetTranslator returns the specified translator for the given locale, // or fallback if not found
[ "GetTranslator", "returns", "the", "specified", "translator", "for", "the", "given", "locale", "or", "fallback", "if", "not", "found" ]
71201497bace774495daed26a3874fd339e0b538
https://github.com/go-playground/universal-translator/blob/71201497bace774495daed26a3874fd339e0b538/universal_translator.go#L57-L64
918
go-playground/universal-translator
universal_translator.go
VerifyTranslations
func (t *UniversalTranslator) VerifyTranslations() (err error) { for _, trans := range t.translators { err = trans.VerifyTranslations() if err != nil { return } } return }
go
func (t *UniversalTranslator) VerifyTranslations() (err error) { for _, trans := range t.translators { err = trans.VerifyTranslations() if err != nil { return } } return }
[ "func", "(", "t", "*", "UniversalTranslator", ")", "VerifyTranslations", "(", ")", "(", "err", "error", ")", "{", "for", "_", ",", "trans", ":=", "range", "t", ".", "translators", "{", "err", "=", "trans", ".", "VerifyTranslations", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n\n", "return", "\n", "}" ]
// VerifyTranslations runs through all locales and identifies any issues // eg. missing plural rules for a locale
[ "VerifyTranslations", "runs", "through", "all", "locales", "and", "identifies", "any", "issues", "eg", ".", "missing", "plural", "rules", "for", "a", "locale" ]
71201497bace774495daed26a3874fd339e0b538
https://github.com/go-playground/universal-translator/blob/71201497bace774495daed26a3874fd339e0b538/universal_translator.go#L103-L113
919
go-playground/universal-translator
errors.go
Error
func (e *ErrConflictingTranslation) Error() string { if _, ok := e.key.(string); !ok { return fmt.Sprintf("error: conflicting key '%#v' rule '%s' with text '%s' for locale '%s', value being ignored", e.key, e.rule, e.text, e.locale) } return fmt.Sprintf("error: conflicting key '%s' rule '%s' with text '%s' for locale '%s', value being ignored", e.key, e.rule, e.text, e.locale) }
go
func (e *ErrConflictingTranslation) Error() string { if _, ok := e.key.(string); !ok { return fmt.Sprintf("error: conflicting key '%#v' rule '%s' with text '%s' for locale '%s', value being ignored", e.key, e.rule, e.text, e.locale) } return fmt.Sprintf("error: conflicting key '%s' rule '%s' with text '%s' for locale '%s', value being ignored", e.key, e.rule, e.text, e.locale) }
[ "func", "(", "e", "*", "ErrConflictingTranslation", ")", "Error", "(", ")", "string", "{", "if", "_", ",", "ok", ":=", "e", ".", "key", ".", "(", "string", ")", ";", "!", "ok", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "key", ",", "e", ".", "rule", ",", "e", ".", "text", ",", "e", ".", "locale", ")", "\n", "}", "\n\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "key", ",", "e", ".", "rule", ",", "e", ".", "text", ",", "e", ".", "locale", ")", "\n", "}" ]
// Error returns ErrConflictingTranslation's internal error text
[ "Error", "returns", "ErrConflictingTranslation", "s", "internal", "error", "text" ]
71201497bace774495daed26a3874fd339e0b538
https://github.com/go-playground/universal-translator/blob/71201497bace774495daed26a3874fd339e0b538/errors.go#L41-L48
920
go-playground/universal-translator
errors.go
Error
func (e *ErrMissingPluralTranslation) Error() string { if _, ok := e.key.(string); !ok { return fmt.Sprintf("error: missing '%s' plural rule '%s' for translation with key '%#v' and locale '%s'", e.translationType, e.rule, e.key, e.locale) } return fmt.Sprintf("error: missing '%s' plural rule '%s' for translation with key '%s' and locale '%s'", e.translationType, e.rule, e.key, e.locale) }
go
func (e *ErrMissingPluralTranslation) Error() string { if _, ok := e.key.(string); !ok { return fmt.Sprintf("error: missing '%s' plural rule '%s' for translation with key '%#v' and locale '%s'", e.translationType, e.rule, e.key, e.locale) } return fmt.Sprintf("error: missing '%s' plural rule '%s' for translation with key '%s' and locale '%s'", e.translationType, e.rule, e.key, e.locale) }
[ "func", "(", "e", "*", "ErrMissingPluralTranslation", ")", "Error", "(", ")", "string", "{", "if", "_", ",", "ok", ":=", "e", ".", "key", ".", "(", "string", ")", ";", "!", "ok", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "translationType", ",", "e", ".", "rule", ",", "e", ".", "key", ",", "e", ".", "locale", ")", "\n", "}", "\n\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "translationType", ",", "e", ".", "rule", ",", "e", ".", "key", ",", "e", ".", "locale", ")", "\n", "}" ]
// Error returns ErrMissingPluralTranslation's internal error text
[ "Error", "returns", "ErrMissingPluralTranslation", "s", "internal", "error", "text" ]
71201497bace774495daed26a3874fd339e0b538
https://github.com/go-playground/universal-translator/blob/71201497bace774495daed26a3874fd339e0b538/errors.go#L90-L97
921
go-playground/universal-translator
errors.go
Error
func (e *ErrMissingBracket) Error() string { return fmt.Sprintf("error: missing bracket '{}', in translation. locale: '%s' key: '%v' text: '%s'", e.locale, e.key, e.text) }
go
func (e *ErrMissingBracket) Error() string { return fmt.Sprintf("error: missing bracket '{}', in translation. locale: '%s' key: '%v' text: '%s'", e.locale, e.key, e.text) }
[ "func", "(", "e", "*", "ErrMissingBracket", ")", "Error", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "locale", ",", "e", ".", "key", ",", "e", ".", "text", ")", "\n", "}" ]
// Error returns ErrMissingBracket error message
[ "Error", "returns", "ErrMissingBracket", "error", "message" ]
71201497bace774495daed26a3874fd339e0b538
https://github.com/go-playground/universal-translator/blob/71201497bace774495daed26a3874fd339e0b538/errors.go#L108-L110
922
go-playground/universal-translator
errors.go
Error
func (e *ErrBadParamSyntax) Error() string { return fmt.Sprintf("error: bad parameter syntax, missing parameter '%s' in translation. locale: '%s' key: '%v' text: '%s'", e.param, e.locale, e.key, e.text) }
go
func (e *ErrBadParamSyntax) Error() string { return fmt.Sprintf("error: bad parameter syntax, missing parameter '%s' in translation. locale: '%s' key: '%v' text: '%s'", e.param, e.locale, e.key, e.text) }
[ "func", "(", "e", "*", "ErrBadParamSyntax", ")", "Error", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "param", ",", "e", ".", "locale", ",", "e", ".", "key", ",", "e", ".", "text", ")", "\n", "}" ]
// Error returns ErrBadParamSyntax error message
[ "Error", "returns", "ErrBadParamSyntax", "error", "message" ]
71201497bace774495daed26a3874fd339e0b538
https://github.com/go-playground/universal-translator/blob/71201497bace774495daed26a3874fd339e0b538/errors.go#L122-L124
923
Redundancy/go-sync
util/readers/sequencelimit.go
SequenceLimit
func SequenceLimit(size int64, readers ...io.Reader) io.Reader { return io.LimitReader( io.MultiReader(readers...), size) }
go
func SequenceLimit(size int64, readers ...io.Reader) io.Reader { return io.LimitReader( io.MultiReader(readers...), size) }
[ "func", "SequenceLimit", "(", "size", "int64", ",", "readers", "...", "io", ".", "Reader", ")", "io", ".", "Reader", "{", "return", "io", ".", "LimitReader", "(", "io", ".", "MultiReader", "(", "readers", "...", ")", ",", "size", ")", "\n", "}" ]
// read from 'readers' in sequence up to a limit of 'size'
[ "read", "from", "readers", "in", "sequence", "up", "to", "a", "limit", "of", "size" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/util/readers/sequencelimit.go#L8-L12
924
Redundancy/go-sync
index/index.go
MakeChecksumIndex
func MakeChecksumIndex(checksums []chunks.ChunkChecksum) *ChecksumIndex { n := &ChecksumIndex{ BlockCount: len(checksums), weakChecksumLookup: make([]map[uint32]StrongChecksumList, 256), } for _, chunk := range checksums { weakChecksumAsInt := binary.LittleEndian.Uint32(chunk.WeakChecksum) arrayOffset := weakChecksumAsInt & 255 if n.weakChecksumLookup[arrayOffset] == nil { n.weakChecksumLookup[arrayOffset] = make(map[uint32]StrongChecksumList) } n.weakChecksumLookup[arrayOffset][weakChecksumAsInt] = append( n.weakChecksumLookup[arrayOffset][weakChecksumAsInt], chunk, ) } sum := 0 count := 0 for _, a := range n.weakChecksumLookup { for _, c := range a { sort.Sort(c) if len(c) > n.MaxStrongLength { n.MaxStrongLength = len(c) } sum += len(c) count += 1 n.Count += len(c) } } n.AverageStrongLength = float32(sum) / float32(count) return n }
go
func MakeChecksumIndex(checksums []chunks.ChunkChecksum) *ChecksumIndex { n := &ChecksumIndex{ BlockCount: len(checksums), weakChecksumLookup: make([]map[uint32]StrongChecksumList, 256), } for _, chunk := range checksums { weakChecksumAsInt := binary.LittleEndian.Uint32(chunk.WeakChecksum) arrayOffset := weakChecksumAsInt & 255 if n.weakChecksumLookup[arrayOffset] == nil { n.weakChecksumLookup[arrayOffset] = make(map[uint32]StrongChecksumList) } n.weakChecksumLookup[arrayOffset][weakChecksumAsInt] = append( n.weakChecksumLookup[arrayOffset][weakChecksumAsInt], chunk, ) } sum := 0 count := 0 for _, a := range n.weakChecksumLookup { for _, c := range a { sort.Sort(c) if len(c) > n.MaxStrongLength { n.MaxStrongLength = len(c) } sum += len(c) count += 1 n.Count += len(c) } } n.AverageStrongLength = float32(sum) / float32(count) return n }
[ "func", "MakeChecksumIndex", "(", "checksums", "[", "]", "chunks", ".", "ChunkChecksum", ")", "*", "ChecksumIndex", "{", "n", ":=", "&", "ChecksumIndex", "{", "BlockCount", ":", "len", "(", "checksums", ")", ",", "weakChecksumLookup", ":", "make", "(", "[", "]", "map", "[", "uint32", "]", "StrongChecksumList", ",", "256", ")", ",", "}", "\n\n", "for", "_", ",", "chunk", ":=", "range", "checksums", "{", "weakChecksumAsInt", ":=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "chunk", ".", "WeakChecksum", ")", "\n", "arrayOffset", ":=", "weakChecksumAsInt", "&", "255", "\n\n", "if", "n", ".", "weakChecksumLookup", "[", "arrayOffset", "]", "==", "nil", "{", "n", ".", "weakChecksumLookup", "[", "arrayOffset", "]", "=", "make", "(", "map", "[", "uint32", "]", "StrongChecksumList", ")", "\n", "}", "\n\n", "n", ".", "weakChecksumLookup", "[", "arrayOffset", "]", "[", "weakChecksumAsInt", "]", "=", "append", "(", "n", ".", "weakChecksumLookup", "[", "arrayOffset", "]", "[", "weakChecksumAsInt", "]", ",", "chunk", ",", ")", "\n\n", "}", "\n\n", "sum", ":=", "0", "\n", "count", ":=", "0", "\n\n", "for", "_", ",", "a", ":=", "range", "n", ".", "weakChecksumLookup", "{", "for", "_", ",", "c", ":=", "range", "a", "{", "sort", ".", "Sort", "(", "c", ")", "\n", "if", "len", "(", "c", ")", ">", "n", ".", "MaxStrongLength", "{", "n", ".", "MaxStrongLength", "=", "len", "(", "c", ")", "\n", "}", "\n", "sum", "+=", "len", "(", "c", ")", "\n", "count", "+=", "1", "\n", "n", ".", "Count", "+=", "len", "(", "c", ")", "\n", "}", "\n", "}", "\n\n", "n", ".", "AverageStrongLength", "=", "float32", "(", "sum", ")", "/", "float32", "(", "count", ")", "\n\n", "return", "n", "\n", "}" ]
// Builds an index in which chunks can be found, with their corresponding offsets // We use this for the
[ "Builds", "an", "index", "in", "which", "chunks", "can", "be", "found", "with", "their", "corresponding", "offsets", "We", "use", "this", "for", "the" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/index/index.go#L52-L91
925
Redundancy/go-sync
blocksources/fixed_size_block_resolver.go
SplitBlockRangeToDesiredSize
func (r *FixedSizeBlockResolver) SplitBlockRangeToDesiredSize(startBlockID, endBlockID uint) []QueuedRequest { if r.MaxDesiredRequestSize == 0 { return []QueuedRequest{ QueuedRequest{ StartBlockID: startBlockID, EndBlockID: endBlockID, }, } } maxSize := r.MaxDesiredRequestSize if r.MaxDesiredRequestSize < r.BlockSize { maxSize = r.BlockSize } // how many blocks is the desired size? blockCountPerRequest := uint(maxSize / r.BlockSize) requests := make([]QueuedRequest, 0, (endBlockID-startBlockID)/blockCountPerRequest+1) currentBlockID := startBlockID for { maxEndBlock := currentBlockID + blockCountPerRequest if maxEndBlock > endBlockID { requests = append( requests, QueuedRequest{ StartBlockID: currentBlockID, EndBlockID: endBlockID, }, ) return requests } else { requests = append( requests, QueuedRequest{ StartBlockID: currentBlockID, EndBlockID: maxEndBlock - 1, }, ) currentBlockID = maxEndBlock } } }
go
func (r *FixedSizeBlockResolver) SplitBlockRangeToDesiredSize(startBlockID, endBlockID uint) []QueuedRequest { if r.MaxDesiredRequestSize == 0 { return []QueuedRequest{ QueuedRequest{ StartBlockID: startBlockID, EndBlockID: endBlockID, }, } } maxSize := r.MaxDesiredRequestSize if r.MaxDesiredRequestSize < r.BlockSize { maxSize = r.BlockSize } // how many blocks is the desired size? blockCountPerRequest := uint(maxSize / r.BlockSize) requests := make([]QueuedRequest, 0, (endBlockID-startBlockID)/blockCountPerRequest+1) currentBlockID := startBlockID for { maxEndBlock := currentBlockID + blockCountPerRequest if maxEndBlock > endBlockID { requests = append( requests, QueuedRequest{ StartBlockID: currentBlockID, EndBlockID: endBlockID, }, ) return requests } else { requests = append( requests, QueuedRequest{ StartBlockID: currentBlockID, EndBlockID: maxEndBlock - 1, }, ) currentBlockID = maxEndBlock } } }
[ "func", "(", "r", "*", "FixedSizeBlockResolver", ")", "SplitBlockRangeToDesiredSize", "(", "startBlockID", ",", "endBlockID", "uint", ")", "[", "]", "QueuedRequest", "{", "if", "r", ".", "MaxDesiredRequestSize", "==", "0", "{", "return", "[", "]", "QueuedRequest", "{", "QueuedRequest", "{", "StartBlockID", ":", "startBlockID", ",", "EndBlockID", ":", "endBlockID", ",", "}", ",", "}", "\n", "}", "\n\n", "maxSize", ":=", "r", ".", "MaxDesiredRequestSize", "\n", "if", "r", ".", "MaxDesiredRequestSize", "<", "r", ".", "BlockSize", "{", "maxSize", "=", "r", ".", "BlockSize", "\n", "}", "\n\n", "// how many blocks is the desired size?", "blockCountPerRequest", ":=", "uint", "(", "maxSize", "/", "r", ".", "BlockSize", ")", "\n\n", "requests", ":=", "make", "(", "[", "]", "QueuedRequest", ",", "0", ",", "(", "endBlockID", "-", "startBlockID", ")", "/", "blockCountPerRequest", "+", "1", ")", "\n", "currentBlockID", ":=", "startBlockID", "\n\n", "for", "{", "maxEndBlock", ":=", "currentBlockID", "+", "blockCountPerRequest", "\n\n", "if", "maxEndBlock", ">", "endBlockID", "{", "requests", "=", "append", "(", "requests", ",", "QueuedRequest", "{", "StartBlockID", ":", "currentBlockID", ",", "EndBlockID", ":", "endBlockID", ",", "}", ",", ")", "\n\n", "return", "requests", "\n", "}", "else", "{", "requests", "=", "append", "(", "requests", ",", "QueuedRequest", "{", "StartBlockID", ":", "currentBlockID", ",", "EndBlockID", ":", "maxEndBlock", "-", "1", ",", "}", ",", ")", "\n\n", "currentBlockID", "=", "maxEndBlock", "\n", "}", "\n", "}", "\n", "}" ]
// Split blocks into chunks of the desired size, or less. This implementation assumes a fixed block size at the source.
[ "Split", "blocks", "into", "chunks", "of", "the", "desired", "size", "or", "less", ".", "This", "implementation", "assumes", "a", "fixed", "block", "size", "at", "the", "source", "." ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/blocksources/fixed_size_block_resolver.go#L26-L73
926
Redundancy/go-sync
util/readers/injectedreader.go
InjectedReader
func InjectedReader( offsetFromStart int64, base io.Reader, inject io.Reader, ) io.Reader { return io.MultiReader( io.LimitReader(base, offsetFromStart), inject, base, ) }
go
func InjectedReader( offsetFromStart int64, base io.Reader, inject io.Reader, ) io.Reader { return io.MultiReader( io.LimitReader(base, offsetFromStart), inject, base, ) }
[ "func", "InjectedReader", "(", "offsetFromStart", "int64", ",", "base", "io", ".", "Reader", ",", "inject", "io", ".", "Reader", ",", ")", "io", ".", "Reader", "{", "return", "io", ".", "MultiReader", "(", "io", ".", "LimitReader", "(", "base", ",", "offsetFromStart", ")", ",", "inject", ",", "base", ",", ")", "\n", "}" ]
// Injects the second reader into the first at an offset
[ "Injects", "the", "second", "reader", "into", "the", "first", "at", "an", "offset" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/util/readers/injectedreader.go#L8-L18
927
Redundancy/go-sync
rollsum/rollsum_32_base.go
AddByte
func (r *Rollsum32Base) AddByte(b byte) { r.a += uint32(b) r.b += r.a }
go
func (r *Rollsum32Base) AddByte(b byte) { r.a += uint32(b) r.b += r.a }
[ "func", "(", "r", "*", "Rollsum32Base", ")", "AddByte", "(", "b", "byte", ")", "{", "r", ".", "a", "+=", "uint32", "(", "b", ")", "\n", "r", ".", "b", "+=", "r", ".", "a", "\n", "}" ]
// Add a single byte into the rollsum
[ "Add", "a", "single", "byte", "into", "the", "rollsum" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/rollsum/rollsum_32_base.go#L25-L28
928
Redundancy/go-sync
rollsum/rollsum_32_base.go
SetBlock
func (r *Rollsum32Base) SetBlock(block []byte) { r.Reset() r.AddBytes(block) }
go
func (r *Rollsum32Base) SetBlock(block []byte) { r.Reset() r.AddBytes(block) }
[ "func", "(", "r", "*", "Rollsum32Base", ")", "SetBlock", "(", "block", "[", "]", "byte", ")", "{", "r", ".", "Reset", "(", ")", "\n", "r", ".", "AddBytes", "(", "block", ")", "\n", "}" ]
// Set a whole block of blockSize
[ "Set", "a", "whole", "block", "of", "blockSize" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/rollsum/rollsum_32_base.go#L67-L70
929
Redundancy/go-sync
rollsum/rollsum_32_base.go
GetSum
func (r *Rollsum32Base) GetSum(b []byte) { value := uint32((r.a & FULL_BYTES_16) + ((r.b & FULL_BYTES_16) << 16)) binary.LittleEndian.PutUint32(b, value) }
go
func (r *Rollsum32Base) GetSum(b []byte) { value := uint32((r.a & FULL_BYTES_16) + ((r.b & FULL_BYTES_16) << 16)) binary.LittleEndian.PutUint32(b, value) }
[ "func", "(", "r", "*", "Rollsum32Base", ")", "GetSum", "(", "b", "[", "]", "byte", ")", "{", "value", ":=", "uint32", "(", "(", "r", ".", "a", "&", "FULL_BYTES_16", ")", "+", "(", "(", "r", ".", "b", "&", "FULL_BYTES_16", ")", "<<", "16", ")", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "b", ",", "value", ")", "\n", "}" ]
// Puts the sum into b. Avoids allocation. b must have length >= 4
[ "Puts", "the", "sum", "into", "b", ".", "Avoids", "allocation", ".", "b", "must", "have", "length", ">", "=", "4" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/rollsum/rollsum_32_base.go#L83-L86
930
Redundancy/go-sync
circularbuffer/noalloc.go
Write
func (c *C2) Write(b []byte) { c.a.Write(b) c.b.Write(b) c.lastWritten = len(b) c.totalWritten += c.lastWritten }
go
func (c *C2) Write(b []byte) { c.a.Write(b) c.b.Write(b) c.lastWritten = len(b) c.totalWritten += c.lastWritten }
[ "func", "(", "c", "*", "C2", ")", "Write", "(", "b", "[", "]", "byte", ")", "{", "c", ".", "a", ".", "Write", "(", "b", ")", "\n", "c", ".", "b", ".", "Write", "(", "b", ")", "\n", "c", ".", "lastWritten", "=", "len", "(", "b", ")", "\n", "c", ".", "totalWritten", "+=", "c", ".", "lastWritten", "\n", "}" ]
// Write new data
[ "Write", "new", "data" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/circularbuffer/noalloc.go#L61-L66
931
Redundancy/go-sync
circularbuffer/noalloc.go
maxWritten
func (c *C2) maxWritten() int { if c.totalWritten < c.blocksize { return c.totalWritten } return c.blocksize }
go
func (c *C2) maxWritten() int { if c.totalWritten < c.blocksize { return c.totalWritten } return c.blocksize }
[ "func", "(", "c", "*", "C2", ")", "maxWritten", "(", ")", "int", "{", "if", "c", ".", "totalWritten", "<", "c", ".", "blocksize", "{", "return", "c", ".", "totalWritten", "\n", "}", "\n\n", "return", "c", ".", "blocksize", "\n", "}" ]
// the total written, up to the blocksize
[ "the", "total", "written", "up", "to", "the", "blocksize" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/circularbuffer/noalloc.go#L78-L84
932
Redundancy/go-sync
circularbuffer/noalloc.go
Truncate
func (c *C2) Truncate(byteCount int) (evicted []byte) { max := c.maxWritten() if byteCount > max { byteCount = max } bufferToRead := c.getBlockBuffer() start := bufferToRead.head - max c.totalWritten = c.maxWritten() - byteCount return bufferToRead.buffer[start : start+byteCount] }
go
func (c *C2) Truncate(byteCount int) (evicted []byte) { max := c.maxWritten() if byteCount > max { byteCount = max } bufferToRead := c.getBlockBuffer() start := bufferToRead.head - max c.totalWritten = c.maxWritten() - byteCount return bufferToRead.buffer[start : start+byteCount] }
[ "func", "(", "c", "*", "C2", ")", "Truncate", "(", "byteCount", "int", ")", "(", "evicted", "[", "]", "byte", ")", "{", "max", ":=", "c", ".", "maxWritten", "(", ")", "\n\n", "if", "byteCount", ">", "max", "{", "byteCount", "=", "max", "\n", "}", "\n\n", "bufferToRead", ":=", "c", ".", "getBlockBuffer", "(", ")", "\n", "start", ":=", "bufferToRead", ".", "head", "-", "max", "\n\n", "c", ".", "totalWritten", "=", "c", ".", "maxWritten", "(", ")", "-", "byteCount", "\n", "return", "bufferToRead", ".", "buffer", "[", "start", ":", "start", "+", "byteCount", "]", "\n", "}" ]
// Shortens the content of the circular buffer // and returns the content removed
[ "Shortens", "the", "content", "of", "the", "circular", "buffer", "and", "returns", "the", "content", "removed" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/circularbuffer/noalloc.go#L96-L108
933
Redundancy/go-sync
circularbuffer/noalloc.go
GetBlock
func (c *C2) GetBlock() []byte { // figure out which buffer has it stored contiguously bufferToRead := c.getBlockBuffer() start := bufferToRead.head - c.maxWritten() return bufferToRead.buffer[start:bufferToRead.head] }
go
func (c *C2) GetBlock() []byte { // figure out which buffer has it stored contiguously bufferToRead := c.getBlockBuffer() start := bufferToRead.head - c.maxWritten() return bufferToRead.buffer[start:bufferToRead.head] }
[ "func", "(", "c", "*", "C2", ")", "GetBlock", "(", ")", "[", "]", "byte", "{", "// figure out which buffer has it stored contiguously", "bufferToRead", ":=", "c", ".", "getBlockBuffer", "(", ")", "\n", "start", ":=", "bufferToRead", ".", "head", "-", "c", ".", "maxWritten", "(", ")", "\n\n", "return", "bufferToRead", ".", "buffer", "[", "start", ":", "bufferToRead", ".", "head", "]", "\n", "}" ]
// get the current buffer contents of block
[ "get", "the", "current", "buffer", "contents", "of", "block" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/circularbuffer/noalloc.go#L111-L117
934
Redundancy/go-sync
circularbuffer/noalloc.go
Evicted
func (c *C2) Evicted() []byte { if c.totalWritten <= c.blocksize { return nil } bufferToRead := c.a if c.b.head < c.a.head { bufferToRead = c.b } bufferStart := bufferToRead.head + c.blocksize readLength := c.lastWritten // if the buffer wasn't full, we don't read the full length if c.totalWritten-c.lastWritten < c.blocksize { readLength -= c.lastWritten - c.totalWritten + c.blocksize } return bufferToRead.buffer[bufferStart-readLength : bufferStart] }
go
func (c *C2) Evicted() []byte { if c.totalWritten <= c.blocksize { return nil } bufferToRead := c.a if c.b.head < c.a.head { bufferToRead = c.b } bufferStart := bufferToRead.head + c.blocksize readLength := c.lastWritten // if the buffer wasn't full, we don't read the full length if c.totalWritten-c.lastWritten < c.blocksize { readLength -= c.lastWritten - c.totalWritten + c.blocksize } return bufferToRead.buffer[bufferStart-readLength : bufferStart] }
[ "func", "(", "c", "*", "C2", ")", "Evicted", "(", ")", "[", "]", "byte", "{", "if", "c", ".", "totalWritten", "<=", "c", ".", "blocksize", "{", "return", "nil", "\n", "}", "\n\n", "bufferToRead", ":=", "c", ".", "a", "\n", "if", "c", ".", "b", ".", "head", "<", "c", ".", "a", ".", "head", "{", "bufferToRead", "=", "c", ".", "b", "\n", "}", "\n\n", "bufferStart", ":=", "bufferToRead", ".", "head", "+", "c", ".", "blocksize", "\n", "readLength", ":=", "c", ".", "lastWritten", "\n\n", "// if the buffer wasn't full, we don't read the full length", "if", "c", ".", "totalWritten", "-", "c", ".", "lastWritten", "<", "c", ".", "blocksize", "{", "readLength", "-=", "c", ".", "lastWritten", "-", "c", ".", "totalWritten", "+", "c", ".", "blocksize", "\n", "}", "\n\n", "return", "bufferToRead", ".", "buffer", "[", "bufferStart", "-", "readLength", ":", "bufferStart", "]", "\n", "}" ]
// get the data that was evicted by the last write
[ "get", "the", "data", "that", "was", "evicted", "by", "the", "last", "write" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/circularbuffer/noalloc.go#L120-L139
935
Redundancy/go-sync
chunks/chunks.go
Match
func (chunk ChunkChecksum) Match(other ChunkChecksum) bool { weakEqual := bytes.Compare(chunk.WeakChecksum, other.WeakChecksum) == 0 strongEqual := false if weakEqual { strongEqual = bytes.Compare(chunk.StrongChecksum, other.StrongChecksum) == 0 } return weakEqual && strongEqual }
go
func (chunk ChunkChecksum) Match(other ChunkChecksum) bool { weakEqual := bytes.Compare(chunk.WeakChecksum, other.WeakChecksum) == 0 strongEqual := false if weakEqual { strongEqual = bytes.Compare(chunk.StrongChecksum, other.StrongChecksum) == 0 } return weakEqual && strongEqual }
[ "func", "(", "chunk", "ChunkChecksum", ")", "Match", "(", "other", "ChunkChecksum", ")", "bool", "{", "weakEqual", ":=", "bytes", ".", "Compare", "(", "chunk", ".", "WeakChecksum", ",", "other", ".", "WeakChecksum", ")", "==", "0", "\n", "strongEqual", ":=", "false", "\n", "if", "weakEqual", "{", "strongEqual", "=", "bytes", ".", "Compare", "(", "chunk", ".", "StrongChecksum", ",", "other", ".", "StrongChecksum", ")", "==", "0", "\n", "}", "\n", "return", "weakEqual", "&&", "strongEqual", "\n", "}" ]
// compares a checksum to another based on the checksums, not the offset
[ "compares", "a", "checksum", "to", "another", "based", "on", "the", "checksums", "not", "the", "offset" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/chunks/chunks.go#L26-L33
936
Redundancy/go-sync
chunks/chunks.go
LoadChecksumsFromReader
func LoadChecksumsFromReader( r io.Reader, weakHashSize int, strongHashSize int, ) ([]ChunkChecksum, error) { result := make([]ChunkChecksum, 0, 20) offset := uint(0) temp := ChunkChecksum{} for { weakBuffer := make([]byte, weakHashSize) n, err := io.ReadFull(r, weakBuffer) if n == weakHashSize { temp.ChunkOffset = offset temp.WeakChecksum = weakBuffer } else if n == 0 && err == io.EOF { break } else { return nil, ErrPartialChecksum } strongBuffer := make([]byte, strongHashSize) n, err = io.ReadFull(r, strongBuffer) if n == strongHashSize { temp.StrongChecksum = strongBuffer result = append(result, temp) if err == io.EOF { break } } else { return nil, ErrPartialChecksum } offset += 1 } return result, nil }
go
func LoadChecksumsFromReader( r io.Reader, weakHashSize int, strongHashSize int, ) ([]ChunkChecksum, error) { result := make([]ChunkChecksum, 0, 20) offset := uint(0) temp := ChunkChecksum{} for { weakBuffer := make([]byte, weakHashSize) n, err := io.ReadFull(r, weakBuffer) if n == weakHashSize { temp.ChunkOffset = offset temp.WeakChecksum = weakBuffer } else if n == 0 && err == io.EOF { break } else { return nil, ErrPartialChecksum } strongBuffer := make([]byte, strongHashSize) n, err = io.ReadFull(r, strongBuffer) if n == strongHashSize { temp.StrongChecksum = strongBuffer result = append(result, temp) if err == io.EOF { break } } else { return nil, ErrPartialChecksum } offset += 1 } return result, nil }
[ "func", "LoadChecksumsFromReader", "(", "r", "io", ".", "Reader", ",", "weakHashSize", "int", ",", "strongHashSize", "int", ",", ")", "(", "[", "]", "ChunkChecksum", ",", "error", ")", "{", "result", ":=", "make", "(", "[", "]", "ChunkChecksum", ",", "0", ",", "20", ")", "\n", "offset", ":=", "uint", "(", "0", ")", "\n\n", "temp", ":=", "ChunkChecksum", "{", "}", "\n\n", "for", "{", "weakBuffer", ":=", "make", "(", "[", "]", "byte", ",", "weakHashSize", ")", "\n", "n", ",", "err", ":=", "io", ".", "ReadFull", "(", "r", ",", "weakBuffer", ")", "\n\n", "if", "n", "==", "weakHashSize", "{", "temp", ".", "ChunkOffset", "=", "offset", "\n", "temp", ".", "WeakChecksum", "=", "weakBuffer", "\n", "}", "else", "if", "n", "==", "0", "&&", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "else", "{", "return", "nil", ",", "ErrPartialChecksum", "\n", "}", "\n\n", "strongBuffer", ":=", "make", "(", "[", "]", "byte", ",", "strongHashSize", ")", "\n", "n", ",", "err", "=", "io", ".", "ReadFull", "(", "r", ",", "strongBuffer", ")", "\n\n", "if", "n", "==", "strongHashSize", "{", "temp", ".", "StrongChecksum", "=", "strongBuffer", "\n", "result", "=", "append", "(", "result", ",", "temp", ")", "\n\n", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "\n", "}", "else", "{", "return", "nil", ",", "ErrPartialChecksum", "\n", "}", "\n\n", "offset", "+=", "1", "\n", "}", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// Loads chunks from a reader, assuming alternating weak then strong hashes
[ "Loads", "chunks", "from", "a", "reader", "assuming", "alternating", "weak", "then", "strong", "hashes" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/chunks/chunks.go#L38-L80
937
Redundancy/go-sync
rsync.go
MakeRSync
func MakeRSync( InputFile, Source, OutFile string, Summary FileSummary, ) (r *RSync, err error) { useTempFile := false if useTempFile, err = IsSameFile(InputFile, OutFile); err != nil { return nil, err } inputFile, err := os.Open(InputFile) if err != nil { return } var out io.WriteCloser var outFilename = OutFile var copier closer if useTempFile { out, outFilename, err = getTempFile() if err != nil { return } copier = &fileCopyCloser{ from: outFilename, to: OutFile, } } else { out, err = getOutFile(OutFile) if err != nil { return } copier = nullCloser{} } // blocksource var source *blocksources.BlockSourceBase resolver := blocksources.MakeFileSizedBlockResolver( uint64(Summary.GetBlockSize()), Summary.GetFileSize(), ) source = blocksources.NewHttpBlockSource( Source, DefaultConcurrency, resolver, &filechecksum.HashVerifier{ Hash: md5.New(), BlockSize: Summary.GetBlockSize(), BlockChecksumGetter: Summary, }, ) r = &RSync{ Input: inputFile, Output: out, Source: source, Summary: Summary, OnClose: []closer{ &fileCloser{inputFile, InputFile}, &fileCloser{out, outFilename}, copier, }, } return }
go
func MakeRSync( InputFile, Source, OutFile string, Summary FileSummary, ) (r *RSync, err error) { useTempFile := false if useTempFile, err = IsSameFile(InputFile, OutFile); err != nil { return nil, err } inputFile, err := os.Open(InputFile) if err != nil { return } var out io.WriteCloser var outFilename = OutFile var copier closer if useTempFile { out, outFilename, err = getTempFile() if err != nil { return } copier = &fileCopyCloser{ from: outFilename, to: OutFile, } } else { out, err = getOutFile(OutFile) if err != nil { return } copier = nullCloser{} } // blocksource var source *blocksources.BlockSourceBase resolver := blocksources.MakeFileSizedBlockResolver( uint64(Summary.GetBlockSize()), Summary.GetFileSize(), ) source = blocksources.NewHttpBlockSource( Source, DefaultConcurrency, resolver, &filechecksum.HashVerifier{ Hash: md5.New(), BlockSize: Summary.GetBlockSize(), BlockChecksumGetter: Summary, }, ) r = &RSync{ Input: inputFile, Output: out, Source: source, Summary: Summary, OnClose: []closer{ &fileCloser{inputFile, InputFile}, &fileCloser{out, outFilename}, copier, }, } return }
[ "func", "MakeRSync", "(", "InputFile", ",", "Source", ",", "OutFile", "string", ",", "Summary", "FileSummary", ",", ")", "(", "r", "*", "RSync", ",", "err", "error", ")", "{", "useTempFile", ":=", "false", "\n", "if", "useTempFile", ",", "err", "=", "IsSameFile", "(", "InputFile", ",", "OutFile", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "inputFile", ",", "err", ":=", "os", ".", "Open", "(", "InputFile", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "var", "out", "io", ".", "WriteCloser", "\n", "var", "outFilename", "=", "OutFile", "\n", "var", "copier", "closer", "\n\n", "if", "useTempFile", "{", "out", ",", "outFilename", ",", "err", "=", "getTempFile", "(", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "copier", "=", "&", "fileCopyCloser", "{", "from", ":", "outFilename", ",", "to", ":", "OutFile", ",", "}", "\n", "}", "else", "{", "out", ",", "err", "=", "getOutFile", "(", "OutFile", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "copier", "=", "nullCloser", "{", "}", "\n", "}", "\n\n", "// blocksource", "var", "source", "*", "blocksources", ".", "BlockSourceBase", "\n\n", "resolver", ":=", "blocksources", ".", "MakeFileSizedBlockResolver", "(", "uint64", "(", "Summary", ".", "GetBlockSize", "(", ")", ")", ",", "Summary", ".", "GetFileSize", "(", ")", ",", ")", "\n\n", "source", "=", "blocksources", ".", "NewHttpBlockSource", "(", "Source", ",", "DefaultConcurrency", ",", "resolver", ",", "&", "filechecksum", ".", "HashVerifier", "{", "Hash", ":", "md5", ".", "New", "(", ")", ",", "BlockSize", ":", "Summary", ".", "GetBlockSize", "(", ")", ",", "BlockChecksumGetter", ":", "Summary", ",", "}", ",", ")", "\n\n", "r", "=", "&", "RSync", "{", "Input", ":", "inputFile", ",", "Output", ":", "out", ",", "Source", ":", "source", ",", "Summary", ":", "Summary", ",", "OnClose", ":", "[", "]", "closer", "{", "&", "fileCloser", "{", "inputFile", ",", "InputFile", "}", ",", "&", "fileCloser", "{", "out", ",", "outFilename", "}", ",", "copier", ",", "}", ",", "}", "\n\n", "return", "\n", "}" ]
// MakeRSync creates an RSync object using string paths, // inferring most of the configuration
[ "MakeRSync", "creates", "an", "RSync", "object", "using", "string", "paths", "inferring", "most", "of", "the", "configuration" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/rsync.go#L94-L168
938
Redundancy/go-sync
rsync.go
Patch
func (rsync *RSync) Patch() (err error) { numMatchers := int64(DefaultConcurrency) blockSize := rsync.Summary.GetBlockSize() sectionSize := rsync.Summary.GetFileSize() / numMatchers sectionSize += int64(blockSize) - (sectionSize % int64(blockSize)) merger := &comparer.MatchMerger{} for i := int64(0); i < numMatchers; i++ { compare := &comparer.Comparer{} offset := sectionSize * i sectionReader := bufio.NewReaderSize( io.NewSectionReader(rsync.Input, offset, sectionSize+int64(blockSize)), megabyte, // 1 MB buffer ) // Bakes in the assumption about how to generate checksums (extract) sectionGenerator := filechecksum.NewFileChecksumGenerator( uint(blockSize), ) matchStream := compare.StartFindMatchingBlocks( sectionReader, offset, sectionGenerator, rsync.Summary, ) merger.StartMergeResultStream(matchStream, int64(blockSize)) } mergedBlocks := merger.GetMergedBlocks() missing := mergedBlocks.GetMissingBlocks(rsync.Summary.GetBlockCount() - 1) return sequential.SequentialPatcher( rsync.Input, rsync.Source, toPatcherMissingSpan(missing, int64(blockSize)), toPatcherFoundSpan(mergedBlocks, int64(blockSize)), 20*megabyte, rsync.Output, ) }
go
func (rsync *RSync) Patch() (err error) { numMatchers := int64(DefaultConcurrency) blockSize := rsync.Summary.GetBlockSize() sectionSize := rsync.Summary.GetFileSize() / numMatchers sectionSize += int64(blockSize) - (sectionSize % int64(blockSize)) merger := &comparer.MatchMerger{} for i := int64(0); i < numMatchers; i++ { compare := &comparer.Comparer{} offset := sectionSize * i sectionReader := bufio.NewReaderSize( io.NewSectionReader(rsync.Input, offset, sectionSize+int64(blockSize)), megabyte, // 1 MB buffer ) // Bakes in the assumption about how to generate checksums (extract) sectionGenerator := filechecksum.NewFileChecksumGenerator( uint(blockSize), ) matchStream := compare.StartFindMatchingBlocks( sectionReader, offset, sectionGenerator, rsync.Summary, ) merger.StartMergeResultStream(matchStream, int64(blockSize)) } mergedBlocks := merger.GetMergedBlocks() missing := mergedBlocks.GetMissingBlocks(rsync.Summary.GetBlockCount() - 1) return sequential.SequentialPatcher( rsync.Input, rsync.Source, toPatcherMissingSpan(missing, int64(blockSize)), toPatcherFoundSpan(mergedBlocks, int64(blockSize)), 20*megabyte, rsync.Output, ) }
[ "func", "(", "rsync", "*", "RSync", ")", "Patch", "(", ")", "(", "err", "error", ")", "{", "numMatchers", ":=", "int64", "(", "DefaultConcurrency", ")", "\n", "blockSize", ":=", "rsync", ".", "Summary", ".", "GetBlockSize", "(", ")", "\n", "sectionSize", ":=", "rsync", ".", "Summary", ".", "GetFileSize", "(", ")", "/", "numMatchers", "\n", "sectionSize", "+=", "int64", "(", "blockSize", ")", "-", "(", "sectionSize", "%", "int64", "(", "blockSize", ")", ")", "\n\n", "merger", ":=", "&", "comparer", ".", "MatchMerger", "{", "}", "\n\n", "for", "i", ":=", "int64", "(", "0", ")", ";", "i", "<", "numMatchers", ";", "i", "++", "{", "compare", ":=", "&", "comparer", ".", "Comparer", "{", "}", "\n", "offset", ":=", "sectionSize", "*", "i", "\n\n", "sectionReader", ":=", "bufio", ".", "NewReaderSize", "(", "io", ".", "NewSectionReader", "(", "rsync", ".", "Input", ",", "offset", ",", "sectionSize", "+", "int64", "(", "blockSize", ")", ")", ",", "megabyte", ",", "// 1 MB buffer", ")", "\n\n", "// Bakes in the assumption about how to generate checksums (extract)", "sectionGenerator", ":=", "filechecksum", ".", "NewFileChecksumGenerator", "(", "uint", "(", "blockSize", ")", ",", ")", "\n\n", "matchStream", ":=", "compare", ".", "StartFindMatchingBlocks", "(", "sectionReader", ",", "offset", ",", "sectionGenerator", ",", "rsync", ".", "Summary", ",", ")", "\n\n", "merger", ".", "StartMergeResultStream", "(", "matchStream", ",", "int64", "(", "blockSize", ")", ")", "\n", "}", "\n\n", "mergedBlocks", ":=", "merger", ".", "GetMergedBlocks", "(", ")", "\n", "missing", ":=", "mergedBlocks", ".", "GetMissingBlocks", "(", "rsync", ".", "Summary", ".", "GetBlockCount", "(", ")", "-", "1", ")", "\n\n", "return", "sequential", ".", "SequentialPatcher", "(", "rsync", ".", "Input", ",", "rsync", ".", "Source", ",", "toPatcherMissingSpan", "(", "missing", ",", "int64", "(", "blockSize", ")", ")", ",", "toPatcherFoundSpan", "(", "mergedBlocks", ",", "int64", "(", "blockSize", ")", ")", ",", "20", "*", "megabyte", ",", "rsync", ".", "Output", ",", ")", "\n", "}" ]
// Patch the files
[ "Patch", "the", "files" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/rsync.go#L171-L211
939
Redundancy/go-sync
rsync.go
IsSameFile
func IsSameFile(path1, path2 string) (same bool, err error) { fi1, err := os.Stat(path1) switch { case os.IsNotExist(err): return false, nil case err != nil: return } fi2, err := os.Stat(path2) switch { case os.IsNotExist(err): return false, nil case err != nil: return } return os.SameFile(fi1, fi2), nil }
go
func IsSameFile(path1, path2 string) (same bool, err error) { fi1, err := os.Stat(path1) switch { case os.IsNotExist(err): return false, nil case err != nil: return } fi2, err := os.Stat(path2) switch { case os.IsNotExist(err): return false, nil case err != nil: return } return os.SameFile(fi1, fi2), nil }
[ "func", "IsSameFile", "(", "path1", ",", "path2", "string", ")", "(", "same", "bool", ",", "err", "error", ")", "{", "fi1", ",", "err", ":=", "os", ".", "Stat", "(", "path1", ")", "\n\n", "switch", "{", "case", "os", ".", "IsNotExist", "(", "err", ")", ":", "return", "false", ",", "nil", "\n", "case", "err", "!=", "nil", ":", "return", "\n", "}", "\n\n", "fi2", ",", "err", ":=", "os", ".", "Stat", "(", "path2", ")", "\n\n", "switch", "{", "case", "os", ".", "IsNotExist", "(", "err", ")", ":", "return", "false", ",", "nil", "\n", "case", "err", "!=", "nil", ":", "return", "\n", "}", "\n\n", "return", "os", ".", "SameFile", "(", "fi1", ",", "fi2", ")", ",", "nil", "\n", "}" ]
// IsSameFile checks if two file paths are the same file
[ "IsSameFile", "checks", "if", "two", "file", "paths", "are", "the", "same", "file" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/rsync.go#L229-L250
940
Redundancy/go-sync
rsync.go
Close
func (rsync *RSync) Close() error { for _, f := range rsync.OnClose { if err := f.Close(); err != nil { return err } } return nil }
go
func (rsync *RSync) Close() error { for _, f := range rsync.OnClose { if err := f.Close(); err != nil { return err } } return nil }
[ "func", "(", "rsync", "*", "RSync", ")", "Close", "(", ")", "error", "{", "for", "_", ",", "f", ":=", "range", "rsync", ".", "OnClose", "{", "if", "err", ":=", "f", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close - close open files, copy to the final location from // a temporary one if neede
[ "Close", "-", "close", "open", "files", "copy", "to", "the", "final", "location", "from", "a", "temporary", "one", "if", "neede" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/rsync.go#L254-L261
941
Redundancy/go-sync
rsync.go
Close
func (f *fileCloser) Close() error { err := f.f.Close() if err != nil { return fmt.Errorf( "Could not close file %v: %v", f.path, err, ) } return nil }
go
func (f *fileCloser) Close() error { err := f.f.Close() if err != nil { return fmt.Errorf( "Could not close file %v: %v", f.path, err, ) } return nil }
[ "func", "(", "f", "*", "fileCloser", ")", "Close", "(", ")", "error", "{", "err", ":=", "f", ".", "f", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "path", ",", "err", ",", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close - add file path information to closing a file
[ "Close", "-", "add", "file", "path", "information", "to", "closing", "a", "file" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/rsync.go#L269-L279
942
Redundancy/go-sync
comparer/merger.go
merge
func (merger *MatchMerger) merge(block1, block2 *BlockSpan, blockSize int64) { var a, b *BlockSpan = block1, block2 if block1.StartBlock > block2.StartBlock { a, b = block2, block1 } if isBordering(a, b, blockSize) { // bordering, merge // A ------ A B ------ B > A ---------------- A merger.startEndBlockMap.Delete(BlockSpanKey(a.EndBlock)) merger.startEndBlockMap.Delete(BlockSpanKey(b.StartBlock)) a.EndBlock = b.EndBlock merger.startEndBlockMap.ReplaceOrInsert(BlockSpanStart(*a)) merger.startEndBlockMap.ReplaceOrInsert(BlockSpanEnd(*a)) } }
go
func (merger *MatchMerger) merge(block1, block2 *BlockSpan, blockSize int64) { var a, b *BlockSpan = block1, block2 if block1.StartBlock > block2.StartBlock { a, b = block2, block1 } if isBordering(a, b, blockSize) { // bordering, merge // A ------ A B ------ B > A ---------------- A merger.startEndBlockMap.Delete(BlockSpanKey(a.EndBlock)) merger.startEndBlockMap.Delete(BlockSpanKey(b.StartBlock)) a.EndBlock = b.EndBlock merger.startEndBlockMap.ReplaceOrInsert(BlockSpanStart(*a)) merger.startEndBlockMap.ReplaceOrInsert(BlockSpanEnd(*a)) } }
[ "func", "(", "merger", "*", "MatchMerger", ")", "merge", "(", "block1", ",", "block2", "*", "BlockSpan", ",", "blockSize", "int64", ")", "{", "var", "a", ",", "b", "*", "BlockSpan", "=", "block1", ",", "block2", "\n\n", "if", "block1", ".", "StartBlock", ">", "block2", ".", "StartBlock", "{", "a", ",", "b", "=", "block2", ",", "block1", "\n", "}", "\n\n", "if", "isBordering", "(", "a", ",", "b", ",", "blockSize", ")", "{", "// bordering, merge", "// A ------ A B ------ B > A ---------------- A", "merger", ".", "startEndBlockMap", ".", "Delete", "(", "BlockSpanKey", "(", "a", ".", "EndBlock", ")", ")", "\n", "merger", ".", "startEndBlockMap", ".", "Delete", "(", "BlockSpanKey", "(", "b", ".", "StartBlock", ")", ")", "\n", "a", ".", "EndBlock", "=", "b", ".", "EndBlock", "\n\n", "merger", ".", "startEndBlockMap", ".", "ReplaceOrInsert", "(", "BlockSpanStart", "(", "*", "a", ")", ")", "\n", "merger", ".", "startEndBlockMap", ".", "ReplaceOrInsert", "(", "BlockSpanEnd", "(", "*", "a", ")", ")", "\n", "}", "\n", "}" ]
// if merged, the block span remaining is the one with the lower start block
[ "if", "merged", "the", "block", "span", "remaining", "is", "the", "one", "with", "the", "lower", "start", "block" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/comparer/merger.go#L106-L123
943
Redundancy/go-sync
comparer/merger.go
StartMergeResultStream
func (merger *MatchMerger) StartMergeResultStream( resultStream <-chan BlockMatchResult, blockSize int64, ) { // Add should be called on the main goroutine // to ensure that it has happened before wait is called merger.wait.Add(1) if merger.startEndBlockMap == nil { merger.startEndBlockMap = llrb.New() } // used by the llrb iterator to signal that it found/didn't find // an existing key on or spanning the given block //foundExisting := make(chan bool) go func() { defer merger.wait.Done() for result := range resultStream { if result.Err != nil { return } merger.Lock() merger.blockCount += 1 blockID := result.BlockIdx preceeding := merger.startEndBlockMap.Get(BlockSpanKey(blockID - 1)) following := merger.startEndBlockMap.Get(BlockSpanKey(blockID + 1)) asBlockSpan := toBlockSpan(result) var foundExisting bool // Exists, or within an existing span merger.startEndBlockMap.AscendGreaterOrEqual( BlockSpanKey(blockID), // iterator func(i llrb.Item) bool { j, ok := i.(BlockSpanIndex) if !ok { foundExisting = true return false } switch k := j.(type) { case BlockSpanStart: // it's only overlapping if its the same blockID foundExisting = k.StartBlock == blockID return false case BlockSpanEnd: // we didn't find a start, so there's an end that overlaps foundExisting = true return false default: foundExisting = true return false } }, ) if foundExisting { merger.Unlock() continue } merger.startEndBlockMap.ReplaceOrInsert( BlockSpanStart(*toBlockSpan(result)), ) if preceeding != nil && following != nil { a := itemToBlockSpan(preceeding) merger.merge( asBlockSpan, &a, blockSize, ) b := itemToBlockSpan(following) merger.merge( &a, &b, blockSize, ) } else if preceeding != nil { a := itemToBlockSpan(preceeding) merger.merge( asBlockSpan, &a, blockSize, ) } else if following != nil { b := itemToBlockSpan(following) merger.merge( asBlockSpan, &b, blockSize, ) } merger.Unlock() } }() }
go
func (merger *MatchMerger) StartMergeResultStream( resultStream <-chan BlockMatchResult, blockSize int64, ) { // Add should be called on the main goroutine // to ensure that it has happened before wait is called merger.wait.Add(1) if merger.startEndBlockMap == nil { merger.startEndBlockMap = llrb.New() } // used by the llrb iterator to signal that it found/didn't find // an existing key on or spanning the given block //foundExisting := make(chan bool) go func() { defer merger.wait.Done() for result := range resultStream { if result.Err != nil { return } merger.Lock() merger.blockCount += 1 blockID := result.BlockIdx preceeding := merger.startEndBlockMap.Get(BlockSpanKey(blockID - 1)) following := merger.startEndBlockMap.Get(BlockSpanKey(blockID + 1)) asBlockSpan := toBlockSpan(result) var foundExisting bool // Exists, or within an existing span merger.startEndBlockMap.AscendGreaterOrEqual( BlockSpanKey(blockID), // iterator func(i llrb.Item) bool { j, ok := i.(BlockSpanIndex) if !ok { foundExisting = true return false } switch k := j.(type) { case BlockSpanStart: // it's only overlapping if its the same blockID foundExisting = k.StartBlock == blockID return false case BlockSpanEnd: // we didn't find a start, so there's an end that overlaps foundExisting = true return false default: foundExisting = true return false } }, ) if foundExisting { merger.Unlock() continue } merger.startEndBlockMap.ReplaceOrInsert( BlockSpanStart(*toBlockSpan(result)), ) if preceeding != nil && following != nil { a := itemToBlockSpan(preceeding) merger.merge( asBlockSpan, &a, blockSize, ) b := itemToBlockSpan(following) merger.merge( &a, &b, blockSize, ) } else if preceeding != nil { a := itemToBlockSpan(preceeding) merger.merge( asBlockSpan, &a, blockSize, ) } else if following != nil { b := itemToBlockSpan(following) merger.merge( asBlockSpan, &b, blockSize, ) } merger.Unlock() } }() }
[ "func", "(", "merger", "*", "MatchMerger", ")", "StartMergeResultStream", "(", "resultStream", "<-", "chan", "BlockMatchResult", ",", "blockSize", "int64", ",", ")", "{", "// Add should be called on the main goroutine", "// to ensure that it has happened before wait is called", "merger", ".", "wait", ".", "Add", "(", "1", ")", "\n\n", "if", "merger", ".", "startEndBlockMap", "==", "nil", "{", "merger", ".", "startEndBlockMap", "=", "llrb", ".", "New", "(", ")", "\n", "}", "\n\n", "// used by the llrb iterator to signal that it found/didn't find", "// an existing key on or spanning the given block", "//foundExisting := make(chan bool)", "go", "func", "(", ")", "{", "defer", "merger", ".", "wait", ".", "Done", "(", ")", "\n\n", "for", "result", ":=", "range", "resultStream", "{", "if", "result", ".", "Err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "merger", ".", "Lock", "(", ")", "\n", "merger", ".", "blockCount", "+=", "1", "\n\n", "blockID", ":=", "result", ".", "BlockIdx", "\n", "preceeding", ":=", "merger", ".", "startEndBlockMap", ".", "Get", "(", "BlockSpanKey", "(", "blockID", "-", "1", ")", ")", "\n", "following", ":=", "merger", ".", "startEndBlockMap", ".", "Get", "(", "BlockSpanKey", "(", "blockID", "+", "1", ")", ")", "\n\n", "asBlockSpan", ":=", "toBlockSpan", "(", "result", ")", "\n\n", "var", "foundExisting", "bool", "\n", "// Exists, or within an existing span", "merger", ".", "startEndBlockMap", ".", "AscendGreaterOrEqual", "(", "BlockSpanKey", "(", "blockID", ")", ",", "// iterator", "func", "(", "i", "llrb", ".", "Item", ")", "bool", "{", "j", ",", "ok", ":=", "i", ".", "(", "BlockSpanIndex", ")", "\n\n", "if", "!", "ok", "{", "foundExisting", "=", "true", "\n", "return", "false", "\n", "}", "\n\n", "switch", "k", ":=", "j", ".", "(", "type", ")", "{", "case", "BlockSpanStart", ":", "// it's only overlapping if its the same blockID", "foundExisting", "=", "k", ".", "StartBlock", "==", "blockID", "\n", "return", "false", "\n\n", "case", "BlockSpanEnd", ":", "// we didn't find a start, so there's an end that overlaps", "foundExisting", "=", "true", "\n", "return", "false", "\n", "default", ":", "foundExisting", "=", "true", "\n", "return", "false", "\n", "}", "\n\n", "}", ",", ")", "\n\n", "if", "foundExisting", "{", "merger", ".", "Unlock", "(", ")", "\n", "continue", "\n", "}", "\n\n", "merger", ".", "startEndBlockMap", ".", "ReplaceOrInsert", "(", "BlockSpanStart", "(", "*", "toBlockSpan", "(", "result", ")", ")", ",", ")", "\n\n", "if", "preceeding", "!=", "nil", "&&", "following", "!=", "nil", "{", "a", ":=", "itemToBlockSpan", "(", "preceeding", ")", "\n", "merger", ".", "merge", "(", "asBlockSpan", ",", "&", "a", ",", "blockSize", ",", ")", "\n\n", "b", ":=", "itemToBlockSpan", "(", "following", ")", "\n", "merger", ".", "merge", "(", "&", "a", ",", "&", "b", ",", "blockSize", ",", ")", "\n\n", "}", "else", "if", "preceeding", "!=", "nil", "{", "a", ":=", "itemToBlockSpan", "(", "preceeding", ")", "\n", "merger", ".", "merge", "(", "asBlockSpan", ",", "&", "a", ",", "blockSize", ",", ")", "\n", "}", "else", "if", "following", "!=", "nil", "{", "b", ":=", "itemToBlockSpan", "(", "following", ")", "\n", "merger", ".", "merge", "(", "asBlockSpan", ",", "&", "b", ",", "blockSize", ",", ")", "\n", "}", "\n\n", "merger", ".", "Unlock", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// Can be used on multiple streams of results simultaneously // starts working asyncronously, call from the initiating goroutine
[ "Can", "be", "used", "on", "multiple", "streams", "of", "results", "simultaneously", "starts", "working", "asyncronously", "call", "from", "the", "initiating", "goroutine" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/comparer/merger.go#L127-L234
944
Redundancy/go-sync
comparer/merger.go
GetMergedBlocks
func (merger *MatchMerger) GetMergedBlocks() (sorted BlockSpanList) { merger.wait.Wait() var smallestKey uint = 0 m := merger.startEndBlockMap m.AscendGreaterOrEqual(m.Min(), func(item llrb.Item) bool { switch block := item.(type) { case BlockSpanStart: sorted = append(sorted, BlockSpan(block)) smallestKey = block.StartBlock + 1 } return true }) sort.Sort(sorted) return }
go
func (merger *MatchMerger) GetMergedBlocks() (sorted BlockSpanList) { merger.wait.Wait() var smallestKey uint = 0 m := merger.startEndBlockMap m.AscendGreaterOrEqual(m.Min(), func(item llrb.Item) bool { switch block := item.(type) { case BlockSpanStart: sorted = append(sorted, BlockSpan(block)) smallestKey = block.StartBlock + 1 } return true }) sort.Sort(sorted) return }
[ "func", "(", "merger", "*", "MatchMerger", ")", "GetMergedBlocks", "(", ")", "(", "sorted", "BlockSpanList", ")", "{", "merger", ".", "wait", ".", "Wait", "(", ")", "\n", "var", "smallestKey", "uint", "=", "0", "\n", "m", ":=", "merger", ".", "startEndBlockMap", "\n\n", "m", ".", "AscendGreaterOrEqual", "(", "m", ".", "Min", "(", ")", ",", "func", "(", "item", "llrb", ".", "Item", ")", "bool", "{", "switch", "block", ":=", "item", ".", "(", "type", ")", "{", "case", "BlockSpanStart", ":", "sorted", "=", "append", "(", "sorted", ",", "BlockSpan", "(", "block", ")", ")", "\n", "smallestKey", "=", "block", ".", "StartBlock", "+", "1", "\n", "}", "\n", "return", "true", "\n", "}", ")", "\n\n", "sort", ".", "Sort", "(", "sorted", ")", "\n", "return", "\n", "}" ]
// Sorted list of blocks, based on StartBlock
[ "Sorted", "list", "of", "blocks", "based", "on", "StartBlock" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/comparer/merger.go#L251-L267
945
Redundancy/go-sync
comparer/merger.go
GetMissingBlocks
func (l BlockSpanList) GetMissingBlocks(maxBlock uint) (sorted BlockSpanList) { // it's difficult to know how many spans we will need sorted = make(BlockSpanList, 0) lastBlockSpanIndex := -1 for _, blockSpan := range l { if int(blockSpan.StartBlock) > lastBlockSpanIndex+1 { sorted = append( sorted, BlockSpan{ StartBlock: uint(lastBlockSpanIndex + 1), EndBlock: blockSpan.StartBlock - 1, }, ) } lastBlockSpanIndex = int(blockSpan.EndBlock) } if lastBlockSpanIndex == -1 { sorted = append( sorted, BlockSpan{ StartBlock: 0, EndBlock: maxBlock, }, ) } else if uint(lastBlockSpanIndex) < maxBlock { sorted = append( sorted, BlockSpan{ StartBlock: uint(lastBlockSpanIndex + 1), EndBlock: maxBlock, }, ) } return sorted }
go
func (l BlockSpanList) GetMissingBlocks(maxBlock uint) (sorted BlockSpanList) { // it's difficult to know how many spans we will need sorted = make(BlockSpanList, 0) lastBlockSpanIndex := -1 for _, blockSpan := range l { if int(blockSpan.StartBlock) > lastBlockSpanIndex+1 { sorted = append( sorted, BlockSpan{ StartBlock: uint(lastBlockSpanIndex + 1), EndBlock: blockSpan.StartBlock - 1, }, ) } lastBlockSpanIndex = int(blockSpan.EndBlock) } if lastBlockSpanIndex == -1 { sorted = append( sorted, BlockSpan{ StartBlock: 0, EndBlock: maxBlock, }, ) } else if uint(lastBlockSpanIndex) < maxBlock { sorted = append( sorted, BlockSpan{ StartBlock: uint(lastBlockSpanIndex + 1), EndBlock: maxBlock, }, ) } return sorted }
[ "func", "(", "l", "BlockSpanList", ")", "GetMissingBlocks", "(", "maxBlock", "uint", ")", "(", "sorted", "BlockSpanList", ")", "{", "// it's difficult to know how many spans we will need", "sorted", "=", "make", "(", "BlockSpanList", ",", "0", ")", "\n\n", "lastBlockSpanIndex", ":=", "-", "1", "\n", "for", "_", ",", "blockSpan", ":=", "range", "l", "{", "if", "int", "(", "blockSpan", ".", "StartBlock", ")", ">", "lastBlockSpanIndex", "+", "1", "{", "sorted", "=", "append", "(", "sorted", ",", "BlockSpan", "{", "StartBlock", ":", "uint", "(", "lastBlockSpanIndex", "+", "1", ")", ",", "EndBlock", ":", "blockSpan", ".", "StartBlock", "-", "1", ",", "}", ",", ")", "\n", "}", "\n\n", "lastBlockSpanIndex", "=", "int", "(", "blockSpan", ".", "EndBlock", ")", "\n", "}", "\n\n", "if", "lastBlockSpanIndex", "==", "-", "1", "{", "sorted", "=", "append", "(", "sorted", ",", "BlockSpan", "{", "StartBlock", ":", "0", ",", "EndBlock", ":", "maxBlock", ",", "}", ",", ")", "\n", "}", "else", "if", "uint", "(", "lastBlockSpanIndex", ")", "<", "maxBlock", "{", "sorted", "=", "append", "(", "sorted", ",", "BlockSpan", "{", "StartBlock", ":", "uint", "(", "lastBlockSpanIndex", "+", "1", ")", ",", "EndBlock", ":", "maxBlock", ",", "}", ",", ")", "\n", "}", "\n\n", "return", "sorted", "\n", "}" ]
// Creates a list of spans that are missing. // note that maxBlock is blockCount-1
[ "Creates", "a", "list", "of", "spans", "that", "are", "missing", ".", "note", "that", "maxBlock", "is", "blockCount", "-", "1" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/comparer/merger.go#L271-L309
946
Redundancy/go-sync
filechecksum/filechecksum.go
Reset
func (check *FileChecksumGenerator) Reset() { check.WeakRollingHash.Reset() check.StrongHash.Reset() check.FileChecksumHash.Reset() }
go
func (check *FileChecksumGenerator) Reset() { check.WeakRollingHash.Reset() check.StrongHash.Reset() check.FileChecksumHash.Reset() }
[ "func", "(", "check", "*", "FileChecksumGenerator", ")", "Reset", "(", ")", "{", "check", ".", "WeakRollingHash", ".", "Reset", "(", ")", "\n", "check", ".", "StrongHash", ".", "Reset", "(", ")", "\n", "check", ".", "FileChecksumHash", ".", "Reset", "(", ")", "\n", "}" ]
// Reset all hashes to initial state
[ "Reset", "all", "hashes", "to", "initial", "state" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/filechecksum/filechecksum.go#L73-L77
947
Redundancy/go-sync
filechecksum/filechecksum.go
GenerateChecksums
func (check *FileChecksumGenerator) GenerateChecksums(inputFile io.Reader, output io.Writer) (fileChecksum []byte, err error) { for chunkResult := range check.StartChecksumGeneration(inputFile, 64, nil) { if chunkResult.Err != nil { return nil, chunkResult.Err } else if chunkResult.Filechecksum != nil { return chunkResult.Filechecksum, nil } for _, chunk := range chunkResult.Checksums { output.Write(chunk.WeakChecksum) output.Write(chunk.StrongChecksum) } } return nil, nil }
go
func (check *FileChecksumGenerator) GenerateChecksums(inputFile io.Reader, output io.Writer) (fileChecksum []byte, err error) { for chunkResult := range check.StartChecksumGeneration(inputFile, 64, nil) { if chunkResult.Err != nil { return nil, chunkResult.Err } else if chunkResult.Filechecksum != nil { return chunkResult.Filechecksum, nil } for _, chunk := range chunkResult.Checksums { output.Write(chunk.WeakChecksum) output.Write(chunk.StrongChecksum) } } return nil, nil }
[ "func", "(", "check", "*", "FileChecksumGenerator", ")", "GenerateChecksums", "(", "inputFile", "io", ".", "Reader", ",", "output", "io", ".", "Writer", ")", "(", "fileChecksum", "[", "]", "byte", ",", "err", "error", ")", "{", "for", "chunkResult", ":=", "range", "check", ".", "StartChecksumGeneration", "(", "inputFile", ",", "64", ",", "nil", ")", "{", "if", "chunkResult", ".", "Err", "!=", "nil", "{", "return", "nil", ",", "chunkResult", ".", "Err", "\n", "}", "else", "if", "chunkResult", ".", "Filechecksum", "!=", "nil", "{", "return", "chunkResult", ".", "Filechecksum", ",", "nil", "\n", "}", "\n\n", "for", "_", ",", "chunk", ":=", "range", "chunkResult", ".", "Checksums", "{", "output", ".", "Write", "(", "chunk", ".", "WeakChecksum", ")", "\n", "output", ".", "Write", "(", "chunk", ".", "StrongChecksum", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", ",", "nil", "\n", "}" ]
// GenerateChecksums reads each block of the input file, and outputs first the weak, then the strong checksum // to the output writer. It will return a checksum for the whole file. // Potentially speaking, this might be better producing a channel of blocks, which would remove the need for io from // a number of other places.
[ "GenerateChecksums", "reads", "each", "block", "of", "the", "input", "file", "and", "outputs", "first", "the", "weak", "then", "the", "strong", "checksum", "to", "the", "output", "writer", ".", "It", "will", "return", "a", "checksum", "for", "the", "whole", "file", ".", "Potentially", "speaking", "this", "might", "be", "better", "producing", "a", "channel", "of", "blocks", "which", "would", "remove", "the", "need", "for", "io", "from", "a", "number", "of", "other", "places", "." ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/filechecksum/filechecksum.go#L103-L118
948
Redundancy/go-sync
rollsum/rollsum_32.go
Write
func (r *Rollsum32) Write(p []byte) (n int, err error) { ulen_p := uint(len(p)) if ulen_p >= r.blockSize { // if it's really long, we can just ignore a load of it remaining := p[ulen_p-r.blockSize:] r.buffer.Write(remaining) r.Rollsum32Base.SetBlock(remaining) } else { b_len := r.buffer.Len() r.buffer.Write(p) evicted := r.buffer.Evicted() r.Rollsum32Base.AddAndRemoveBytes(p, evicted, b_len) } return len(p), nil }
go
func (r *Rollsum32) Write(p []byte) (n int, err error) { ulen_p := uint(len(p)) if ulen_p >= r.blockSize { // if it's really long, we can just ignore a load of it remaining := p[ulen_p-r.blockSize:] r.buffer.Write(remaining) r.Rollsum32Base.SetBlock(remaining) } else { b_len := r.buffer.Len() r.buffer.Write(p) evicted := r.buffer.Evicted() r.Rollsum32Base.AddAndRemoveBytes(p, evicted, b_len) } return len(p), nil }
[ "func", "(", "r", "*", "Rollsum32", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "ulen_p", ":=", "uint", "(", "len", "(", "p", ")", ")", "\n\n", "if", "ulen_p", ">=", "r", ".", "blockSize", "{", "// if it's really long, we can just ignore a load of it", "remaining", ":=", "p", "[", "ulen_p", "-", "r", ".", "blockSize", ":", "]", "\n", "r", ".", "buffer", ".", "Write", "(", "remaining", ")", "\n", "r", ".", "Rollsum32Base", ".", "SetBlock", "(", "remaining", ")", "\n", "}", "else", "{", "b_len", ":=", "r", ".", "buffer", ".", "Len", "(", ")", "\n", "r", ".", "buffer", ".", "Write", "(", "p", ")", "\n", "evicted", ":=", "r", ".", "buffer", ".", "Evicted", "(", ")", "\n", "r", ".", "Rollsum32Base", ".", "AddAndRemoveBytes", "(", "p", ",", "evicted", ",", "b_len", ")", "\n", "}", "\n\n", "return", "len", "(", "p", ")", ",", "nil", "\n", "}" ]
// cannot be called concurrently
[ "cannot", "be", "called", "concurrently" ]
8931874cad5cacc627b94fcbcb182460e174aeef
https://github.com/Redundancy/go-sync/blob/8931874cad5cacc627b94fcbcb182460e174aeef/rollsum/rollsum_32.go#L34-L50
949
mdempsky/unconvert
unconvert.go
intersect
func (e editSet) intersect(x editSet) { for pos := range e { if _, ok := x[pos]; !ok { delete(e, pos) } } }
go
func (e editSet) intersect(x editSet) { for pos := range e { if _, ok := x[pos]; !ok { delete(e, pos) } } }
[ "func", "(", "e", "editSet", ")", "intersect", "(", "x", "editSet", ")", "{", "for", "pos", ":=", "range", "e", "{", "if", "_", ",", "ok", ":=", "x", "[", "pos", "]", ";", "!", "ok", "{", "delete", "(", "e", ",", "pos", ")", "\n", "}", "\n", "}", "\n", "}" ]
// intersect removes positions from e that are not present in x.
[ "intersect", "removes", "positions", "from", "e", "that", "are", "not", "present", "in", "x", "." ]
2f5dc3378ed3ba283f5125b8bb47f6ba672f879b
https://github.com/mdempsky/unconvert/blob/2f5dc3378ed3ba283f5125b8bb47f6ba672f879b/unconvert.go#L55-L61
950
mdempsky/unconvert
unconvert.go
isFloatingPoint
func isFloatingPoint(t types.Type) bool { ut, ok := t.Underlying().(*types.Basic) return ok && ut.Info()&(types.IsFloat|types.IsComplex) != 0 }
go
func isFloatingPoint(t types.Type) bool { ut, ok := t.Underlying().(*types.Basic) return ok && ut.Info()&(types.IsFloat|types.IsComplex) != 0 }
[ "func", "isFloatingPoint", "(", "t", "types", ".", "Type", ")", "bool", "{", "ut", ",", "ok", ":=", "t", ".", "Underlying", "(", ")", ".", "(", "*", "types", ".", "Basic", ")", "\n", "return", "ok", "&&", "ut", ".", "Info", "(", ")", "&", "(", "types", ".", "IsFloat", "|", "types", ".", "IsComplex", ")", "!=", "0", "\n", "}" ]
// isFloatingPointer reports whether t's underlying type is a floating // point type.
[ "isFloatingPointer", "reports", "whether", "t", "s", "underlying", "type", "is", "a", "floating", "point", "type", "." ]
2f5dc3378ed3ba283f5125b8bb47f6ba672f879b
https://github.com/mdempsky/unconvert/blob/2f5dc3378ed3ba283f5125b8bb47f6ba672f879b/unconvert.go#L443-L446
951
Code-Hex/pget
requests.go
Checking
func (p *Pget) Checking() error { ctx, cancelAll := context.WithTimeout(context.Background(), time.Duration(p.timeout)*time.Second) ch := MakeCh() defer ch.Close() for _, url := range p.URLs { fmt.Fprintf(os.Stdout, "Checking now %s\n", url) go p.CheckMirrors(ctx, url, ch) } // listen for error or size channel size, err := ch.CheckingListen(ctx, cancelAll, len(p.URLs)) if err != nil { return err } // did already get filename from -o option filename := p.Utils.FileName() if filename == "" { filename = p.Utils.URLFileName(p.TargetDir, p.TargetURLs[0]) } p.SetFileName(filename) p.SetFullFileName(p.TargetDir, filename) p.Utils.SetDirName(p.TargetDir, filename, p.Procs) p.SetFileSize(size) return nil }
go
func (p *Pget) Checking() error { ctx, cancelAll := context.WithTimeout(context.Background(), time.Duration(p.timeout)*time.Second) ch := MakeCh() defer ch.Close() for _, url := range p.URLs { fmt.Fprintf(os.Stdout, "Checking now %s\n", url) go p.CheckMirrors(ctx, url, ch) } // listen for error or size channel size, err := ch.CheckingListen(ctx, cancelAll, len(p.URLs)) if err != nil { return err } // did already get filename from -o option filename := p.Utils.FileName() if filename == "" { filename = p.Utils.URLFileName(p.TargetDir, p.TargetURLs[0]) } p.SetFileName(filename) p.SetFullFileName(p.TargetDir, filename) p.Utils.SetDirName(p.TargetDir, filename, p.Procs) p.SetFileSize(size) return nil }
[ "func", "(", "p", "*", "Pget", ")", "Checking", "(", ")", "error", "{", "ctx", ",", "cancelAll", ":=", "context", ".", "WithTimeout", "(", "context", ".", "Background", "(", ")", ",", "time", ".", "Duration", "(", "p", ".", "timeout", ")", "*", "time", ".", "Second", ")", "\n\n", "ch", ":=", "MakeCh", "(", ")", "\n", "defer", "ch", ".", "Close", "(", ")", "\n\n", "for", "_", ",", "url", ":=", "range", "p", ".", "URLs", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stdout", ",", "\"", "\\n", "\"", ",", "url", ")", "\n", "go", "p", ".", "CheckMirrors", "(", "ctx", ",", "url", ",", "ch", ")", "\n", "}", "\n\n", "// listen for error or size channel", "size", ",", "err", ":=", "ch", ".", "CheckingListen", "(", "ctx", ",", "cancelAll", ",", "len", "(", "p", ".", "URLs", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// did already get filename from -o option", "filename", ":=", "p", ".", "Utils", ".", "FileName", "(", ")", "\n", "if", "filename", "==", "\"", "\"", "{", "filename", "=", "p", ".", "Utils", ".", "URLFileName", "(", "p", ".", "TargetDir", ",", "p", ".", "TargetURLs", "[", "0", "]", ")", "\n", "}", "\n", "p", ".", "SetFileName", "(", "filename", ")", "\n", "p", ".", "SetFullFileName", "(", "p", ".", "TargetDir", ",", "filename", ")", "\n", "p", ".", "Utils", ".", "SetDirName", "(", "p", ".", "TargetDir", ",", "filename", ",", "p", ".", "Procs", ")", "\n\n", "p", ".", "SetFileSize", "(", "size", ")", "\n\n", "return", "nil", "\n", "}" ]
// Checking is check to can request
[ "Checking", "is", "check", "to", "can", "request" ]
9294f7465fa777e5d9400500691e244a9a9ff225
https://github.com/Code-Hex/pget/blob/9294f7465fa777e5d9400500691e244a9a9ff225/requests.go#L32-L62
952
Code-Hex/pget
requests.go
CheckMirrors
func (p *Pget) CheckMirrors(ctx context.Context, url string, ch *Ch) { res, err := ctxhttp.Head(ctx, http.DefaultClient, url) if err != nil { ch.Err <- errors.Wrap(err, "failed to head request: "+url) return } if res.Header.Get("Accept-Ranges") != "bytes" { ch.Err <- errors.Errorf("not supported range access: %s", url) return } // To perform with the correct "range access" // get the last url in the redirect _url := res.Request.URL.String() if isNotLastURL(_url, url) { p.TargetURLs = append(p.TargetURLs, _url) } else { p.TargetURLs = append(p.TargetURLs, url) } // get of ContentLength if res.ContentLength <= 0 { ch.Err <- errors.New("invalid content length") return } ch.Size <- uint(res.ContentLength) }
go
func (p *Pget) CheckMirrors(ctx context.Context, url string, ch *Ch) { res, err := ctxhttp.Head(ctx, http.DefaultClient, url) if err != nil { ch.Err <- errors.Wrap(err, "failed to head request: "+url) return } if res.Header.Get("Accept-Ranges") != "bytes" { ch.Err <- errors.Errorf("not supported range access: %s", url) return } // To perform with the correct "range access" // get the last url in the redirect _url := res.Request.URL.String() if isNotLastURL(_url, url) { p.TargetURLs = append(p.TargetURLs, _url) } else { p.TargetURLs = append(p.TargetURLs, url) } // get of ContentLength if res.ContentLength <= 0 { ch.Err <- errors.New("invalid content length") return } ch.Size <- uint(res.ContentLength) }
[ "func", "(", "p", "*", "Pget", ")", "CheckMirrors", "(", "ctx", "context", ".", "Context", ",", "url", "string", ",", "ch", "*", "Ch", ")", "{", "res", ",", "err", ":=", "ctxhttp", ".", "Head", "(", "ctx", ",", "http", ".", "DefaultClient", ",", "url", ")", "\n", "if", "err", "!=", "nil", "{", "ch", ".", "Err", "<-", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", "+", "url", ")", "\n", "return", "\n", "}", "\n\n", "if", "res", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "!=", "\"", "\"", "{", "ch", ".", "Err", "<-", "errors", ".", "Errorf", "(", "\"", "\"", ",", "url", ")", "\n", "return", "\n", "}", "\n\n", "// To perform with the correct \"range access\"", "// get the last url in the redirect", "_url", ":=", "res", ".", "Request", ".", "URL", ".", "String", "(", ")", "\n", "if", "isNotLastURL", "(", "_url", ",", "url", ")", "{", "p", ".", "TargetURLs", "=", "append", "(", "p", ".", "TargetURLs", ",", "_url", ")", "\n", "}", "else", "{", "p", ".", "TargetURLs", "=", "append", "(", "p", ".", "TargetURLs", ",", "url", ")", "\n", "}", "\n\n", "// get of ContentLength", "if", "res", ".", "ContentLength", "<=", "0", "{", "ch", ".", "Err", "<-", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "ch", ".", "Size", "<-", "uint", "(", "res", ".", "ContentLength", ")", "\n", "}" ]
// CheckMirrors method check be able to range access. also get redirected url.
[ "CheckMirrors", "method", "check", "be", "able", "to", "range", "access", ".", "also", "get", "redirected", "url", "." ]
9294f7465fa777e5d9400500691e244a9a9ff225
https://github.com/Code-Hex/pget/blob/9294f7465fa777e5d9400500691e244a9a9ff225/requests.go#L65-L93
953
Code-Hex/pget
requests.go
Download
func (p *Pget) Download() error { procs := uint(p.Procs) filesize := p.FileSize() dirname := p.DirName() // create download location if err := os.MkdirAll(dirname, 0755); err != nil { return errors.Wrap(err, "failed to mkdir for download location") } // calculate split file size split := filesize / procs if err := p.Utils.IsFree(split); err != nil { return err } grp, ctx := errgroup.WithContext(context.Background()) // on an assignment for request p.Assignment(grp, procs, split) if err := p.Utils.ProgressBar(ctx); err != nil { return err } // wait for Assignment method if err := grp.Wait(); err != nil { return err } return nil }
go
func (p *Pget) Download() error { procs := uint(p.Procs) filesize := p.FileSize() dirname := p.DirName() // create download location if err := os.MkdirAll(dirname, 0755); err != nil { return errors.Wrap(err, "failed to mkdir for download location") } // calculate split file size split := filesize / procs if err := p.Utils.IsFree(split); err != nil { return err } grp, ctx := errgroup.WithContext(context.Background()) // on an assignment for request p.Assignment(grp, procs, split) if err := p.Utils.ProgressBar(ctx); err != nil { return err } // wait for Assignment method if err := grp.Wait(); err != nil { return err } return nil }
[ "func", "(", "p", "*", "Pget", ")", "Download", "(", ")", "error", "{", "procs", ":=", "uint", "(", "p", ".", "Procs", ")", "\n\n", "filesize", ":=", "p", ".", "FileSize", "(", ")", "\n", "dirname", ":=", "p", ".", "DirName", "(", ")", "\n\n", "// create download location", "if", "err", ":=", "os", ".", "MkdirAll", "(", "dirname", ",", "0755", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// calculate split file size", "split", ":=", "filesize", "/", "procs", "\n\n", "if", "err", ":=", "p", ".", "Utils", ".", "IsFree", "(", "split", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "grp", ",", "ctx", ":=", "errgroup", ".", "WithContext", "(", "context", ".", "Background", "(", ")", ")", "\n\n", "// on an assignment for request", "p", ".", "Assignment", "(", "grp", ",", "procs", ",", "split", ")", "\n\n", "if", "err", ":=", "p", ".", "Utils", ".", "ProgressBar", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// wait for Assignment method", "if", "err", ":=", "grp", ".", "Wait", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Download method distributes the task to each goroutine for each URL
[ "Download", "method", "distributes", "the", "task", "to", "each", "goroutine", "for", "each", "URL" ]
9294f7465fa777e5d9400500691e244a9a9ff225
https://github.com/Code-Hex/pget/blob/9294f7465fa777e5d9400500691e244a9a9ff225/requests.go#L96-L130
954
Code-Hex/pget
requests.go
Assignment
func (p Pget) Assignment(grp *errgroup.Group, procs, split uint) { filename := p.FileName() dirname := p.DirName() assignment := uint(p.Procs / len(p.TargetURLs)) var lasturl string totalActiveProcs := uint(0) for i := uint(0); i < procs; i++ { partName := fmt.Sprintf("%s/%s.%d.%d", dirname, filename, procs, i) // make range r := p.Utils.MakeRange(i, split, procs) if info, err := os.Stat(partName); err == nil { infosize := uint(info.Size()) // check if the part is fully downloaded if isLastProc(i, procs) { if infosize == r.high-r.low { continue } } else if infosize == split { // skip as the part is already downloaded continue } // make low range from this next byte r.low += infosize } totalActiveProcs++ url := p.TargetURLs[0] // give efficiency and equality work if totalActiveProcs%assignment == 0 { // Like shift method if len(p.TargetURLs) > 1 { p.TargetURLs = p.TargetURLs[1:] } // check whether to output the message if lasturl != url { fmt.Fprintf(os.Stdout, "Download start from %s\n", url) lasturl = url } } // execute get request grp.Go(func() error { return p.Requests(r, filename, dirname, url) }) } }
go
func (p Pget) Assignment(grp *errgroup.Group, procs, split uint) { filename := p.FileName() dirname := p.DirName() assignment := uint(p.Procs / len(p.TargetURLs)) var lasturl string totalActiveProcs := uint(0) for i := uint(0); i < procs; i++ { partName := fmt.Sprintf("%s/%s.%d.%d", dirname, filename, procs, i) // make range r := p.Utils.MakeRange(i, split, procs) if info, err := os.Stat(partName); err == nil { infosize := uint(info.Size()) // check if the part is fully downloaded if isLastProc(i, procs) { if infosize == r.high-r.low { continue } } else if infosize == split { // skip as the part is already downloaded continue } // make low range from this next byte r.low += infosize } totalActiveProcs++ url := p.TargetURLs[0] // give efficiency and equality work if totalActiveProcs%assignment == 0 { // Like shift method if len(p.TargetURLs) > 1 { p.TargetURLs = p.TargetURLs[1:] } // check whether to output the message if lasturl != url { fmt.Fprintf(os.Stdout, "Download start from %s\n", url) lasturl = url } } // execute get request grp.Go(func() error { return p.Requests(r, filename, dirname, url) }) } }
[ "func", "(", "p", "Pget", ")", "Assignment", "(", "grp", "*", "errgroup", ".", "Group", ",", "procs", ",", "split", "uint", ")", "{", "filename", ":=", "p", ".", "FileName", "(", ")", "\n", "dirname", ":=", "p", ".", "DirName", "(", ")", "\n\n", "assignment", ":=", "uint", "(", "p", ".", "Procs", "/", "len", "(", "p", ".", "TargetURLs", ")", ")", "\n\n", "var", "lasturl", "string", "\n", "totalActiveProcs", ":=", "uint", "(", "0", ")", "\n", "for", "i", ":=", "uint", "(", "0", ")", ";", "i", "<", "procs", ";", "i", "++", "{", "partName", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "dirname", ",", "filename", ",", "procs", ",", "i", ")", "\n\n", "// make range", "r", ":=", "p", ".", "Utils", ".", "MakeRange", "(", "i", ",", "split", ",", "procs", ")", "\n\n", "if", "info", ",", "err", ":=", "os", ".", "Stat", "(", "partName", ")", ";", "err", "==", "nil", "{", "infosize", ":=", "uint", "(", "info", ".", "Size", "(", ")", ")", "\n", "// check if the part is fully downloaded", "if", "isLastProc", "(", "i", ",", "procs", ")", "{", "if", "infosize", "==", "r", ".", "high", "-", "r", ".", "low", "{", "continue", "\n", "}", "\n", "}", "else", "if", "infosize", "==", "split", "{", "// skip as the part is already downloaded", "continue", "\n", "}", "\n\n", "// make low range from this next byte", "r", ".", "low", "+=", "infosize", "\n", "}", "\n\n", "totalActiveProcs", "++", "\n\n", "url", ":=", "p", ".", "TargetURLs", "[", "0", "]", "\n\n", "// give efficiency and equality work", "if", "totalActiveProcs", "%", "assignment", "==", "0", "{", "// Like shift method", "if", "len", "(", "p", ".", "TargetURLs", ")", ">", "1", "{", "p", ".", "TargetURLs", "=", "p", ".", "TargetURLs", "[", "1", ":", "]", "\n", "}", "\n\n", "// check whether to output the message", "if", "lasturl", "!=", "url", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stdout", ",", "\"", "\\n", "\"", ",", "url", ")", "\n", "lasturl", "=", "url", "\n", "}", "\n", "}", "\n\n", "// execute get request", "grp", ".", "Go", "(", "func", "(", ")", "error", "{", "return", "p", ".", "Requests", "(", "r", ",", "filename", ",", "dirname", ",", "url", ")", "\n", "}", ")", "\n", "}", "\n", "}" ]
// Assignment method that to each goroutine gives the task
[ "Assignment", "method", "that", "to", "each", "goroutine", "gives", "the", "task" ]
9294f7465fa777e5d9400500691e244a9a9ff225
https://github.com/Code-Hex/pget/blob/9294f7465fa777e5d9400500691e244a9a9ff225/requests.go#L133-L186
955
Code-Hex/pget
requests.go
Requests
func (p Pget) Requests(r Range, filename, dirname, url string) error { res, err := p.MakeResponse(r, url) // ctxhttp if err != nil { return errors.Wrap(err, fmt.Sprintf("failed to split get requests: %d", r.worker)) } defer res.Body.Close() partName := fmt.Sprintf("%s/%s.%d.%d", dirname, filename, p.Procs, r.worker) output, err := os.OpenFile(partName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if err != nil { return errors.Wrap(err, fmt.Sprintf("failed to create %s in %s", filename, dirname)) } defer output.Close() io.Copy(output, res.Body) return nil }
go
func (p Pget) Requests(r Range, filename, dirname, url string) error { res, err := p.MakeResponse(r, url) // ctxhttp if err != nil { return errors.Wrap(err, fmt.Sprintf("failed to split get requests: %d", r.worker)) } defer res.Body.Close() partName := fmt.Sprintf("%s/%s.%d.%d", dirname, filename, p.Procs, r.worker) output, err := os.OpenFile(partName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if err != nil { return errors.Wrap(err, fmt.Sprintf("failed to create %s in %s", filename, dirname)) } defer output.Close() io.Copy(output, res.Body) return nil }
[ "func", "(", "p", "Pget", ")", "Requests", "(", "r", "Range", ",", "filename", ",", "dirname", ",", "url", "string", ")", "error", "{", "res", ",", "err", ":=", "p", ".", "MakeResponse", "(", "r", ",", "url", ")", "// ctxhttp", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "r", ".", "worker", ")", ")", "\n", "}", "\n", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n\n", "partName", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "dirname", ",", "filename", ",", "p", ".", "Procs", ",", "r", ".", "worker", ")", "\n\n", "output", ",", "err", ":=", "os", ".", "OpenFile", "(", "partName", ",", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREATE", "|", "os", ".", "O_APPEND", ",", "0666", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "filename", ",", "dirname", ")", ")", "\n", "}", "\n", "defer", "output", ".", "Close", "(", ")", "\n\n", "io", ".", "Copy", "(", "output", ",", "res", ".", "Body", ")", "\n\n", "return", "nil", "\n", "}" ]
// Requests method will download the file
[ "Requests", "method", "will", "download", "the", "file" ]
9294f7465fa777e5d9400500691e244a9a9ff225
https://github.com/Code-Hex/pget/blob/9294f7465fa777e5d9400500691e244a9a9ff225/requests.go#L189-L208
956
Code-Hex/pget
pget.go
New
func New() *Pget { return &Pget{ Trace: false, Utils: &Data{}, Procs: runtime.NumCPU(), // default timeout: 10, } }
go
func New() *Pget { return &Pget{ Trace: false, Utils: &Data{}, Procs: runtime.NumCPU(), // default timeout: 10, } }
[ "func", "New", "(", ")", "*", "Pget", "{", "return", "&", "Pget", "{", "Trace", ":", "false", ",", "Utils", ":", "&", "Data", "{", "}", ",", "Procs", ":", "runtime", ".", "NumCPU", "(", ")", ",", "// default", "timeout", ":", "10", ",", "}", "\n", "}" ]
// New for pget package
[ "New", "for", "pget", "package" ]
9294f7465fa777e5d9400500691e244a9a9ff225
https://github.com/Code-Hex/pget/blob/9294f7465fa777e5d9400500691e244a9a9ff225/pget.go#L42-L49
957
Code-Hex/pget
pget.go
ErrTop
func (pget Pget) ErrTop(err error) error { for e := err; e != nil; { switch e.(type) { case ignore: return nil case cause: e = e.(cause).Cause() default: return e } } return nil }
go
func (pget Pget) ErrTop(err error) error { for e := err; e != nil; { switch e.(type) { case ignore: return nil case cause: e = e.(cause).Cause() default: return e } } return nil }
[ "func", "(", "pget", "Pget", ")", "ErrTop", "(", "err", "error", ")", "error", "{", "for", "e", ":=", "err", ";", "e", "!=", "nil", ";", "{", "switch", "e", ".", "(", "type", ")", "{", "case", "ignore", ":", "return", "nil", "\n", "case", "cause", ":", "e", "=", "e", ".", "(", "cause", ")", ".", "Cause", "(", ")", "\n", "default", ":", "return", "e", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ErrTop get important message from wrapped error message
[ "ErrTop", "get", "important", "message", "from", "wrapped", "error", "message" ]
9294f7465fa777e5d9400500691e244a9a9ff225
https://github.com/Code-Hex/pget/blob/9294f7465fa777e5d9400500691e244a9a9ff225/pget.go#L52-L65
958
Code-Hex/pget
pget.go
Run
func (pget *Pget) Run() error { if err := pget.Ready(); err != nil { return pget.ErrTop(err) } if err := pget.Checking(); err != nil { return errors.Wrap(err, "failed to check header") } if err := pget.Download(); err != nil { return err } if err := pget.Utils.BindwithFiles(pget.Procs); err != nil { return err } return nil }
go
func (pget *Pget) Run() error { if err := pget.Ready(); err != nil { return pget.ErrTop(err) } if err := pget.Checking(); err != nil { return errors.Wrap(err, "failed to check header") } if err := pget.Download(); err != nil { return err } if err := pget.Utils.BindwithFiles(pget.Procs); err != nil { return err } return nil }
[ "func", "(", "pget", "*", "Pget", ")", "Run", "(", ")", "error", "{", "if", "err", ":=", "pget", ".", "Ready", "(", ")", ";", "err", "!=", "nil", "{", "return", "pget", ".", "ErrTop", "(", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "pget", ".", "Checking", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "pget", ".", "Download", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "pget", ".", "Utils", ".", "BindwithFiles", "(", "pget", ".", "Procs", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Run execute methods in pget package
[ "Run", "execute", "methods", "in", "pget", "package" ]
9294f7465fa777e5d9400500691e244a9a9ff225
https://github.com/Code-Hex/pget/blob/9294f7465fa777e5d9400500691e244a9a9ff225/pget.go#L68-L86
959
Code-Hex/pget
pget.go
Ready
func (pget *Pget) Ready() error { if procs := os.Getenv("GOMAXPROCS"); procs == "" { runtime.GOMAXPROCS(pget.Procs) } var opts Options if err := pget.parseOptions(&opts, os.Args[1:]); err != nil { return errors.Wrap(err, "failed to parse command line args") } if opts.Trace { pget.Trace = opts.Trace } if opts.Procs > 2 { pget.Procs = opts.Procs } if opts.Timeout > 0 { pget.timeout = opts.Timeout } if err := pget.parseURLs(); err != nil { return errors.Wrap(err, "failed to parse of url") } if opts.Output != "" { pget.Utils.SetFileName(opts.Output) } if opts.UserAgent != "" { pget.useragent = opts.UserAgent } if opts.Referer != "" { pget.referer = opts.Referer } if opts.TargetDir != "" { info, err := os.Stat(opts.TargetDir) if err != nil { if !os.IsNotExist(err) { return errors.Wrap(err, "target dir is invalid") } if err := os.MkdirAll(opts.TargetDir, 0755); err != nil { return errors.Wrapf(err, "failed to create diretory at %s", opts.TargetDir) } } else if !info.IsDir() { return errors.New("target dir is not a valid directory") } opts.TargetDir = strings.TrimSuffix(opts.TargetDir, "/") } pget.TargetDir = opts.TargetDir return nil }
go
func (pget *Pget) Ready() error { if procs := os.Getenv("GOMAXPROCS"); procs == "" { runtime.GOMAXPROCS(pget.Procs) } var opts Options if err := pget.parseOptions(&opts, os.Args[1:]); err != nil { return errors.Wrap(err, "failed to parse command line args") } if opts.Trace { pget.Trace = opts.Trace } if opts.Procs > 2 { pget.Procs = opts.Procs } if opts.Timeout > 0 { pget.timeout = opts.Timeout } if err := pget.parseURLs(); err != nil { return errors.Wrap(err, "failed to parse of url") } if opts.Output != "" { pget.Utils.SetFileName(opts.Output) } if opts.UserAgent != "" { pget.useragent = opts.UserAgent } if opts.Referer != "" { pget.referer = opts.Referer } if opts.TargetDir != "" { info, err := os.Stat(opts.TargetDir) if err != nil { if !os.IsNotExist(err) { return errors.Wrap(err, "target dir is invalid") } if err := os.MkdirAll(opts.TargetDir, 0755); err != nil { return errors.Wrapf(err, "failed to create diretory at %s", opts.TargetDir) } } else if !info.IsDir() { return errors.New("target dir is not a valid directory") } opts.TargetDir = strings.TrimSuffix(opts.TargetDir, "/") } pget.TargetDir = opts.TargetDir return nil }
[ "func", "(", "pget", "*", "Pget", ")", "Ready", "(", ")", "error", "{", "if", "procs", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", ";", "procs", "==", "\"", "\"", "{", "runtime", ".", "GOMAXPROCS", "(", "pget", ".", "Procs", ")", "\n", "}", "\n\n", "var", "opts", "Options", "\n", "if", "err", ":=", "pget", ".", "parseOptions", "(", "&", "opts", ",", "os", ".", "Args", "[", "1", ":", "]", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "opts", ".", "Trace", "{", "pget", ".", "Trace", "=", "opts", ".", "Trace", "\n", "}", "\n\n", "if", "opts", ".", "Procs", ">", "2", "{", "pget", ".", "Procs", "=", "opts", ".", "Procs", "\n", "}", "\n\n", "if", "opts", ".", "Timeout", ">", "0", "{", "pget", ".", "timeout", "=", "opts", ".", "Timeout", "\n", "}", "\n\n", "if", "err", ":=", "pget", ".", "parseURLs", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "opts", ".", "Output", "!=", "\"", "\"", "{", "pget", ".", "Utils", ".", "SetFileName", "(", "opts", ".", "Output", ")", "\n", "}", "\n\n", "if", "opts", ".", "UserAgent", "!=", "\"", "\"", "{", "pget", ".", "useragent", "=", "opts", ".", "UserAgent", "\n", "}", "\n\n", "if", "opts", ".", "Referer", "!=", "\"", "\"", "{", "pget", ".", "referer", "=", "opts", ".", "Referer", "\n", "}", "\n\n", "if", "opts", ".", "TargetDir", "!=", "\"", "\"", "{", "info", ",", "err", ":=", "os", ".", "Stat", "(", "opts", ".", "TargetDir", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "opts", ".", "TargetDir", ",", "0755", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "opts", ".", "TargetDir", ")", "\n", "}", "\n\n", "}", "else", "if", "!", "info", ".", "IsDir", "(", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "opts", ".", "TargetDir", "=", "strings", ".", "TrimSuffix", "(", "opts", ".", "TargetDir", ",", "\"", "\"", ")", "\n", "}", "\n", "pget", ".", "TargetDir", "=", "opts", ".", "TargetDir", "\n\n", "return", "nil", "\n", "}" ]
// Ready method define the variables required to Download.
[ "Ready", "method", "define", "the", "variables", "required", "to", "Download", "." ]
9294f7465fa777e5d9400500691e244a9a9ff225
https://github.com/Code-Hex/pget/blob/9294f7465fa777e5d9400500691e244a9a9ff225/pget.go#L89-L146
960
Code-Hex/pget
util.go
SetFullFileName
func (d *Data) SetFullFileName(directory, filename string) { if directory == "" { d.fullfilename = fmt.Sprintf("%s", filename) } else { d.fullfilename = fmt.Sprintf("%s/%s", directory, filename) } }
go
func (d *Data) SetFullFileName(directory, filename string) { if directory == "" { d.fullfilename = fmt.Sprintf("%s", filename) } else { d.fullfilename = fmt.Sprintf("%s/%s", directory, filename) } }
[ "func", "(", "d", "*", "Data", ")", "SetFullFileName", "(", "directory", ",", "filename", "string", ")", "{", "if", "directory", "==", "\"", "\"", "{", "d", ".", "fullfilename", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "filename", ")", "\n", "}", "else", "{", "d", ".", "fullfilename", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "directory", ",", "filename", ")", "\n", "}", "\n", "}" ]
// SetFullFileName set to Data structs member
[ "SetFullFileName", "set", "to", "Data", "structs", "member" ]
9294f7465fa777e5d9400500691e244a9a9ff225
https://github.com/Code-Hex/pget/blob/9294f7465fa777e5d9400500691e244a9a9ff225/util.go#L78-L84
961
Code-Hex/pget
util.go
URLFileName
func (d *Data) URLFileName(targetDir, url string) string { token := strings.Split(url, "/") // get of filename from url var original string for i := 1; original == ""; i++ { original = token[len(token)-i] } filename := original // create unique filename for i := 1; true; i++ { var filePath string if targetDir == "" { filePath = filename } else { filePath = fmt.Sprintf("%s/%s", targetDir, filename) } if _, err := os.Stat(filePath); err == nil { filename = fmt.Sprintf("%s-%d", original, i) } else { break } } return filename }
go
func (d *Data) URLFileName(targetDir, url string) string { token := strings.Split(url, "/") // get of filename from url var original string for i := 1; original == ""; i++ { original = token[len(token)-i] } filename := original // create unique filename for i := 1; true; i++ { var filePath string if targetDir == "" { filePath = filename } else { filePath = fmt.Sprintf("%s/%s", targetDir, filename) } if _, err := os.Stat(filePath); err == nil { filename = fmt.Sprintf("%s-%d", original, i) } else { break } } return filename }
[ "func", "(", "d", "*", "Data", ")", "URLFileName", "(", "targetDir", ",", "url", "string", ")", "string", "{", "token", ":=", "strings", ".", "Split", "(", "url", ",", "\"", "\"", ")", "\n\n", "// get of filename from url", "var", "original", "string", "\n", "for", "i", ":=", "1", ";", "original", "==", "\"", "\"", ";", "i", "++", "{", "original", "=", "token", "[", "len", "(", "token", ")", "-", "i", "]", "\n", "}", "\n\n", "filename", ":=", "original", "\n\n", "// create unique filename", "for", "i", ":=", "1", ";", "true", ";", "i", "++", "{", "var", "filePath", "string", "\n", "if", "targetDir", "==", "\"", "\"", "{", "filePath", "=", "filename", "\n", "}", "else", "{", "filePath", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "targetDir", ",", "filename", ")", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "filePath", ")", ";", "err", "==", "nil", "{", "filename", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "original", ",", "i", ")", "\n", "}", "else", "{", "break", "\n", "}", "\n", "}", "\n\n", "return", "filename", "\n", "}" ]
// URLFileName set to Data structs member using url
[ "URLFileName", "set", "to", "Data", "structs", "member", "using", "url" ]
9294f7465fa777e5d9400500691e244a9a9ff225
https://github.com/Code-Hex/pget/blob/9294f7465fa777e5d9400500691e244a9a9ff225/util.go#L92-L120
962
Code-Hex/pget
util.go
SetDirName
func (d *Data) SetDirName(path, filename string, procs int) { if path == "" { d.dirname = fmt.Sprintf("_%s.%d", filename, procs) } else { d.dirname = fmt.Sprintf("%s/_%s.%d", path, filename, procs) } }
go
func (d *Data) SetDirName(path, filename string, procs int) { if path == "" { d.dirname = fmt.Sprintf("_%s.%d", filename, procs) } else { d.dirname = fmt.Sprintf("%s/_%s.%d", path, filename, procs) } }
[ "func", "(", "d", "*", "Data", ")", "SetDirName", "(", "path", ",", "filename", "string", ",", "procs", "int", ")", "{", "if", "path", "==", "\"", "\"", "{", "d", ".", "dirname", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "filename", ",", "procs", ")", "\n", "}", "else", "{", "d", ".", "dirname", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "path", ",", "filename", ",", "procs", ")", "\n", "}", "\n\n", "}" ]
// SetDirName set to Data structs member
[ "SetDirName", "set", "to", "Data", "structs", "member" ]
9294f7465fa777e5d9400500691e244a9a9ff225
https://github.com/Code-Hex/pget/blob/9294f7465fa777e5d9400500691e244a9a9ff225/util.go#L123-L130
963
Code-Hex/pget
util.go
IsFree
func (d Data) IsFree(split uint) error { want := d.filesize + split if d.freeSpace() < want { return errors.Errorf("there is not sufficient free space in a disk") } return nil }
go
func (d Data) IsFree(split uint) error { want := d.filesize + split if d.freeSpace() < want { return errors.Errorf("there is not sufficient free space in a disk") } return nil }
[ "func", "(", "d", "Data", ")", "IsFree", "(", "split", "uint", ")", "error", "{", "want", ":=", "d", ".", "filesize", "+", "split", "\n", "if", "d", ".", "freeSpace", "(", ")", "<", "want", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// IsFree is check your disk space for size needed to download
[ "IsFree", "is", "check", "your", "disk", "space", "for", "size", "needed", "to", "download" ]
9294f7465fa777e5d9400500691e244a9a9ff225
https://github.com/Code-Hex/pget/blob/9294f7465fa777e5d9400500691e244a9a9ff225/util.go#L144-L151
964
Code-Hex/pget
util.go
MakeRange
func (d *Data) MakeRange(i, split, procs uint) Range { low := split * i high := low + split - 1 if i == procs-1 { high = d.FileSize() } return Range{ low: low, high: high, worker: i, } }
go
func (d *Data) MakeRange(i, split, procs uint) Range { low := split * i high := low + split - 1 if i == procs-1 { high = d.FileSize() } return Range{ low: low, high: high, worker: i, } }
[ "func", "(", "d", "*", "Data", ")", "MakeRange", "(", "i", ",", "split", ",", "procs", "uint", ")", "Range", "{", "low", ":=", "split", "*", "i", "\n", "high", ":=", "low", "+", "split", "-", "1", "\n", "if", "i", "==", "procs", "-", "1", "{", "high", "=", "d", ".", "FileSize", "(", ")", "\n", "}", "\n\n", "return", "Range", "{", "low", ":", "low", ",", "high", ":", "high", ",", "worker", ":", "i", ",", "}", "\n", "}" ]
// MakeRange will return Range struct to download function
[ "MakeRange", "will", "return", "Range", "struct", "to", "download", "function" ]
9294f7465fa777e5d9400500691e244a9a9ff225
https://github.com/Code-Hex/pget/blob/9294f7465fa777e5d9400500691e244a9a9ff225/util.go#L171-L183
965
Code-Hex/pget
util.go
ProgressBar
func (d Data) ProgressBar(ctx context.Context) error { filesize := int64(d.filesize) dirname := d.dirname bar := pb.New64(filesize) bar.Start() for { select { case <-ctx.Done(): return nil default: size, err := d.Progress(dirname) if err != nil { return errors.Wrap(err, "failed to get directory size") } if size < filesize { bar.Set64(size) } else { bar.Set64(filesize) bar.Finish() return nil } // To save cpu resource time.Sleep(100 * time.Millisecond) } } }
go
func (d Data) ProgressBar(ctx context.Context) error { filesize := int64(d.filesize) dirname := d.dirname bar := pb.New64(filesize) bar.Start() for { select { case <-ctx.Done(): return nil default: size, err := d.Progress(dirname) if err != nil { return errors.Wrap(err, "failed to get directory size") } if size < filesize { bar.Set64(size) } else { bar.Set64(filesize) bar.Finish() return nil } // To save cpu resource time.Sleep(100 * time.Millisecond) } } }
[ "func", "(", "d", "Data", ")", "ProgressBar", "(", "ctx", "context", ".", "Context", ")", "error", "{", "filesize", ":=", "int64", "(", "d", ".", "filesize", ")", "\n", "dirname", ":=", "d", ".", "dirname", "\n\n", "bar", ":=", "pb", ".", "New64", "(", "filesize", ")", "\n", "bar", ".", "Start", "(", ")", "\n\n", "for", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "nil", "\n", "default", ":", "size", ",", "err", ":=", "d", ".", "Progress", "(", "dirname", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "size", "<", "filesize", "{", "bar", ".", "Set64", "(", "size", ")", "\n", "}", "else", "{", "bar", ".", "Set64", "(", "filesize", ")", "\n", "bar", ".", "Finish", "(", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// To save cpu resource", "time", ".", "Sleep", "(", "100", "*", "time", ".", "Millisecond", ")", "\n", "}", "\n", "}", "\n", "}" ]
// ProgressBar is to show progressbar
[ "ProgressBar", "is", "to", "show", "progressbar" ]
9294f7465fa777e5d9400500691e244a9a9ff225
https://github.com/Code-Hex/pget/blob/9294f7465fa777e5d9400500691e244a9a9ff225/util.go#L186-L215
966
Code-Hex/pget
util.go
BindwithFiles
func (d *Data) BindwithFiles(procs int) error { fmt.Println("\nbinding with files...") filesize := d.filesize filename := d.filename dirname := d.dirname fh, err := os.Create(d.fullfilename) if err != nil { return errors.Wrap(err, "failed to create a file in download location") } defer fh.Close() bar := pb.New64(int64(filesize)) bar.Start() var f string for i := 0; i < procs; i++ { f = fmt.Sprintf("%s/%s.%d.%d", dirname, filename, procs, i) subfp, err := os.Open(f) if err != nil { return errors.Wrap(err, "failed to open "+f+" in download location") } proxy := bar.NewProxyReader(subfp) io.Copy(fh, proxy) // Not use defer subfp.Close() // remove a file in download location for join if err := os.Remove(f); err != nil { return errors.Wrap(err, "failed to remove a file in download location") } } bar.Finish() // remove download location // RemoveAll reason: will create .DS_Store in download location if execute on mac if err := os.RemoveAll(dirname); err != nil { return errors.Wrap(err, "failed to remove download location") } fmt.Println("Complete") return nil }
go
func (d *Data) BindwithFiles(procs int) error { fmt.Println("\nbinding with files...") filesize := d.filesize filename := d.filename dirname := d.dirname fh, err := os.Create(d.fullfilename) if err != nil { return errors.Wrap(err, "failed to create a file in download location") } defer fh.Close() bar := pb.New64(int64(filesize)) bar.Start() var f string for i := 0; i < procs; i++ { f = fmt.Sprintf("%s/%s.%d.%d", dirname, filename, procs, i) subfp, err := os.Open(f) if err != nil { return errors.Wrap(err, "failed to open "+f+" in download location") } proxy := bar.NewProxyReader(subfp) io.Copy(fh, proxy) // Not use defer subfp.Close() // remove a file in download location for join if err := os.Remove(f); err != nil { return errors.Wrap(err, "failed to remove a file in download location") } } bar.Finish() // remove download location // RemoveAll reason: will create .DS_Store in download location if execute on mac if err := os.RemoveAll(dirname); err != nil { return errors.Wrap(err, "failed to remove download location") } fmt.Println("Complete") return nil }
[ "func", "(", "d", "*", "Data", ")", "BindwithFiles", "(", "procs", "int", ")", "error", "{", "fmt", ".", "Println", "(", "\"", "\\n", "\"", ")", "\n\n", "filesize", ":=", "d", ".", "filesize", "\n", "filename", ":=", "d", ".", "filename", "\n", "dirname", ":=", "d", ".", "dirname", "\n\n", "fh", ",", "err", ":=", "os", ".", "Create", "(", "d", ".", "fullfilename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "defer", "fh", ".", "Close", "(", ")", "\n\n", "bar", ":=", "pb", ".", "New64", "(", "int64", "(", "filesize", ")", ")", "\n", "bar", ".", "Start", "(", ")", "\n\n", "var", "f", "string", "\n", "for", "i", ":=", "0", ";", "i", "<", "procs", ";", "i", "++", "{", "f", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "dirname", ",", "filename", ",", "procs", ",", "i", ")", "\n", "subfp", ",", "err", ":=", "os", ".", "Open", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", "+", "f", "+", "\"", "\"", ")", "\n", "}", "\n\n", "proxy", ":=", "bar", ".", "NewProxyReader", "(", "subfp", ")", "\n", "io", ".", "Copy", "(", "fh", ",", "proxy", ")", "\n\n", "// Not use defer", "subfp", ".", "Close", "(", ")", "\n\n", "// remove a file in download location for join", "if", "err", ":=", "os", ".", "Remove", "(", "f", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "bar", ".", "Finish", "(", ")", "\n\n", "// remove download location", "// RemoveAll reason: will create .DS_Store in download location if execute on mac", "if", "err", ":=", "os", ".", "RemoveAll", "(", "dirname", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n\n", "return", "nil", "\n", "}" ]
// BindwithFiles function for file binding after split download
[ "BindwithFiles", "function", "for", "file", "binding", "after", "split", "download" ]
9294f7465fa777e5d9400500691e244a9a9ff225
https://github.com/Code-Hex/pget/blob/9294f7465fa777e5d9400500691e244a9a9ff225/util.go#L218-L266
967
Code-Hex/pget
ch.go
MakeCh
func MakeCh() *Ch { return &Ch{ Err: make(chan error), Size: make(chan uint), Done: make(chan bool), } }
go
func MakeCh() *Ch { return &Ch{ Err: make(chan error), Size: make(chan uint), Done: make(chan bool), } }
[ "func", "MakeCh", "(", ")", "*", "Ch", "{", "return", "&", "Ch", "{", "Err", ":", "make", "(", "chan", "error", ")", ",", "Size", ":", "make", "(", "chan", "uint", ")", ",", "Done", ":", "make", "(", "chan", "bool", ")", ",", "}", "\n", "}" ]
// MakeCh instead of init
[ "MakeCh", "instead", "of", "init" ]
9294f7465fa777e5d9400500691e244a9a9ff225
https://github.com/Code-Hex/pget/blob/9294f7465fa777e5d9400500691e244a9a9ff225/ch.go#L16-L22
968
Code-Hex/pget
ch.go
Close
func (ch *Ch) Close() { close(ch.Err) close(ch.Size) close(ch.Done) }
go
func (ch *Ch) Close() { close(ch.Err) close(ch.Size) close(ch.Done) }
[ "func", "(", "ch", "*", "Ch", ")", "Close", "(", ")", "{", "close", "(", "ch", ".", "Err", ")", "\n", "close", "(", "ch", ".", "Size", ")", "\n", "close", "(", "ch", ".", "Done", ")", "\n", "}" ]
// Close method will close channel in Ch struct
[ "Close", "method", "will", "close", "channel", "in", "Ch", "struct" ]
9294f7465fa777e5d9400500691e244a9a9ff225
https://github.com/Code-Hex/pget/blob/9294f7465fa777e5d9400500691e244a9a9ff225/ch.go#L25-L29
969
Code-Hex/pget
ch.go
CheckingListen
func (ch *Ch) CheckingListen(ctx context.Context, cancelAll context.CancelFunc, totalActiveProcs int) (size uint, e error) { ContentLens := uint(0) for i := 0; i < totalActiveProcs; i++ { select { case <-ctx.Done(): i-- case err := <-ch.Err: if e != nil { cancelAll() } e = err case size = <-ch.Size: if ContentLens == 0 { ContentLens = size } else { if ContentLens != size { if e != nil { cancelAll() } e = errors.New("Not match the file on each mirrors") } } } } return }
go
func (ch *Ch) CheckingListen(ctx context.Context, cancelAll context.CancelFunc, totalActiveProcs int) (size uint, e error) { ContentLens := uint(0) for i := 0; i < totalActiveProcs; i++ { select { case <-ctx.Done(): i-- case err := <-ch.Err: if e != nil { cancelAll() } e = err case size = <-ch.Size: if ContentLens == 0 { ContentLens = size } else { if ContentLens != size { if e != nil { cancelAll() } e = errors.New("Not match the file on each mirrors") } } } } return }
[ "func", "(", "ch", "*", "Ch", ")", "CheckingListen", "(", "ctx", "context", ".", "Context", ",", "cancelAll", "context", ".", "CancelFunc", ",", "totalActiveProcs", "int", ")", "(", "size", "uint", ",", "e", "error", ")", "{", "ContentLens", ":=", "uint", "(", "0", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "totalActiveProcs", ";", "i", "++", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "i", "--", "\n", "case", "err", ":=", "<-", "ch", ".", "Err", ":", "if", "e", "!=", "nil", "{", "cancelAll", "(", ")", "\n", "}", "\n", "e", "=", "err", "\n", "case", "size", "=", "<-", "ch", ".", "Size", ":", "if", "ContentLens", "==", "0", "{", "ContentLens", "=", "size", "\n", "}", "else", "{", "if", "ContentLens", "!=", "size", "{", "if", "e", "!=", "nil", "{", "cancelAll", "(", ")", "\n", "}", "\n", "e", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "\n", "}" ]
// CheckingListen method wait all channels for Checking method in requests
[ "CheckingListen", "method", "wait", "all", "channels", "for", "Checking", "method", "in", "requests" ]
9294f7465fa777e5d9400500691e244a9a9ff225
https://github.com/Code-Hex/pget/blob/9294f7465fa777e5d9400500691e244a9a9ff225/ch.go#L32-L58
970
pierrec/xxHash
xxHash64/xxHash64.go
New
func New(seed uint64) hash.Hash64 { xxh := &xxHash{seed: seed} xxh.Reset() return xxh }
go
func New(seed uint64) hash.Hash64 { xxh := &xxHash{seed: seed} xxh.Reset() return xxh }
[ "func", "New", "(", "seed", "uint64", ")", "hash", ".", "Hash64", "{", "xxh", ":=", "&", "xxHash", "{", "seed", ":", "seed", "}", "\n", "xxh", ".", "Reset", "(", ")", "\n", "return", "xxh", "\n", "}" ]
// New returns a new Hash64 instance.
[ "New", "returns", "a", "new", "Hash64", "instance", "." ]
d17cb990ad2d219d5901415ceaeb50d17df59527
https://github.com/pierrec/xxHash/blob/d17cb990ad2d219d5901415ceaeb50d17df59527/xxHash64/xxHash64.go#L27-L31
971
pierrec/xxHash
xxHash64/xxHash64.go
Sum64
func (xxh *xxHash) Sum64() uint64 { var h64 uint64 if xxh.totalLen >= 32 { h64 = rol1(xxh.v1) + rol7(xxh.v2) + rol12(xxh.v3) + rol18(xxh.v4) xxh.v1 *= prime64_2 xxh.v2 *= prime64_2 xxh.v3 *= prime64_2 xxh.v4 *= prime64_2 h64 = (h64^(rol31(xxh.v1)*prime64_1))*prime64_1 + prime64_4 h64 = (h64^(rol31(xxh.v2)*prime64_1))*prime64_1 + prime64_4 h64 = (h64^(rol31(xxh.v3)*prime64_1))*prime64_1 + prime64_4 h64 = (h64^(rol31(xxh.v4)*prime64_1))*prime64_1 + prime64_4 h64 += xxh.totalLen } else { h64 = xxh.seed + prime64_5 + xxh.totalLen } p := 0 n := xxh.bufused for n := n - 8; p <= n; p += 8 { h64 ^= rol31(u64(xxh.buf[p:p+8])*prime64_2) * prime64_1 h64 = rol27(h64)*prime64_1 + prime64_4 } if p+4 <= n { sub := xxh.buf[p : p+4] h64 ^= uint64(u32(sub)) * prime64_1 h64 = rol23(h64)*prime64_2 + prime64_3 p += 4 } for ; p < n; p++ { h64 ^= uint64(xxh.buf[p]) * prime64_5 h64 = rol11(h64) * prime64_1 } h64 ^= h64 >> 33 h64 *= prime64_2 h64 ^= h64 >> 29 h64 *= prime64_3 h64 ^= h64 >> 32 return h64 }
go
func (xxh *xxHash) Sum64() uint64 { var h64 uint64 if xxh.totalLen >= 32 { h64 = rol1(xxh.v1) + rol7(xxh.v2) + rol12(xxh.v3) + rol18(xxh.v4) xxh.v1 *= prime64_2 xxh.v2 *= prime64_2 xxh.v3 *= prime64_2 xxh.v4 *= prime64_2 h64 = (h64^(rol31(xxh.v1)*prime64_1))*prime64_1 + prime64_4 h64 = (h64^(rol31(xxh.v2)*prime64_1))*prime64_1 + prime64_4 h64 = (h64^(rol31(xxh.v3)*prime64_1))*prime64_1 + prime64_4 h64 = (h64^(rol31(xxh.v4)*prime64_1))*prime64_1 + prime64_4 h64 += xxh.totalLen } else { h64 = xxh.seed + prime64_5 + xxh.totalLen } p := 0 n := xxh.bufused for n := n - 8; p <= n; p += 8 { h64 ^= rol31(u64(xxh.buf[p:p+8])*prime64_2) * prime64_1 h64 = rol27(h64)*prime64_1 + prime64_4 } if p+4 <= n { sub := xxh.buf[p : p+4] h64 ^= uint64(u32(sub)) * prime64_1 h64 = rol23(h64)*prime64_2 + prime64_3 p += 4 } for ; p < n; p++ { h64 ^= uint64(xxh.buf[p]) * prime64_5 h64 = rol11(h64) * prime64_1 } h64 ^= h64 >> 33 h64 *= prime64_2 h64 ^= h64 >> 29 h64 *= prime64_3 h64 ^= h64 >> 32 return h64 }
[ "func", "(", "xxh", "*", "xxHash", ")", "Sum64", "(", ")", "uint64", "{", "var", "h64", "uint64", "\n", "if", "xxh", ".", "totalLen", ">=", "32", "{", "h64", "=", "rol1", "(", "xxh", ".", "v1", ")", "+", "rol7", "(", "xxh", ".", "v2", ")", "+", "rol12", "(", "xxh", ".", "v3", ")", "+", "rol18", "(", "xxh", ".", "v4", ")", "\n\n", "xxh", ".", "v1", "*=", "prime64_2", "\n", "xxh", ".", "v2", "*=", "prime64_2", "\n", "xxh", ".", "v3", "*=", "prime64_2", "\n", "xxh", ".", "v4", "*=", "prime64_2", "\n\n", "h64", "=", "(", "h64", "^", "(", "rol31", "(", "xxh", ".", "v1", ")", "*", "prime64_1", ")", ")", "*", "prime64_1", "+", "prime64_4", "\n", "h64", "=", "(", "h64", "^", "(", "rol31", "(", "xxh", ".", "v2", ")", "*", "prime64_1", ")", ")", "*", "prime64_1", "+", "prime64_4", "\n", "h64", "=", "(", "h64", "^", "(", "rol31", "(", "xxh", ".", "v3", ")", "*", "prime64_1", ")", ")", "*", "prime64_1", "+", "prime64_4", "\n", "h64", "=", "(", "h64", "^", "(", "rol31", "(", "xxh", ".", "v4", ")", "*", "prime64_1", ")", ")", "*", "prime64_1", "+", "prime64_4", "\n\n", "h64", "+=", "xxh", ".", "totalLen", "\n", "}", "else", "{", "h64", "=", "xxh", ".", "seed", "+", "prime64_5", "+", "xxh", ".", "totalLen", "\n", "}", "\n\n", "p", ":=", "0", "\n", "n", ":=", "xxh", ".", "bufused", "\n", "for", "n", ":=", "n", "-", "8", ";", "p", "<=", "n", ";", "p", "+=", "8", "{", "h64", "^=", "rol31", "(", "u64", "(", "xxh", ".", "buf", "[", "p", ":", "p", "+", "8", "]", ")", "*", "prime64_2", ")", "*", "prime64_1", "\n", "h64", "=", "rol27", "(", "h64", ")", "*", "prime64_1", "+", "prime64_4", "\n", "}", "\n", "if", "p", "+", "4", "<=", "n", "{", "sub", ":=", "xxh", ".", "buf", "[", "p", ":", "p", "+", "4", "]", "\n", "h64", "^=", "uint64", "(", "u32", "(", "sub", ")", ")", "*", "prime64_1", "\n", "h64", "=", "rol23", "(", "h64", ")", "*", "prime64_2", "+", "prime64_3", "\n", "p", "+=", "4", "\n", "}", "\n", "for", ";", "p", "<", "n", ";", "p", "++", "{", "h64", "^=", "uint64", "(", "xxh", ".", "buf", "[", "p", "]", ")", "*", "prime64_5", "\n", "h64", "=", "rol11", "(", "h64", ")", "*", "prime64_1", "\n", "}", "\n\n", "h64", "^=", "h64", ">>", "33", "\n", "h64", "*=", "prime64_2", "\n", "h64", "^=", "h64", ">>", "29", "\n", "h64", "*=", "prime64_3", "\n", "h64", "^=", "h64", ">>", "32", "\n\n", "return", "h64", "\n", "}" ]
// Sum64 returns the 64bits Hash value.
[ "Sum64", "returns", "the", "64bits", "Hash", "value", "." ]
d17cb990ad2d219d5901415ceaeb50d17df59527
https://github.com/pierrec/xxHash/blob/d17cb990ad2d219d5901415ceaeb50d17df59527/xxHash64/xxHash64.go#L108-L152
972
pierrec/xxHash
xxHash64/xxHash64.go
Checksum
func Checksum(input []byte, seed uint64) uint64 { n := len(input) var h64 uint64 if n >= 32 { v1 := seed + prime64_1 + prime64_2 v2 := seed + prime64_2 v3 := seed v4 := seed - prime64_1 p := 0 for n := n - 32; p <= n; p += 32 { sub := input[p:][:32] //BCE hint for compiler v1 = rol31(v1+u64(sub[:])*prime64_2) * prime64_1 v2 = rol31(v2+u64(sub[8:])*prime64_2) * prime64_1 v3 = rol31(v3+u64(sub[16:])*prime64_2) * prime64_1 v4 = rol31(v4+u64(sub[24:])*prime64_2) * prime64_1 } h64 = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) v1 *= prime64_2 v2 *= prime64_2 v3 *= prime64_2 v4 *= prime64_2 h64 = (h64^(rol31(v1)*prime64_1))*prime64_1 + prime64_4 h64 = (h64^(rol31(v2)*prime64_1))*prime64_1 + prime64_4 h64 = (h64^(rol31(v3)*prime64_1))*prime64_1 + prime64_4 h64 = (h64^(rol31(v4)*prime64_1))*prime64_1 + prime64_4 h64 += uint64(n) input = input[p:] n -= p } else { h64 = seed + prime64_5 + uint64(n) } p := 0 for n := n - 8; p <= n; p += 8 { sub := input[p : p+8] h64 ^= rol31(u64(sub)*prime64_2) * prime64_1 h64 = rol27(h64)*prime64_1 + prime64_4 } if p+4 <= n { sub := input[p : p+4] h64 ^= uint64(u32(sub)) * prime64_1 h64 = rol23(h64)*prime64_2 + prime64_3 p += 4 } for ; p < n; p++ { h64 ^= uint64(input[p]) * prime64_5 h64 = rol11(h64) * prime64_1 } h64 ^= h64 >> 33 h64 *= prime64_2 h64 ^= h64 >> 29 h64 *= prime64_3 h64 ^= h64 >> 32 return h64 }
go
func Checksum(input []byte, seed uint64) uint64 { n := len(input) var h64 uint64 if n >= 32 { v1 := seed + prime64_1 + prime64_2 v2 := seed + prime64_2 v3 := seed v4 := seed - prime64_1 p := 0 for n := n - 32; p <= n; p += 32 { sub := input[p:][:32] //BCE hint for compiler v1 = rol31(v1+u64(sub[:])*prime64_2) * prime64_1 v2 = rol31(v2+u64(sub[8:])*prime64_2) * prime64_1 v3 = rol31(v3+u64(sub[16:])*prime64_2) * prime64_1 v4 = rol31(v4+u64(sub[24:])*prime64_2) * prime64_1 } h64 = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) v1 *= prime64_2 v2 *= prime64_2 v3 *= prime64_2 v4 *= prime64_2 h64 = (h64^(rol31(v1)*prime64_1))*prime64_1 + prime64_4 h64 = (h64^(rol31(v2)*prime64_1))*prime64_1 + prime64_4 h64 = (h64^(rol31(v3)*prime64_1))*prime64_1 + prime64_4 h64 = (h64^(rol31(v4)*prime64_1))*prime64_1 + prime64_4 h64 += uint64(n) input = input[p:] n -= p } else { h64 = seed + prime64_5 + uint64(n) } p := 0 for n := n - 8; p <= n; p += 8 { sub := input[p : p+8] h64 ^= rol31(u64(sub)*prime64_2) * prime64_1 h64 = rol27(h64)*prime64_1 + prime64_4 } if p+4 <= n { sub := input[p : p+4] h64 ^= uint64(u32(sub)) * prime64_1 h64 = rol23(h64)*prime64_2 + prime64_3 p += 4 } for ; p < n; p++ { h64 ^= uint64(input[p]) * prime64_5 h64 = rol11(h64) * prime64_1 } h64 ^= h64 >> 33 h64 *= prime64_2 h64 ^= h64 >> 29 h64 *= prime64_3 h64 ^= h64 >> 32 return h64 }
[ "func", "Checksum", "(", "input", "[", "]", "byte", ",", "seed", "uint64", ")", "uint64", "{", "n", ":=", "len", "(", "input", ")", "\n", "var", "h64", "uint64", "\n\n", "if", "n", ">=", "32", "{", "v1", ":=", "seed", "+", "prime64_1", "+", "prime64_2", "\n", "v2", ":=", "seed", "+", "prime64_2", "\n", "v3", ":=", "seed", "\n", "v4", ":=", "seed", "-", "prime64_1", "\n", "p", ":=", "0", "\n", "for", "n", ":=", "n", "-", "32", ";", "p", "<=", "n", ";", "p", "+=", "32", "{", "sub", ":=", "input", "[", "p", ":", "]", "[", ":", "32", "]", "//BCE hint for compiler", "\n", "v1", "=", "rol31", "(", "v1", "+", "u64", "(", "sub", "[", ":", "]", ")", "*", "prime64_2", ")", "*", "prime64_1", "\n", "v2", "=", "rol31", "(", "v2", "+", "u64", "(", "sub", "[", "8", ":", "]", ")", "*", "prime64_2", ")", "*", "prime64_1", "\n", "v3", "=", "rol31", "(", "v3", "+", "u64", "(", "sub", "[", "16", ":", "]", ")", "*", "prime64_2", ")", "*", "prime64_1", "\n", "v4", "=", "rol31", "(", "v4", "+", "u64", "(", "sub", "[", "24", ":", "]", ")", "*", "prime64_2", ")", "*", "prime64_1", "\n", "}", "\n\n", "h64", "=", "rol1", "(", "v1", ")", "+", "rol7", "(", "v2", ")", "+", "rol12", "(", "v3", ")", "+", "rol18", "(", "v4", ")", "\n\n", "v1", "*=", "prime64_2", "\n", "v2", "*=", "prime64_2", "\n", "v3", "*=", "prime64_2", "\n", "v4", "*=", "prime64_2", "\n\n", "h64", "=", "(", "h64", "^", "(", "rol31", "(", "v1", ")", "*", "prime64_1", ")", ")", "*", "prime64_1", "+", "prime64_4", "\n", "h64", "=", "(", "h64", "^", "(", "rol31", "(", "v2", ")", "*", "prime64_1", ")", ")", "*", "prime64_1", "+", "prime64_4", "\n", "h64", "=", "(", "h64", "^", "(", "rol31", "(", "v3", ")", "*", "prime64_1", ")", ")", "*", "prime64_1", "+", "prime64_4", "\n", "h64", "=", "(", "h64", "^", "(", "rol31", "(", "v4", ")", "*", "prime64_1", ")", ")", "*", "prime64_1", "+", "prime64_4", "\n\n", "h64", "+=", "uint64", "(", "n", ")", "\n\n", "input", "=", "input", "[", "p", ":", "]", "\n", "n", "-=", "p", "\n", "}", "else", "{", "h64", "=", "seed", "+", "prime64_5", "+", "uint64", "(", "n", ")", "\n", "}", "\n\n", "p", ":=", "0", "\n", "for", "n", ":=", "n", "-", "8", ";", "p", "<=", "n", ";", "p", "+=", "8", "{", "sub", ":=", "input", "[", "p", ":", "p", "+", "8", "]", "\n", "h64", "^=", "rol31", "(", "u64", "(", "sub", ")", "*", "prime64_2", ")", "*", "prime64_1", "\n", "h64", "=", "rol27", "(", "h64", ")", "*", "prime64_1", "+", "prime64_4", "\n", "}", "\n", "if", "p", "+", "4", "<=", "n", "{", "sub", ":=", "input", "[", "p", ":", "p", "+", "4", "]", "\n", "h64", "^=", "uint64", "(", "u32", "(", "sub", ")", ")", "*", "prime64_1", "\n", "h64", "=", "rol23", "(", "h64", ")", "*", "prime64_2", "+", "prime64_3", "\n", "p", "+=", "4", "\n", "}", "\n", "for", ";", "p", "<", "n", ";", "p", "++", "{", "h64", "^=", "uint64", "(", "input", "[", "p", "]", ")", "*", "prime64_5", "\n", "h64", "=", "rol11", "(", "h64", ")", "*", "prime64_1", "\n", "}", "\n\n", "h64", "^=", "h64", ">>", "33", "\n", "h64", "*=", "prime64_2", "\n", "h64", "^=", "h64", ">>", "29", "\n", "h64", "*=", "prime64_3", "\n", "h64", "^=", "h64", ">>", "32", "\n\n", "return", "h64", "\n", "}" ]
// Checksum returns the 64bits Hash value.
[ "Checksum", "returns", "the", "64bits", "Hash", "value", "." ]
d17cb990ad2d219d5901415ceaeb50d17df59527
https://github.com/pierrec/xxHash/blob/d17cb990ad2d219d5901415ceaeb50d17df59527/xxHash64/xxHash64.go#L155-L217
973
pierrec/xxHash
xxHash32/xxHash32.go
New
func New(seed uint32) hash.Hash32 { xxh := &xxHash{seed: seed} xxh.Reset() return xxh }
go
func New(seed uint32) hash.Hash32 { xxh := &xxHash{seed: seed} xxh.Reset() return xxh }
[ "func", "New", "(", "seed", "uint32", ")", "hash", ".", "Hash32", "{", "xxh", ":=", "&", "xxHash", "{", "seed", ":", "seed", "}", "\n", "xxh", ".", "Reset", "(", ")", "\n", "return", "xxh", "\n", "}" ]
// New returns a new Hash32 instance.
[ "New", "returns", "a", "new", "Hash32", "instance", "." ]
d17cb990ad2d219d5901415ceaeb50d17df59527
https://github.com/pierrec/xxHash/blob/d17cb990ad2d219d5901415ceaeb50d17df59527/xxHash32/xxHash32.go#L27-L31
974
pierrec/xxHash
xxHash32/xxHash32.go
Sum32
func (xxh *xxHash) Sum32() uint32 { h32 := uint32(xxh.totalLen) if xxh.totalLen >= 16 { h32 += rol1(xxh.v1) + rol7(xxh.v2) + rol12(xxh.v3) + rol18(xxh.v4) } else { h32 += xxh.seed + prime32_5 } p := 0 n := xxh.bufused for n := n - 4; p <= n; p += 4 { h32 += u32(xxh.buf[p:p+4]) * prime32_3 h32 = rol17(h32) * prime32_4 } for ; p < n; p++ { h32 += uint32(xxh.buf[p]) * prime32_5 h32 = rol11(h32) * prime32_1 } h32 ^= h32 >> 15 h32 *= prime32_2 h32 ^= h32 >> 13 h32 *= prime32_3 h32 ^= h32 >> 16 return h32 }
go
func (xxh *xxHash) Sum32() uint32 { h32 := uint32(xxh.totalLen) if xxh.totalLen >= 16 { h32 += rol1(xxh.v1) + rol7(xxh.v2) + rol12(xxh.v3) + rol18(xxh.v4) } else { h32 += xxh.seed + prime32_5 } p := 0 n := xxh.bufused for n := n - 4; p <= n; p += 4 { h32 += u32(xxh.buf[p:p+4]) * prime32_3 h32 = rol17(h32) * prime32_4 } for ; p < n; p++ { h32 += uint32(xxh.buf[p]) * prime32_5 h32 = rol11(h32) * prime32_1 } h32 ^= h32 >> 15 h32 *= prime32_2 h32 ^= h32 >> 13 h32 *= prime32_3 h32 ^= h32 >> 16 return h32 }
[ "func", "(", "xxh", "*", "xxHash", ")", "Sum32", "(", ")", "uint32", "{", "h32", ":=", "uint32", "(", "xxh", ".", "totalLen", ")", "\n", "if", "xxh", ".", "totalLen", ">=", "16", "{", "h32", "+=", "rol1", "(", "xxh", ".", "v1", ")", "+", "rol7", "(", "xxh", ".", "v2", ")", "+", "rol12", "(", "xxh", ".", "v3", ")", "+", "rol18", "(", "xxh", ".", "v4", ")", "\n", "}", "else", "{", "h32", "+=", "xxh", ".", "seed", "+", "prime32_5", "\n", "}", "\n\n", "p", ":=", "0", "\n", "n", ":=", "xxh", ".", "bufused", "\n", "for", "n", ":=", "n", "-", "4", ";", "p", "<=", "n", ";", "p", "+=", "4", "{", "h32", "+=", "u32", "(", "xxh", ".", "buf", "[", "p", ":", "p", "+", "4", "]", ")", "*", "prime32_3", "\n", "h32", "=", "rol17", "(", "h32", ")", "*", "prime32_4", "\n", "}", "\n", "for", ";", "p", "<", "n", ";", "p", "++", "{", "h32", "+=", "uint32", "(", "xxh", ".", "buf", "[", "p", "]", ")", "*", "prime32_5", "\n", "h32", "=", "rol11", "(", "h32", ")", "*", "prime32_1", "\n", "}", "\n\n", "h32", "^=", "h32", ">>", "15", "\n", "h32", "*=", "prime32_2", "\n", "h32", "^=", "h32", ">>", "13", "\n", "h32", "*=", "prime32_3", "\n", "h32", "^=", "h32", ">>", "16", "\n\n", "return", "h32", "\n", "}" ]
// Sum32 returns the 32 bits Hash value.
[ "Sum32", "returns", "the", "32", "bits", "Hash", "value", "." ]
d17cb990ad2d219d5901415ceaeb50d17df59527
https://github.com/pierrec/xxHash/blob/d17cb990ad2d219d5901415ceaeb50d17df59527/xxHash32/xxHash32.go#L108-L134
975
pierrec/xxHash
xxHash32/xxHash32.go
Checksum
func Checksum(input []byte, seed uint32) uint32 { n := len(input) h32 := uint32(n) if n < 16 { h32 += seed + prime32_5 } else { v1 := seed + prime32_1 + prime32_2 v2 := seed + prime32_2 v3 := seed v4 := seed - prime32_1 p := 0 for n := n - 16; p <= n; p += 16 { sub := input[p:][:16] //BCE hint for compiler v1 = rol13(v1+u32(sub[:])*prime32_2) * prime32_1 v2 = rol13(v2+u32(sub[4:])*prime32_2) * prime32_1 v3 = rol13(v3+u32(sub[8:])*prime32_2) * prime32_1 v4 = rol13(v4+u32(sub[12:])*prime32_2) * prime32_1 } input = input[p:] n -= p h32 += rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) } p := 0 for n := n - 4; p <= n; p += 4 { h32 += u32(input[p:p+4]) * prime32_3 h32 = rol17(h32) * prime32_4 } for p < n { h32 += uint32(input[p]) * prime32_5 h32 = rol11(h32) * prime32_1 p++ } h32 ^= h32 >> 15 h32 *= prime32_2 h32 ^= h32 >> 13 h32 *= prime32_3 h32 ^= h32 >> 16 return h32 }
go
func Checksum(input []byte, seed uint32) uint32 { n := len(input) h32 := uint32(n) if n < 16 { h32 += seed + prime32_5 } else { v1 := seed + prime32_1 + prime32_2 v2 := seed + prime32_2 v3 := seed v4 := seed - prime32_1 p := 0 for n := n - 16; p <= n; p += 16 { sub := input[p:][:16] //BCE hint for compiler v1 = rol13(v1+u32(sub[:])*prime32_2) * prime32_1 v2 = rol13(v2+u32(sub[4:])*prime32_2) * prime32_1 v3 = rol13(v3+u32(sub[8:])*prime32_2) * prime32_1 v4 = rol13(v4+u32(sub[12:])*prime32_2) * prime32_1 } input = input[p:] n -= p h32 += rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) } p := 0 for n := n - 4; p <= n; p += 4 { h32 += u32(input[p:p+4]) * prime32_3 h32 = rol17(h32) * prime32_4 } for p < n { h32 += uint32(input[p]) * prime32_5 h32 = rol11(h32) * prime32_1 p++ } h32 ^= h32 >> 15 h32 *= prime32_2 h32 ^= h32 >> 13 h32 *= prime32_3 h32 ^= h32 >> 16 return h32 }
[ "func", "Checksum", "(", "input", "[", "]", "byte", ",", "seed", "uint32", ")", "uint32", "{", "n", ":=", "len", "(", "input", ")", "\n", "h32", ":=", "uint32", "(", "n", ")", "\n\n", "if", "n", "<", "16", "{", "h32", "+=", "seed", "+", "prime32_5", "\n", "}", "else", "{", "v1", ":=", "seed", "+", "prime32_1", "+", "prime32_2", "\n", "v2", ":=", "seed", "+", "prime32_2", "\n", "v3", ":=", "seed", "\n", "v4", ":=", "seed", "-", "prime32_1", "\n", "p", ":=", "0", "\n", "for", "n", ":=", "n", "-", "16", ";", "p", "<=", "n", ";", "p", "+=", "16", "{", "sub", ":=", "input", "[", "p", ":", "]", "[", ":", "16", "]", "//BCE hint for compiler", "\n", "v1", "=", "rol13", "(", "v1", "+", "u32", "(", "sub", "[", ":", "]", ")", "*", "prime32_2", ")", "*", "prime32_1", "\n", "v2", "=", "rol13", "(", "v2", "+", "u32", "(", "sub", "[", "4", ":", "]", ")", "*", "prime32_2", ")", "*", "prime32_1", "\n", "v3", "=", "rol13", "(", "v3", "+", "u32", "(", "sub", "[", "8", ":", "]", ")", "*", "prime32_2", ")", "*", "prime32_1", "\n", "v4", "=", "rol13", "(", "v4", "+", "u32", "(", "sub", "[", "12", ":", "]", ")", "*", "prime32_2", ")", "*", "prime32_1", "\n", "}", "\n", "input", "=", "input", "[", "p", ":", "]", "\n", "n", "-=", "p", "\n", "h32", "+=", "rol1", "(", "v1", ")", "+", "rol7", "(", "v2", ")", "+", "rol12", "(", "v3", ")", "+", "rol18", "(", "v4", ")", "\n", "}", "\n\n", "p", ":=", "0", "\n", "for", "n", ":=", "n", "-", "4", ";", "p", "<=", "n", ";", "p", "+=", "4", "{", "h32", "+=", "u32", "(", "input", "[", "p", ":", "p", "+", "4", "]", ")", "*", "prime32_3", "\n", "h32", "=", "rol17", "(", "h32", ")", "*", "prime32_4", "\n", "}", "\n", "for", "p", "<", "n", "{", "h32", "+=", "uint32", "(", "input", "[", "p", "]", ")", "*", "prime32_5", "\n", "h32", "=", "rol11", "(", "h32", ")", "*", "prime32_1", "\n", "p", "++", "\n", "}", "\n\n", "h32", "^=", "h32", ">>", "15", "\n", "h32", "*=", "prime32_2", "\n", "h32", "^=", "h32", ">>", "13", "\n", "h32", "*=", "prime32_3", "\n", "h32", "^=", "h32", ">>", "16", "\n\n", "return", "h32", "\n", "}" ]
// Checksum returns the 32bits Hash value.
[ "Checksum", "returns", "the", "32bits", "Hash", "value", "." ]
d17cb990ad2d219d5901415ceaeb50d17df59527
https://github.com/pierrec/xxHash/blob/d17cb990ad2d219d5901415ceaeb50d17df59527/xxHash32/xxHash32.go#L137-L179
976
sethgrid/pester
sample/main.go
randoHandler
func randoHandler(w http.ResponseWriter, r *http.Request) { delay := rand.Intn(5000) var code int switch rand.Intn(10) { case 0: code = 404 case 1: code = 400 case 2: code = 501 case 3: code = 500 default: code = 200 } log.Printf("incoming request on :9000 - will return %d in %d ms", code, delay) <-time.Tick(time.Duration(delay) * time.Millisecond) w.WriteHeader(code) w.Write([]byte(http.StatusText(code))) }
go
func randoHandler(w http.ResponseWriter, r *http.Request) { delay := rand.Intn(5000) var code int switch rand.Intn(10) { case 0: code = 404 case 1: code = 400 case 2: code = 501 case 3: code = 500 default: code = 200 } log.Printf("incoming request on :9000 - will return %d in %d ms", code, delay) <-time.Tick(time.Duration(delay) * time.Millisecond) w.WriteHeader(code) w.Write([]byte(http.StatusText(code))) }
[ "func", "randoHandler", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "delay", ":=", "rand", ".", "Intn", "(", "5000", ")", "\n", "var", "code", "int", "\n", "switch", "rand", ".", "Intn", "(", "10", ")", "{", "case", "0", ":", "code", "=", "404", "\n", "case", "1", ":", "code", "=", "400", "\n", "case", "2", ":", "code", "=", "501", "\n", "case", "3", ":", "code", "=", "500", "\n", "default", ":", "code", "=", "200", "\n", "}", "\n\n", "log", ".", "Printf", "(", "\"", "\"", ",", "code", ",", "delay", ")", "\n\n", "<-", "time", ".", "Tick", "(", "time", ".", "Duration", "(", "delay", ")", "*", "time", ".", "Millisecond", ")", "\n\n", "w", ".", "WriteHeader", "(", "code", ")", "\n", "w", ".", "Write", "(", "[", "]", "byte", "(", "http", ".", "StatusText", "(", "code", ")", ")", ")", "\n", "}" ]
// randoHandler will cause random delays and give random status responses
[ "randoHandler", "will", "cause", "random", "delays", "and", "give", "random", "status", "responses" ]
68a33a018ad0ac8266f272ec669307a1829c0486
https://github.com/sethgrid/pester/blob/68a33a018ad0ac8266f272ec669307a1829c0486/sample/main.go#L162-L184
977
sethgrid/pester
pester.go
New
func New() *Client { return &Client{ Concurrency: DefaultClient.Concurrency, MaxRetries: DefaultClient.MaxRetries, Backoff: DefaultClient.Backoff, ErrLog: DefaultClient.ErrLog, wg: &sync.WaitGroup{}, RetryOnHTTP429: false, } }
go
func New() *Client { return &Client{ Concurrency: DefaultClient.Concurrency, MaxRetries: DefaultClient.MaxRetries, Backoff: DefaultClient.Backoff, ErrLog: DefaultClient.ErrLog, wg: &sync.WaitGroup{}, RetryOnHTTP429: false, } }
[ "func", "New", "(", ")", "*", "Client", "{", "return", "&", "Client", "{", "Concurrency", ":", "DefaultClient", ".", "Concurrency", ",", "MaxRetries", ":", "DefaultClient", ".", "MaxRetries", ",", "Backoff", ":", "DefaultClient", ".", "Backoff", ",", "ErrLog", ":", "DefaultClient", ".", "ErrLog", ",", "wg", ":", "&", "sync", ".", "WaitGroup", "{", "}", ",", "RetryOnHTTP429", ":", "false", ",", "}", "\n", "}" ]
// New constructs a new DefaultClient with sensible default values
[ "New", "constructs", "a", "new", "DefaultClient", "with", "sensible", "default", "values" ]
68a33a018ad0ac8266f272ec669307a1829c0486
https://github.com/sethgrid/pester/blob/68a33a018ad0ac8266f272ec669307a1829c0486/pester.go#L95-L104
978
sethgrid/pester
pester.go
NewExtendedClient
func NewExtendedClient(hc *http.Client) *Client { c := New() c.hc = hc return c }
go
func NewExtendedClient(hc *http.Client) *Client { c := New() c.hc = hc return c }
[ "func", "NewExtendedClient", "(", "hc", "*", "http", ".", "Client", ")", "*", "Client", "{", "c", ":=", "New", "(", ")", "\n", "c", ".", "hc", "=", "hc", "\n", "return", "c", "\n", "}" ]
// NewExtendedClient allows you to pass in an http.Client that is previously set up // and extends it to have Pester's features of concurrency and retries.
[ "NewExtendedClient", "allows", "you", "to", "pass", "in", "an", "http", ".", "Client", "that", "is", "previously", "set", "up", "and", "extends", "it", "to", "have", "Pester", "s", "features", "of", "concurrency", "and", "retries", "." ]
68a33a018ad0ac8266f272ec669307a1829c0486
https://github.com/sethgrid/pester/blob/68a33a018ad0ac8266f272ec669307a1829c0486/pester.go#L108-L112
979
sethgrid/pester
pester.go
ExponentialBackoff
func ExponentialBackoff(i int) time.Duration { return time.Duration(1<<uint(i)) * time.Second }
go
func ExponentialBackoff(i int) time.Duration { return time.Duration(1<<uint(i)) * time.Second }
[ "func", "ExponentialBackoff", "(", "i", "int", ")", "time", ".", "Duration", "{", "return", "time", ".", "Duration", "(", "1", "<<", "uint", "(", "i", ")", ")", "*", "time", ".", "Second", "\n", "}" ]
// ExponentialBackoff returns ever increasing backoffs by a power of 2
[ "ExponentialBackoff", "returns", "ever", "increasing", "backoffs", "by", "a", "power", "of", "2" ]
68a33a018ad0ac8266f272ec669307a1829c0486
https://github.com/sethgrid/pester/blob/68a33a018ad0ac8266f272ec669307a1829c0486/pester.go#L130-L132
980
sethgrid/pester
pester.go
LinearBackoff
func LinearBackoff(i int) time.Duration { return time.Duration(i) * time.Second }
go
func LinearBackoff(i int) time.Duration { return time.Duration(i) * time.Second }
[ "func", "LinearBackoff", "(", "i", "int", ")", "time", ".", "Duration", "{", "return", "time", ".", "Duration", "(", "i", ")", "*", "time", ".", "Second", "\n", "}" ]
// LinearBackoff returns increasing durations, each a second longer than the last
[ "LinearBackoff", "returns", "increasing", "durations", "each", "a", "second", "longer", "than", "the", "last" ]
68a33a018ad0ac8266f272ec669307a1829c0486
https://github.com/sethgrid/pester/blob/68a33a018ad0ac8266f272ec669307a1829c0486/pester.go#L141-L143
981
sethgrid/pester
pester.go
LogString
func (c *Client) LogString() string { c.Lock() defer c.Unlock() var res string for _, e := range c.ErrLog { res += c.FormatError(e) } return res }
go
func (c *Client) LogString() string { c.Lock() defer c.Unlock() var res string for _, e := range c.ErrLog { res += c.FormatError(e) } return res }
[ "func", "(", "c", "*", "Client", ")", "LogString", "(", ")", "string", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n", "var", "res", "string", "\n", "for", "_", ",", "e", ":=", "range", "c", ".", "ErrLog", "{", "res", "+=", "c", ".", "FormatError", "(", "e", ")", "\n", "}", "\n", "return", "res", "\n", "}" ]
// LogString provides a string representation of the errors the client has seen
[ "LogString", "provides", "a", "string", "representation", "of", "the", "errors", "the", "client", "has", "seen" ]
68a33a018ad0ac8266f272ec669307a1829c0486
https://github.com/sethgrid/pester/blob/68a33a018ad0ac8266f272ec669307a1829c0486/pester.go#L361-L369
982
sethgrid/pester
pester.go
FormatError
func (c *Client) FormatError(e ErrEntry) string { return fmt.Sprintf("%d %s [%s] %s request-%d retry-%d error: %s\n", e.Time.Unix(), e.Method, e.Verb, e.URL, e.Request, e.Retry, e.Err) }
go
func (c *Client) FormatError(e ErrEntry) string { return fmt.Sprintf("%d %s [%s] %s request-%d retry-%d error: %s\n", e.Time.Unix(), e.Method, e.Verb, e.URL, e.Request, e.Retry, e.Err) }
[ "func", "(", "c", "*", "Client", ")", "FormatError", "(", "e", "ErrEntry", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "e", ".", "Time", ".", "Unix", "(", ")", ",", "e", ".", "Method", ",", "e", ".", "Verb", ",", "e", ".", "URL", ",", "e", ".", "Request", ",", "e", ".", "Retry", ",", "e", ".", "Err", ")", "\n", "}" ]
// Format the Error to human readable string
[ "Format", "the", "Error", "to", "human", "readable", "string" ]
68a33a018ad0ac8266f272ec669307a1829c0486
https://github.com/sethgrid/pester/blob/68a33a018ad0ac8266f272ec669307a1829c0486/pester.go#L372-L375
983
sethgrid/pester
pester.go
LogErrCount
func (c *Client) LogErrCount() int { c.Lock() defer c.Unlock() return len(c.ErrLog) }
go
func (c *Client) LogErrCount() int { c.Lock() defer c.Unlock() return len(c.ErrLog) }
[ "func", "(", "c", "*", "Client", ")", "LogErrCount", "(", ")", "int", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n", "return", "len", "(", "c", ".", "ErrLog", ")", "\n", "}" ]
// LogErrCount is a helper method used primarily for test validation
[ "LogErrCount", "is", "a", "helper", "method", "used", "primarily", "for", "test", "validation" ]
68a33a018ad0ac8266f272ec669307a1829c0486
https://github.com/sethgrid/pester/blob/68a33a018ad0ac8266f272ec669307a1829c0486/pester.go#L378-L382
984
sethgrid/pester
pester.go
Do
func (c *Client) Do(req *http.Request) (resp *http.Response, err error) { return c.pester(params{method: "Do", req: req, verb: req.Method, url: req.URL.String()}) }
go
func (c *Client) Do(req *http.Request) (resp *http.Response, err error) { return c.pester(params{method: "Do", req: req, verb: req.Method, url: req.URL.String()}) }
[ "func", "(", "c", "*", "Client", ")", "Do", "(", "req", "*", "http", ".", "Request", ")", "(", "resp", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "return", "c", ".", "pester", "(", "params", "{", "method", ":", "\"", "\"", ",", "req", ":", "req", ",", "verb", ":", "req", ".", "Method", ",", "url", ":", "req", ".", "URL", ".", "String", "(", ")", "}", ")", "\n", "}" ]
// Do provides the same functionality as http.Client.Do
[ "Do", "provides", "the", "same", "functionality", "as", "http", ".", "Client", ".", "Do" ]
68a33a018ad0ac8266f272ec669307a1829c0486
https://github.com/sethgrid/pester/blob/68a33a018ad0ac8266f272ec669307a1829c0486/pester.go#L403-L405
985
sethgrid/pester
pester.go
Get
func (c *Client) Get(url string) (resp *http.Response, err error) { return c.pester(params{method: "Get", url: url, verb: "GET"}) }
go
func (c *Client) Get(url string) (resp *http.Response, err error) { return c.pester(params{method: "Get", url: url, verb: "GET"}) }
[ "func", "(", "c", "*", "Client", ")", "Get", "(", "url", "string", ")", "(", "resp", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "return", "c", ".", "pester", "(", "params", "{", "method", ":", "\"", "\"", ",", "url", ":", "url", ",", "verb", ":", "\"", "\"", "}", ")", "\n", "}" ]
// Get provides the same functionality as http.Client.Get
[ "Get", "provides", "the", "same", "functionality", "as", "http", ".", "Client", ".", "Get" ]
68a33a018ad0ac8266f272ec669307a1829c0486
https://github.com/sethgrid/pester/blob/68a33a018ad0ac8266f272ec669307a1829c0486/pester.go#L408-L410
986
sethgrid/pester
pester.go
Post
func (c *Client) Post(url string, bodyType string, body io.Reader) (resp *http.Response, err error) { return c.pester(params{method: "Post", url: url, bodyType: bodyType, body: body, verb: "POST"}) }
go
func (c *Client) Post(url string, bodyType string, body io.Reader) (resp *http.Response, err error) { return c.pester(params{method: "Post", url: url, bodyType: bodyType, body: body, verb: "POST"}) }
[ "func", "(", "c", "*", "Client", ")", "Post", "(", "url", "string", ",", "bodyType", "string", ",", "body", "io", ".", "Reader", ")", "(", "resp", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "return", "c", ".", "pester", "(", "params", "{", "method", ":", "\"", "\"", ",", "url", ":", "url", ",", "bodyType", ":", "bodyType", ",", "body", ":", "body", ",", "verb", ":", "\"", "\"", "}", ")", "\n", "}" ]
// Post provides the same functionality as http.Client.Post
[ "Post", "provides", "the", "same", "functionality", "as", "http", ".", "Client", ".", "Post" ]
68a33a018ad0ac8266f272ec669307a1829c0486
https://github.com/sethgrid/pester/blob/68a33a018ad0ac8266f272ec669307a1829c0486/pester.go#L418-L420
987
sethgrid/pester
pester.go
PostForm
func (c *Client) PostForm(url string, data url.Values) (resp *http.Response, err error) { return c.pester(params{method: "PostForm", url: url, data: data, verb: "POST"}) }
go
func (c *Client) PostForm(url string, data url.Values) (resp *http.Response, err error) { return c.pester(params{method: "PostForm", url: url, data: data, verb: "POST"}) }
[ "func", "(", "c", "*", "Client", ")", "PostForm", "(", "url", "string", ",", "data", "url", ".", "Values", ")", "(", "resp", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "return", "c", ".", "pester", "(", "params", "{", "method", ":", "\"", "\"", ",", "url", ":", "url", ",", "data", ":", "data", ",", "verb", ":", "\"", "\"", "}", ")", "\n", "}" ]
// PostForm provides the same functionality as http.Client.PostForm
[ "PostForm", "provides", "the", "same", "functionality", "as", "http", ".", "Client", ".", "PostForm" ]
68a33a018ad0ac8266f272ec669307a1829c0486
https://github.com/sethgrid/pester/blob/68a33a018ad0ac8266f272ec669307a1829c0486/pester.go#L423-L425
988
sethgrid/pester
pester.go
Get
func Get(url string) (resp *http.Response, err error) { c := New() return c.Get(url) }
go
func Get(url string) (resp *http.Response, err error) { c := New() return c.Get(url) }
[ "func", "Get", "(", "url", "string", ")", "(", "resp", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "c", ":=", "New", "(", ")", "\n", "return", "c", ".", "Get", "(", "url", ")", "\n", "}" ]
// Get provides the same functionality as http.Client.Get and creates its own constructor
[ "Get", "provides", "the", "same", "functionality", "as", "http", ".", "Client", ".", "Get", "and", "creates", "its", "own", "constructor" ]
68a33a018ad0ac8266f272ec669307a1829c0486
https://github.com/sethgrid/pester/blob/68a33a018ad0ac8266f272ec669307a1829c0486/pester.go#L443-L446
989
sethgrid/pester
pester.go
Post
func Post(url string, bodyType string, body io.Reader) (resp *http.Response, err error) { c := New() return c.Post(url, bodyType, body) }
go
func Post(url string, bodyType string, body io.Reader) (resp *http.Response, err error) { c := New() return c.Post(url, bodyType, body) }
[ "func", "Post", "(", "url", "string", ",", "bodyType", "string", ",", "body", "io", ".", "Reader", ")", "(", "resp", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "c", ":=", "New", "(", ")", "\n", "return", "c", ".", "Post", "(", "url", ",", "bodyType", ",", "body", ")", "\n", "}" ]
// Post provides the same functionality as http.Client.Post and creates its own constructor
[ "Post", "provides", "the", "same", "functionality", "as", "http", ".", "Client", ".", "Post", "and", "creates", "its", "own", "constructor" ]
68a33a018ad0ac8266f272ec669307a1829c0486
https://github.com/sethgrid/pester/blob/68a33a018ad0ac8266f272ec669307a1829c0486/pester.go#L455-L458
990
sethgrid/pester
pester.go
PostForm
func PostForm(url string, data url.Values) (resp *http.Response, err error) { c := New() return c.PostForm(url, data) }
go
func PostForm(url string, data url.Values) (resp *http.Response, err error) { c := New() return c.PostForm(url, data) }
[ "func", "PostForm", "(", "url", "string", ",", "data", "url", ".", "Values", ")", "(", "resp", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "c", ":=", "New", "(", ")", "\n", "return", "c", ".", "PostForm", "(", "url", ",", "data", ")", "\n", "}" ]
// PostForm provides the same functionality as http.Client.PostForm and creates its own constructor
[ "PostForm", "provides", "the", "same", "functionality", "as", "http", ".", "Client", ".", "PostForm", "and", "creates", "its", "own", "constructor" ]
68a33a018ad0ac8266f272ec669307a1829c0486
https://github.com/sethgrid/pester/blob/68a33a018ad0ac8266f272ec669307a1829c0486/pester.go#L461-L464
991
otiai10/copy
copy.go
Copy
func Copy(src, dest string) error { info, err := os.Lstat(src) if err != nil { return err } return copy(src, dest, info) }
go
func Copy(src, dest string) error { info, err := os.Lstat(src) if err != nil { return err } return copy(src, dest, info) }
[ "func", "Copy", "(", "src", ",", "dest", "string", ")", "error", "{", "info", ",", "err", ":=", "os", ".", "Lstat", "(", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "copy", "(", "src", ",", "dest", ",", "info", ")", "\n", "}" ]
// Copy copies src to dest, doesn't matter if src is a directory or a file
[ "Copy", "copies", "src", "to", "dest", "doesn", "t", "matter", "if", "src", "is", "a", "directory", "or", "a", "file" ]
c7381036ced2f01eaf44354b320b47a6874aef0b
https://github.com/otiai10/copy/blob/c7381036ced2f01eaf44354b320b47a6874aef0b/copy.go#L18-L24
992
otiai10/copy
copy.go
copy
func copy(src, dest string, info os.FileInfo) error { if info.Mode()&os.ModeSymlink != 0 { return lcopy(src, dest, info) } if info.IsDir() { return dcopy(src, dest, info) } return fcopy(src, dest, info) }
go
func copy(src, dest string, info os.FileInfo) error { if info.Mode()&os.ModeSymlink != 0 { return lcopy(src, dest, info) } if info.IsDir() { return dcopy(src, dest, info) } return fcopy(src, dest, info) }
[ "func", "copy", "(", "src", ",", "dest", "string", ",", "info", "os", ".", "FileInfo", ")", "error", "{", "if", "info", ".", "Mode", "(", ")", "&", "os", ".", "ModeSymlink", "!=", "0", "{", "return", "lcopy", "(", "src", ",", "dest", ",", "info", ")", "\n", "}", "\n", "if", "info", ".", "IsDir", "(", ")", "{", "return", "dcopy", "(", "src", ",", "dest", ",", "info", ")", "\n", "}", "\n", "return", "fcopy", "(", "src", ",", "dest", ",", "info", ")", "\n", "}" ]
// copy dispatches copy-funcs according to the mode. // Because this "copy" could be called recursively, // "info" MUST be given here, NOT nil.
[ "copy", "dispatches", "copy", "-", "funcs", "according", "to", "the", "mode", ".", "Because", "this", "copy", "could", "be", "called", "recursively", "info", "MUST", "be", "given", "here", "NOT", "nil", "." ]
c7381036ced2f01eaf44354b320b47a6874aef0b
https://github.com/otiai10/copy/blob/c7381036ced2f01eaf44354b320b47a6874aef0b/copy.go#L29-L37
993
otiai10/copy
copy.go
fcopy
func fcopy(src, dest string, info os.FileInfo) error { if err := os.MkdirAll(filepath.Dir(dest), os.ModePerm); err != nil { return err } f, err := os.Create(dest) if err != nil { return err } defer f.Close() if err = os.Chmod(f.Name(), info.Mode()); err != nil { return err } s, err := os.Open(src) if err != nil { return err } defer s.Close() _, err = io.Copy(f, s) return err }
go
func fcopy(src, dest string, info os.FileInfo) error { if err := os.MkdirAll(filepath.Dir(dest), os.ModePerm); err != nil { return err } f, err := os.Create(dest) if err != nil { return err } defer f.Close() if err = os.Chmod(f.Name(), info.Mode()); err != nil { return err } s, err := os.Open(src) if err != nil { return err } defer s.Close() _, err = io.Copy(f, s) return err }
[ "func", "fcopy", "(", "src", ",", "dest", "string", ",", "info", "os", ".", "FileInfo", ")", "error", "{", "if", "err", ":=", "os", ".", "MkdirAll", "(", "filepath", ".", "Dir", "(", "dest", ")", ",", "os", ".", "ModePerm", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "f", ",", "err", ":=", "os", ".", "Create", "(", "dest", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "if", "err", "=", "os", ".", "Chmod", "(", "f", ".", "Name", "(", ")", ",", "info", ".", "Mode", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ",", "err", ":=", "os", ".", "Open", "(", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "s", ".", "Close", "(", ")", "\n\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "f", ",", "s", ")", "\n", "return", "err", "\n", "}" ]
// fcopy is for just a file, // with considering existence of parent directory // and file permission.
[ "fcopy", "is", "for", "just", "a", "file", "with", "considering", "existence", "of", "parent", "directory", "and", "file", "permission", "." ]
c7381036ced2f01eaf44354b320b47a6874aef0b
https://github.com/otiai10/copy/blob/c7381036ced2f01eaf44354b320b47a6874aef0b/copy.go#L42-L66
994
otiai10/copy
copy.go
dcopy
func dcopy(srcdir, destdir string, info os.FileInfo) error { originalMode := info.Mode() // Make dest dir with 0755 so that everything writable. if err := os.MkdirAll(destdir, tmpPermissionForDirectory); err != nil { return err } // Recover dir mode with original one. defer os.Chmod(destdir, originalMode) contents, err := ioutil.ReadDir(srcdir) if err != nil { return err } for _, content := range contents { cs, cd := filepath.Join(srcdir, content.Name()), filepath.Join(destdir, content.Name()) if err := copy(cs, cd, content); err != nil { // If any error, exit immediately return err } } return nil }
go
func dcopy(srcdir, destdir string, info os.FileInfo) error { originalMode := info.Mode() // Make dest dir with 0755 so that everything writable. if err := os.MkdirAll(destdir, tmpPermissionForDirectory); err != nil { return err } // Recover dir mode with original one. defer os.Chmod(destdir, originalMode) contents, err := ioutil.ReadDir(srcdir) if err != nil { return err } for _, content := range contents { cs, cd := filepath.Join(srcdir, content.Name()), filepath.Join(destdir, content.Name()) if err := copy(cs, cd, content); err != nil { // If any error, exit immediately return err } } return nil }
[ "func", "dcopy", "(", "srcdir", ",", "destdir", "string", ",", "info", "os", ".", "FileInfo", ")", "error", "{", "originalMode", ":=", "info", ".", "Mode", "(", ")", "\n\n", "// Make dest dir with 0755 so that everything writable.", "if", "err", ":=", "os", ".", "MkdirAll", "(", "destdir", ",", "tmpPermissionForDirectory", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// Recover dir mode with original one.", "defer", "os", ".", "Chmod", "(", "destdir", ",", "originalMode", ")", "\n\n", "contents", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "srcdir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "for", "_", ",", "content", ":=", "range", "contents", "{", "cs", ",", "cd", ":=", "filepath", ".", "Join", "(", "srcdir", ",", "content", ".", "Name", "(", ")", ")", ",", "filepath", ".", "Join", "(", "destdir", ",", "content", ".", "Name", "(", ")", ")", "\n", "if", "err", ":=", "copy", "(", "cs", ",", "cd", ",", "content", ")", ";", "err", "!=", "nil", "{", "// If any error, exit immediately", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// dcopy is for a directory, // with scanning contents inside the directory // and pass everything to "copy" recursively.
[ "dcopy", "is", "for", "a", "directory", "with", "scanning", "contents", "inside", "the", "directory", "and", "pass", "everything", "to", "copy", "recursively", "." ]
c7381036ced2f01eaf44354b320b47a6874aef0b
https://github.com/otiai10/copy/blob/c7381036ced2f01eaf44354b320b47a6874aef0b/copy.go#L71-L96
995
otiai10/copy
copy.go
lcopy
func lcopy(src, dest string, info os.FileInfo) error { src, err := os.Readlink(src) if err != nil { return err } return os.Symlink(src, dest) }
go
func lcopy(src, dest string, info os.FileInfo) error { src, err := os.Readlink(src) if err != nil { return err } return os.Symlink(src, dest) }
[ "func", "lcopy", "(", "src", ",", "dest", "string", ",", "info", "os", ".", "FileInfo", ")", "error", "{", "src", ",", "err", ":=", "os", ".", "Readlink", "(", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "os", ".", "Symlink", "(", "src", ",", "dest", ")", "\n", "}" ]
// lcopy is for a symlink, // with just creating a new symlink by replicating src symlink.
[ "lcopy", "is", "for", "a", "symlink", "with", "just", "creating", "a", "new", "symlink", "by", "replicating", "src", "symlink", "." ]
c7381036ced2f01eaf44354b320b47a6874aef0b
https://github.com/otiai10/copy/blob/c7381036ced2f01eaf44354b320b47a6874aef0b/copy.go#L100-L106
996
mdp/qrterminal
qrterminal.go
GenerateWithConfig
func GenerateWithConfig(text string, config Config) { if config.QuietZone < 1 { config.QuietZone = 1 // at least 1-pixel-wide white quiet zone } w := config.Writer code, _ := qr.Encode(text, config.Level) if config.HalfBlocks { config.writeHalfBlocks(w, code) } else { config.writeFullBlocks(w, code) } }
go
func GenerateWithConfig(text string, config Config) { if config.QuietZone < 1 { config.QuietZone = 1 // at least 1-pixel-wide white quiet zone } w := config.Writer code, _ := qr.Encode(text, config.Level) if config.HalfBlocks { config.writeHalfBlocks(w, code) } else { config.writeFullBlocks(w, code) } }
[ "func", "GenerateWithConfig", "(", "text", "string", ",", "config", "Config", ")", "{", "if", "config", ".", "QuietZone", "<", "1", "{", "config", ".", "QuietZone", "=", "1", "// at least 1-pixel-wide white quiet zone", "\n", "}", "\n", "w", ":=", "config", ".", "Writer", "\n", "code", ",", "_", ":=", "qr", ".", "Encode", "(", "text", ",", "config", ".", "Level", ")", "\n", "if", "config", ".", "HalfBlocks", "{", "config", ".", "writeHalfBlocks", "(", "w", ",", "code", ")", "\n", "}", "else", "{", "config", ".", "writeFullBlocks", "(", "w", ",", "code", ")", "\n", "}", "\n", "}" ]
// GenerateWithConfig expects a string to encode and a config
[ "GenerateWithConfig", "expects", "a", "string", "to", "encode", "and", "a", "config" ]
28b49810f53911623d0a538d8edc01b8cbe2bd0e
https://github.com/mdp/qrterminal/blob/28b49810f53911623d0a538d8edc01b8cbe2bd0e/qrterminal.go#L115-L126
997
mdp/qrterminal
qrterminal.go
Generate
func Generate(text string, l qr.Level, w io.Writer) { config := Config{ Level: l, Writer: w, BlackChar: BLACK, WhiteChar: WHITE, QuietZone: QUIET_ZONE, } GenerateWithConfig(text, config) }
go
func Generate(text string, l qr.Level, w io.Writer) { config := Config{ Level: l, Writer: w, BlackChar: BLACK, WhiteChar: WHITE, QuietZone: QUIET_ZONE, } GenerateWithConfig(text, config) }
[ "func", "Generate", "(", "text", "string", ",", "l", "qr", ".", "Level", ",", "w", "io", ".", "Writer", ")", "{", "config", ":=", "Config", "{", "Level", ":", "l", ",", "Writer", ":", "w", ",", "BlackChar", ":", "BLACK", ",", "WhiteChar", ":", "WHITE", ",", "QuietZone", ":", "QUIET_ZONE", ",", "}", "\n", "GenerateWithConfig", "(", "text", ",", "config", ")", "\n", "}" ]
// Generate a QR Code and write it out to io.Writer
[ "Generate", "a", "QR", "Code", "and", "write", "it", "out", "to", "io", ".", "Writer" ]
28b49810f53911623d0a538d8edc01b8cbe2bd0e
https://github.com/mdp/qrterminal/blob/28b49810f53911623d0a538d8edc01b8cbe2bd0e/qrterminal.go#L129-L138
998
mdp/qrterminal
qrterminal.go
GenerateHalfBlock
func GenerateHalfBlock(text string, l qr.Level, w io.Writer) { config := Config{ Level: l, Writer: w, HalfBlocks: true, BlackChar: BLACK_BLACK, WhiteBlackChar: WHITE_BLACK, WhiteChar: WHITE_WHITE, BlackWhiteChar: BLACK_WHITE, QuietZone: QUIET_ZONE, } GenerateWithConfig(text, config) }
go
func GenerateHalfBlock(text string, l qr.Level, w io.Writer) { config := Config{ Level: l, Writer: w, HalfBlocks: true, BlackChar: BLACK_BLACK, WhiteBlackChar: WHITE_BLACK, WhiteChar: WHITE_WHITE, BlackWhiteChar: BLACK_WHITE, QuietZone: QUIET_ZONE, } GenerateWithConfig(text, config) }
[ "func", "GenerateHalfBlock", "(", "text", "string", ",", "l", "qr", ".", "Level", ",", "w", "io", ".", "Writer", ")", "{", "config", ":=", "Config", "{", "Level", ":", "l", ",", "Writer", ":", "w", ",", "HalfBlocks", ":", "true", ",", "BlackChar", ":", "BLACK_BLACK", ",", "WhiteBlackChar", ":", "WHITE_BLACK", ",", "WhiteChar", ":", "WHITE_WHITE", ",", "BlackWhiteChar", ":", "BLACK_WHITE", ",", "QuietZone", ":", "QUIET_ZONE", ",", "}", "\n", "GenerateWithConfig", "(", "text", ",", "config", ")", "\n", "}" ]
// Generate a QR Code with half blocks and write it out to io.Writer
[ "Generate", "a", "QR", "Code", "with", "half", "blocks", "and", "write", "it", "out", "to", "io", ".", "Writer" ]
28b49810f53911623d0a538d8edc01b8cbe2bd0e
https://github.com/mdp/qrterminal/blob/28b49810f53911623d0a538d8edc01b8cbe2bd0e/qrterminal.go#L141-L153
999
namsral/flag
extras.go
ParseEnv
func (f *FlagSet) ParseEnv(environ []string) error { m := f.formal env := make(map[string]string) for _, s := range environ { i := strings.Index(s, "=") if i < 1 { continue } env[s[0:i]] = s[i+1 : len(s)] } for _, flag := range m { name := flag.Name _, set := f.actual[name] if set { continue } flag, alreadythere := m[name] if !alreadythere { if name == "help" || name == "h" { // special case for nice help message. f.usage() return ErrHelp } return f.failf("environment variable provided but not defined: %s", name) } envKey := strings.ToUpper(flag.Name) if f.envPrefix != "" { envKey = f.envPrefix + "_" + envKey } envKey = strings.Replace(envKey, "-", "_", -1) value, isSet := env[envKey] if !isSet { continue } hasValue := false if len(value) > 0 { hasValue = true } if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() { // special case: doesn't need an arg if hasValue { if err := fv.Set(value); err != nil { return f.failf("invalid boolean value %q for environment variable %s: %v", value, name, err) } } else { // flag without value is regarded a bool fv.Set("true") } } else { if err := flag.Value.Set(value); err != nil { return f.failf("invalid value %q for environment variable %s: %v", value, name, err) } } // update f.actual if f.actual == nil { f.actual = make(map[string]*Flag) } f.actual[name] = flag } return nil }
go
func (f *FlagSet) ParseEnv(environ []string) error { m := f.formal env := make(map[string]string) for _, s := range environ { i := strings.Index(s, "=") if i < 1 { continue } env[s[0:i]] = s[i+1 : len(s)] } for _, flag := range m { name := flag.Name _, set := f.actual[name] if set { continue } flag, alreadythere := m[name] if !alreadythere { if name == "help" || name == "h" { // special case for nice help message. f.usage() return ErrHelp } return f.failf("environment variable provided but not defined: %s", name) } envKey := strings.ToUpper(flag.Name) if f.envPrefix != "" { envKey = f.envPrefix + "_" + envKey } envKey = strings.Replace(envKey, "-", "_", -1) value, isSet := env[envKey] if !isSet { continue } hasValue := false if len(value) > 0 { hasValue = true } if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() { // special case: doesn't need an arg if hasValue { if err := fv.Set(value); err != nil { return f.failf("invalid boolean value %q for environment variable %s: %v", value, name, err) } } else { // flag without value is regarded a bool fv.Set("true") } } else { if err := flag.Value.Set(value); err != nil { return f.failf("invalid value %q for environment variable %s: %v", value, name, err) } } // update f.actual if f.actual == nil { f.actual = make(map[string]*Flag) } f.actual[name] = flag } return nil }
[ "func", "(", "f", "*", "FlagSet", ")", "ParseEnv", "(", "environ", "[", "]", "string", ")", "error", "{", "m", ":=", "f", ".", "formal", "\n\n", "env", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "_", ",", "s", ":=", "range", "environ", "{", "i", ":=", "strings", ".", "Index", "(", "s", ",", "\"", "\"", ")", "\n", "if", "i", "<", "1", "{", "continue", "\n", "}", "\n", "env", "[", "s", "[", "0", ":", "i", "]", "]", "=", "s", "[", "i", "+", "1", ":", "len", "(", "s", ")", "]", "\n", "}", "\n\n", "for", "_", ",", "flag", ":=", "range", "m", "{", "name", ":=", "flag", ".", "Name", "\n", "_", ",", "set", ":=", "f", ".", "actual", "[", "name", "]", "\n", "if", "set", "{", "continue", "\n", "}", "\n\n", "flag", ",", "alreadythere", ":=", "m", "[", "name", "]", "\n", "if", "!", "alreadythere", "{", "if", "name", "==", "\"", "\"", "||", "name", "==", "\"", "\"", "{", "// special case for nice help message.", "f", ".", "usage", "(", ")", "\n", "return", "ErrHelp", "\n", "}", "\n", "return", "f", ".", "failf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n\n", "envKey", ":=", "strings", ".", "ToUpper", "(", "flag", ".", "Name", ")", "\n", "if", "f", ".", "envPrefix", "!=", "\"", "\"", "{", "envKey", "=", "f", ".", "envPrefix", "+", "\"", "\"", "+", "envKey", "\n", "}", "\n", "envKey", "=", "strings", ".", "Replace", "(", "envKey", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n\n", "value", ",", "isSet", ":=", "env", "[", "envKey", "]", "\n", "if", "!", "isSet", "{", "continue", "\n", "}", "\n\n", "hasValue", ":=", "false", "\n", "if", "len", "(", "value", ")", ">", "0", "{", "hasValue", "=", "true", "\n", "}", "\n\n", "if", "fv", ",", "ok", ":=", "flag", ".", "Value", ".", "(", "boolFlag", ")", ";", "ok", "&&", "fv", ".", "IsBoolFlag", "(", ")", "{", "// special case: doesn't need an arg", "if", "hasValue", "{", "if", "err", ":=", "fv", ".", "Set", "(", "value", ")", ";", "err", "!=", "nil", "{", "return", "f", ".", "failf", "(", "\"", "\"", ",", "value", ",", "name", ",", "err", ")", "\n", "}", "\n", "}", "else", "{", "// flag without value is regarded a bool", "fv", ".", "Set", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "else", "{", "if", "err", ":=", "flag", ".", "Value", ".", "Set", "(", "value", ")", ";", "err", "!=", "nil", "{", "return", "f", ".", "failf", "(", "\"", "\"", ",", "value", ",", "name", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "// update f.actual", "if", "f", ".", "actual", "==", "nil", "{", "f", ".", "actual", "=", "make", "(", "map", "[", "string", "]", "*", "Flag", ")", "\n", "}", "\n", "f", ".", "actual", "[", "name", "]", "=", "flag", "\n\n", "}", "\n", "return", "nil", "\n", "}" ]
// ParseEnv parses flags from environment variables. // Flags already set will be ignored.
[ "ParseEnv", "parses", "flags", "from", "environment", "variables", ".", "Flags", "already", "set", "will", "be", "ignored", "." ]
67f268f20922975c067ed799e4be6bacf152208c
https://github.com/namsral/flag/blob/67f268f20922975c067ed799e4be6bacf152208c/extras.go#L19-L87