repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
shurcooL/graphql
internal/jsonutil/graphql.go
pushState
func (d *decoder) pushState(s json.Delim) { d.parseState = append(d.parseState, s) }
go
func (d *decoder) pushState(s json.Delim) { d.parseState = append(d.parseState, s) }
[ "func", "(", "d", "*", "decoder", ")", "pushState", "(", "s", "json", ".", "Delim", ")", "{", "d", ".", "parseState", "=", "append", "(", "d", ".", "parseState", ",", "s", ")", "\n", "}" ]
// pushState pushes a new parse state s onto the stack.
[ "pushState", "pushes", "a", "new", "parse", "state", "s", "onto", "the", "stack", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/internal/jsonutil/graphql.go#L225-L227
train
shurcooL/graphql
internal/jsonutil/graphql.go
state
func (d *decoder) state() json.Delim { if len(d.parseState) == 0 { return 0 } return d.parseState[len(d.parseState)-1] }
go
func (d *decoder) state() json.Delim { if len(d.parseState) == 0 { return 0 } return d.parseState[len(d.parseState)-1] }
[ "func", "(", "d", "*", "decoder", ")", "state", "(", ")", "json", ".", "Delim", "{", "if", "len", "(", "d", ".", "parseState", ")", "==", "0", "{", "return", "0", "\n", "}", "\n", "return", "d", ".", "parseState", "[", "len", "(", "d", ".", "parseState", ")", "-", "1", "]", "\n", "}" ]
// state reports the parse state on top of stack, or 0 if empty.
[ "state", "reports", "the", "parse", "state", "on", "top", "of", "stack", "or", "0", "if", "empty", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/internal/jsonutil/graphql.go#L236-L241
train
shurcooL/graphql
internal/jsonutil/graphql.go
popAllVs
func (d *decoder) popAllVs() { var nonEmpty [][]reflect.Value for i := range d.vs { d.vs[i] = d.vs[i][:len(d.vs[i])-1] if len(d.vs[i]) > 0 { nonEmpty = append(nonEmpty, d.vs[i]) } } d.vs = nonEmpty }
go
func (d *decoder) popAllVs() { var nonEmpty [][]reflect.Value for i := range d.vs { d.vs[i] = d.vs[i][:len(d.vs[i])-1] if len(d.vs[i]) > 0 { nonEmpty = append(nonEmpty, d.vs[i]) } } d.vs = nonEmpty }
[ "func", "(", "d", "*", "decoder", ")", "popAllVs", "(", ")", "{", "var", "nonEmpty", "[", "]", "[", "]", "reflect", ".", "Value", "\n", "for", "i", ":=", "range", "d", ".", "vs", "{", "d", ".", "vs", "[", "i", "]", "=", "d", ".", "vs", "[", "i", "]", "[", ":", "len", "(", "d", ".", "vs", "[", "i", "]", ")", "-", "1", "]", "\n", "if", "len", "(", "d", ".", "vs", "[", "i", "]", ")", ">", "0", "{", "nonEmpty", "=", "append", "(", "nonEmpty", ",", "d", ".", "vs", "[", "i", "]", ")", "\n", "}", "\n", "}", "\n", "d", ".", "vs", "=", "nonEmpty", "\n", "}" ]
// popAllVs pops from all d.vs stacks, keeping only non-empty ones.
[ "popAllVs", "pops", "from", "all", "d", ".", "vs", "stacks", "keeping", "only", "non", "-", "empty", "ones", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/internal/jsonutil/graphql.go#L244-L253
train
shurcooL/graphql
internal/jsonutil/graphql.go
fieldByGraphQLName
func fieldByGraphQLName(v reflect.Value, name string) reflect.Value { for i := 0; i < v.NumField(); i++ { if v.Type().Field(i).PkgPath != "" { // Skip unexported field. continue } if hasGraphQLName(v.Type().Field(i), name) { return v.Field(i) } } return reflect.Value{} }
go
func fieldByGraphQLName(v reflect.Value, name string) reflect.Value { for i := 0; i < v.NumField(); i++ { if v.Type().Field(i).PkgPath != "" { // Skip unexported field. continue } if hasGraphQLName(v.Type().Field(i), name) { return v.Field(i) } } return reflect.Value{} }
[ "func", "fieldByGraphQLName", "(", "v", "reflect", ".", "Value", ",", "name", "string", ")", "reflect", ".", "Value", "{", "for", "i", ":=", "0", ";", "i", "<", "v", ".", "NumField", "(", ")", ";", "i", "++", "{", "if", "v", ".", "Type", "(", ")", ".", "Field", "(", "i", ")", ".", "PkgPath", "!=", "\"", "\"", "{", "// Skip unexported field.", "continue", "\n", "}", "\n", "if", "hasGraphQLName", "(", "v", ".", "Type", "(", ")", ".", "Field", "(", "i", ")", ",", "name", ")", "{", "return", "v", ".", "Field", "(", "i", ")", "\n", "}", "\n", "}", "\n", "return", "reflect", ".", "Value", "{", "}", "\n", "}" ]
// fieldByGraphQLName returns an exported struct field of struct v // that matches GraphQL name, or invalid reflect.Value if none found.
[ "fieldByGraphQLName", "returns", "an", "exported", "struct", "field", "of", "struct", "v", "that", "matches", "GraphQL", "name", "or", "invalid", "reflect", ".", "Value", "if", "none", "found", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/internal/jsonutil/graphql.go#L257-L268
train
shurcooL/graphql
internal/jsonutil/graphql.go
hasGraphQLName
func hasGraphQLName(f reflect.StructField, name string) bool { value, ok := f.Tag.Lookup("graphql") if !ok { // TODO: caseconv package is relatively slow. Optimize it, then consider using it here. //return caseconv.MixedCapsToLowerCamelCase(f.Name) == name return strings.EqualFold(f.Name, name) } value = strings.TrimSpace(value) // TODO: Parse better. if strings.HasPrefix(value, "...") { // GraphQL fragment. It doesn't have a name. return false } if i := strings.Index(value, "("); i != -1 { value = value[:i] } if i := strings.Index(value, ":"); i != -1 { value = value[:i] } return strings.TrimSpace(value) == name }
go
func hasGraphQLName(f reflect.StructField, name string) bool { value, ok := f.Tag.Lookup("graphql") if !ok { // TODO: caseconv package is relatively slow. Optimize it, then consider using it here. //return caseconv.MixedCapsToLowerCamelCase(f.Name) == name return strings.EqualFold(f.Name, name) } value = strings.TrimSpace(value) // TODO: Parse better. if strings.HasPrefix(value, "...") { // GraphQL fragment. It doesn't have a name. return false } if i := strings.Index(value, "("); i != -1 { value = value[:i] } if i := strings.Index(value, ":"); i != -1 { value = value[:i] } return strings.TrimSpace(value) == name }
[ "func", "hasGraphQLName", "(", "f", "reflect", ".", "StructField", ",", "name", "string", ")", "bool", "{", "value", ",", "ok", ":=", "f", ".", "Tag", ".", "Lookup", "(", "\"", "\"", ")", "\n", "if", "!", "ok", "{", "// TODO: caseconv package is relatively slow. Optimize it, then consider using it here.", "//return caseconv.MixedCapsToLowerCamelCase(f.Name) == name", "return", "strings", ".", "EqualFold", "(", "f", ".", "Name", ",", "name", ")", "\n", "}", "\n", "value", "=", "strings", ".", "TrimSpace", "(", "value", ")", "// TODO: Parse better.", "\n", "if", "strings", ".", "HasPrefix", "(", "value", ",", "\"", "\"", ")", "{", "// GraphQL fragment. It doesn't have a name.", "return", "false", "\n", "}", "\n", "if", "i", ":=", "strings", ".", "Index", "(", "value", ",", "\"", "\"", ")", ";", "i", "!=", "-", "1", "{", "value", "=", "value", "[", ":", "i", "]", "\n", "}", "\n", "if", "i", ":=", "strings", ".", "Index", "(", "value", ",", "\"", "\"", ")", ";", "i", "!=", "-", "1", "{", "value", "=", "value", "[", ":", "i", "]", "\n", "}", "\n", "return", "strings", ".", "TrimSpace", "(", "value", ")", "==", "name", "\n", "}" ]
// hasGraphQLName reports whether struct field f has GraphQL name.
[ "hasGraphQLName", "reports", "whether", "struct", "field", "f", "has", "GraphQL", "name", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/internal/jsonutil/graphql.go#L271-L290
train
shurcooL/graphql
internal/jsonutil/graphql.go
isGraphQLFragment
func isGraphQLFragment(f reflect.StructField) bool { value, ok := f.Tag.Lookup("graphql") if !ok { return false } value = strings.TrimSpace(value) // TODO: Parse better. return strings.HasPrefix(value, "...") }
go
func isGraphQLFragment(f reflect.StructField) bool { value, ok := f.Tag.Lookup("graphql") if !ok { return false } value = strings.TrimSpace(value) // TODO: Parse better. return strings.HasPrefix(value, "...") }
[ "func", "isGraphQLFragment", "(", "f", "reflect", ".", "StructField", ")", "bool", "{", "value", ",", "ok", ":=", "f", ".", "Tag", ".", "Lookup", "(", "\"", "\"", ")", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "value", "=", "strings", ".", "TrimSpace", "(", "value", ")", "// TODO: Parse better.", "\n", "return", "strings", ".", "HasPrefix", "(", "value", ",", "\"", "\"", ")", "\n", "}" ]
// isGraphQLFragment reports whether struct field f is a GraphQL fragment.
[ "isGraphQLFragment", "reports", "whether", "struct", "field", "f", "is", "a", "GraphQL", "fragment", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/internal/jsonutil/graphql.go#L293-L300
train
shurcooL/graphql
internal/jsonutil/graphql.go
unmarshalValue
func unmarshalValue(value json.Token, v reflect.Value) error { b, err := json.Marshal(value) // TODO: Short-circuit (if profiling says it's worth it). if err != nil { return err } return json.Unmarshal(b, v.Addr().Interface()) }
go
func unmarshalValue(value json.Token, v reflect.Value) error { b, err := json.Marshal(value) // TODO: Short-circuit (if profiling says it's worth it). if err != nil { return err } return json.Unmarshal(b, v.Addr().Interface()) }
[ "func", "unmarshalValue", "(", "value", "json", ".", "Token", ",", "v", "reflect", ".", "Value", ")", "error", "{", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "value", ")", "// TODO: Short-circuit (if profiling says it's worth it).", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "json", ".", "Unmarshal", "(", "b", ",", "v", ".", "Addr", "(", ")", ".", "Interface", "(", ")", ")", "\n", "}" ]
// unmarshalValue unmarshals JSON value into v. // v must be addressable and not obtained by the use of unexported // struct fields, otherwise unmarshalValue will panic.
[ "unmarshalValue", "unmarshals", "JSON", "value", "into", "v", ".", "v", "must", "be", "addressable", "and", "not", "obtained", "by", "the", "use", "of", "unexported", "struct", "fields", "otherwise", "unmarshalValue", "will", "panic", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/internal/jsonutil/graphql.go#L305-L311
train
h2non/bimg
image.go
Resize
func (i *Image) Resize(width, height int) ([]byte, error) { options := Options{ Width: width, Height: height, Embed: true, } return i.Process(options) }
go
func (i *Image) Resize(width, height int) ([]byte, error) { options := Options{ Width: width, Height: height, Embed: true, } return i.Process(options) }
[ "func", "(", "i", "*", "Image", ")", "Resize", "(", "width", ",", "height", "int", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "options", ":=", "Options", "{", "Width", ":", "width", ",", "Height", ":", "height", ",", "Embed", ":", "true", ",", "}", "\n", "return", "i", ".", "Process", "(", "options", ")", "\n", "}" ]
// Resize resizes the image to fixed width and height.
[ "Resize", "resizes", "the", "image", "to", "fixed", "width", "and", "height", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/image.go#L14-L21
train
h2non/bimg
image.go
Crop
func (i *Image) Crop(width, height int, gravity Gravity) ([]byte, error) { options := Options{ Width: width, Height: height, Gravity: gravity, Crop: true, } return i.Process(options) }
go
func (i *Image) Crop(width, height int, gravity Gravity) ([]byte, error) { options := Options{ Width: width, Height: height, Gravity: gravity, Crop: true, } return i.Process(options) }
[ "func", "(", "i", "*", "Image", ")", "Crop", "(", "width", ",", "height", "int", ",", "gravity", "Gravity", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "options", ":=", "Options", "{", "Width", ":", "width", ",", "Height", ":", "height", ",", "Gravity", ":", "gravity", ",", "Crop", ":", "true", ",", "}", "\n", "return", "i", ".", "Process", "(", "options", ")", "\n", "}" ]
// Crop crops the image to the exact size specified.
[ "Crop", "crops", "the", "image", "to", "the", "exact", "size", "specified", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/image.go#L93-L101
train
h2non/bimg
image.go
Watermark
func (i *Image) Watermark(w Watermark) ([]byte, error) { options := Options{Watermark: w} return i.Process(options) }
go
func (i *Image) Watermark(w Watermark) ([]byte, error) { options := Options{Watermark: w} return i.Process(options) }
[ "func", "(", "i", "*", "Image", ")", "Watermark", "(", "w", "Watermark", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "options", ":=", "Options", "{", "Watermark", ":", "w", "}", "\n", "return", "i", ".", "Process", "(", "options", ")", "\n", "}" ]
// Watermark adds text as watermark on the given image.
[ "Watermark", "adds", "text", "as", "watermark", "on", "the", "given", "image", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/image.go#L133-L136
train
h2non/bimg
image.go
WatermarkImage
func (i *Image) WatermarkImage(w WatermarkImage) ([]byte, error) { options := Options{WatermarkImage: w} return i.Process(options) }
go
func (i *Image) WatermarkImage(w WatermarkImage) ([]byte, error) { options := Options{WatermarkImage: w} return i.Process(options) }
[ "func", "(", "i", "*", "Image", ")", "WatermarkImage", "(", "w", "WatermarkImage", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "options", ":=", "Options", "{", "WatermarkImage", ":", "w", "}", "\n", "return", "i", ".", "Process", "(", "options", ")", "\n", "}" ]
// WatermarkImage adds image as watermark on the given image.
[ "WatermarkImage", "adds", "image", "as", "watermark", "on", "the", "given", "image", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/image.go#L139-L142
train
h2non/bimg
image.go
Flip
func (i *Image) Flip() ([]byte, error) { options := Options{Flip: true} return i.Process(options) }
go
func (i *Image) Flip() ([]byte, error) { options := Options{Flip: true} return i.Process(options) }
[ "func", "(", "i", "*", "Image", ")", "Flip", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "options", ":=", "Options", "{", "Flip", ":", "true", "}", "\n", "return", "i", ".", "Process", "(", "options", ")", "\n", "}" ]
// Flip flips the image about the vertical Y axis.
[ "Flip", "flips", "the", "image", "about", "the", "vertical", "Y", "axis", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/image.go#L158-L161
train
h2non/bimg
image.go
Convert
func (i *Image) Convert(t ImageType) ([]byte, error) { options := Options{Type: t} return i.Process(options) }
go
func (i *Image) Convert(t ImageType) ([]byte, error) { options := Options{Type: t} return i.Process(options) }
[ "func", "(", "i", "*", "Image", ")", "Convert", "(", "t", "ImageType", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "options", ":=", "Options", "{", "Type", ":", "t", "}", "\n", "return", "i", ".", "Process", "(", "options", ")", "\n", "}" ]
// Convert converts image to another format.
[ "Convert", "converts", "image", "to", "another", "format", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/image.go#L170-L173
train
h2non/bimg
image.go
Colourspace
func (i *Image) Colourspace(c Interpretation) ([]byte, error) { options := Options{Interpretation: c} return i.Process(options) }
go
func (i *Image) Colourspace(c Interpretation) ([]byte, error) { options := Options{Interpretation: c} return i.Process(options) }
[ "func", "(", "i", "*", "Image", ")", "Colourspace", "(", "c", "Interpretation", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "options", ":=", "Options", "{", "Interpretation", ":", "c", "}", "\n", "return", "i", ".", "Process", "(", "options", ")", "\n", "}" ]
// Colourspace performs a color space conversion bsaed on the given interpretation.
[ "Colourspace", "performs", "a", "color", "space", "conversion", "bsaed", "on", "the", "given", "interpretation", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/image.go#L176-L179
train
h2non/bimg
image.go
Process
func (i *Image) Process(o Options) ([]byte, error) { image, err := Resize(i.buffer, o) if err != nil { return nil, err } i.buffer = image return image, nil }
go
func (i *Image) Process(o Options) ([]byte, error) { image, err := Resize(i.buffer, o) if err != nil { return nil, err } i.buffer = image return image, nil }
[ "func", "(", "i", "*", "Image", ")", "Process", "(", "o", "Options", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "image", ",", "err", ":=", "Resize", "(", "i", ".", "buffer", ",", "o", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "i", ".", "buffer", "=", "image", "\n", "return", "image", ",", "nil", "\n", "}" ]
// Process processes the image based on the given transformation options, // talking with libvips bindings accordingly and returning the resultant // image buffer.
[ "Process", "processes", "the", "image", "based", "on", "the", "given", "transformation", "options", "talking", "with", "libvips", "bindings", "accordingly", "and", "returning", "the", "resultant", "image", "buffer", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/image.go#L191-L198
train
h2non/bimg
metadata.go
Size
func Size(buf []byte) (ImageSize, error) { metadata, err := Metadata(buf) if err != nil { return ImageSize{}, err } return ImageSize{ Width: int(metadata.Size.Width), Height: int(metadata.Size.Height), }, nil }
go
func Size(buf []byte) (ImageSize, error) { metadata, err := Metadata(buf) if err != nil { return ImageSize{}, err } return ImageSize{ Width: int(metadata.Size.Width), Height: int(metadata.Size.Height), }, nil }
[ "func", "Size", "(", "buf", "[", "]", "byte", ")", "(", "ImageSize", ",", "error", ")", "{", "metadata", ",", "err", ":=", "Metadata", "(", "buf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ImageSize", "{", "}", ",", "err", "\n", "}", "\n\n", "return", "ImageSize", "{", "Width", ":", "int", "(", "metadata", ".", "Size", ".", "Width", ")", ",", "Height", ":", "int", "(", "metadata", ".", "Size", ".", "Height", ")", ",", "}", ",", "nil", "\n", "}" ]
// Size returns the image size by width and height pixels.
[ "Size", "returns", "the", "image", "size", "by", "width", "and", "height", "pixels", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/metadata.go#L28-L38
train
h2non/bimg
resize.go
Resize
func Resize(buf []byte, o Options) ([]byte, error) { // Required in order to prevent premature garbage collection. See: // https://github.com/h2non/bimg/pull/162 defer runtime.KeepAlive(buf) return resizer(buf, o) }
go
func Resize(buf []byte, o Options) ([]byte, error) { // Required in order to prevent premature garbage collection. See: // https://github.com/h2non/bimg/pull/162 defer runtime.KeepAlive(buf) return resizer(buf, o) }
[ "func", "Resize", "(", "buf", "[", "]", "byte", ",", "o", "Options", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Required in order to prevent premature garbage collection. See:", "// https://github.com/h2non/bimg/pull/162", "defer", "runtime", ".", "KeepAlive", "(", "buf", ")", "\n", "return", "resizer", "(", "buf", ",", "o", ")", "\n", "}" ]
// Resize is used to transform a given image as byte buffer // with the passed options.
[ "Resize", "is", "used", "to", "transform", "a", "given", "image", "as", "byte", "buffer", "with", "the", "passed", "options", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/resize.go#L11-L16
train
h2non/bimg
file.go
Write
func Write(path string, buf []byte) error { return ioutil.WriteFile(path, buf, 0644) }
go
func Write(path string, buf []byte) error { return ioutil.WriteFile(path, buf, 0644) }
[ "func", "Write", "(", "path", "string", ",", "buf", "[", "]", "byte", ")", "error", "{", "return", "ioutil", ".", "WriteFile", "(", "path", ",", "buf", ",", "0644", ")", "\n", "}" ]
// Write writes the given byte buffer into disk // to the given file path.
[ "Write", "writes", "the", "given", "byte", "buffer", "into", "disk", "to", "the", "given", "file", "path", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/file.go#L13-L15
train
h2non/bimg
type.go
discoverSupportedImageTypes
func discoverSupportedImageTypes() { imageMutex.Lock() for imageType := range ImageTypes { SupportedImageTypes[imageType] = SupportedImageType{ Load: VipsIsTypeSupported(imageType), Save: VipsIsTypeSupportedSave(imageType), } } imageMutex.Unlock() }
go
func discoverSupportedImageTypes() { imageMutex.Lock() for imageType := range ImageTypes { SupportedImageTypes[imageType] = SupportedImageType{ Load: VipsIsTypeSupported(imageType), Save: VipsIsTypeSupportedSave(imageType), } } imageMutex.Unlock() }
[ "func", "discoverSupportedImageTypes", "(", ")", "{", "imageMutex", ".", "Lock", "(", ")", "\n", "for", "imageType", ":=", "range", "ImageTypes", "{", "SupportedImageTypes", "[", "imageType", "]", "=", "SupportedImageType", "{", "Load", ":", "VipsIsTypeSupported", "(", "imageType", ")", ",", "Save", ":", "VipsIsTypeSupportedSave", "(", "imageType", ")", ",", "}", "\n", "}", "\n", "imageMutex", ".", "Unlock", "(", ")", "\n", "}" ]
// discoverSupportedImageTypes is used to fill SupportedImageTypes map.
[ "discoverSupportedImageTypes", "is", "used", "to", "fill", "SupportedImageTypes", "map", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/type.go#L68-L77
train
h2non/bimg
type.go
isBinary
func isBinary(buf []byte) bool { if len(buf) < 24 { return false } for i := 0; i < 24; i++ { charCode, _ := utf8.DecodeRuneInString(string(buf[i])) if charCode == 65533 || charCode <= 8 { return true } } return false }
go
func isBinary(buf []byte) bool { if len(buf) < 24 { return false } for i := 0; i < 24; i++ { charCode, _ := utf8.DecodeRuneInString(string(buf[i])) if charCode == 65533 || charCode <= 8 { return true } } return false }
[ "func", "isBinary", "(", "buf", "[", "]", "byte", ")", "bool", "{", "if", "len", "(", "buf", ")", "<", "24", "{", "return", "false", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "24", ";", "i", "++", "{", "charCode", ",", "_", ":=", "utf8", ".", "DecodeRuneInString", "(", "string", "(", "buf", "[", "i", "]", ")", ")", "\n", "if", "charCode", "==", "65533", "||", "charCode", "<=", "8", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isBinary checks if the given buffer is a binary file.
[ "isBinary", "checks", "if", "the", "given", "buffer", "is", "a", "binary", "file", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/type.go#L80-L91
train
h2non/bimg
type.go
IsSVGImage
func IsSVGImage(buf []byte) bool { return !isBinary(buf) && svgRegex.Match(htmlCommentRegex.ReplaceAll(buf, []byte{})) }
go
func IsSVGImage(buf []byte) bool { return !isBinary(buf) && svgRegex.Match(htmlCommentRegex.ReplaceAll(buf, []byte{})) }
[ "func", "IsSVGImage", "(", "buf", "[", "]", "byte", ")", "bool", "{", "return", "!", "isBinary", "(", "buf", ")", "&&", "svgRegex", ".", "Match", "(", "htmlCommentRegex", ".", "ReplaceAll", "(", "buf", ",", "[", "]", "byte", "{", "}", ")", ")", "\n", "}" ]
// IsSVGImage returns true if the given buffer is a valid SVG image.
[ "IsSVGImage", "returns", "true", "if", "the", "given", "buffer", "is", "a", "valid", "SVG", "image", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/type.go#L94-L96
train
h2non/bimg
type.go
IsImageTypeSupportedByVips
func IsImageTypeSupportedByVips(t ImageType) SupportedImageType { imageMutex.RLock() // Discover supported image types and cache the result itShouldDiscover := len(SupportedImageTypes) == 0 if itShouldDiscover { imageMutex.RUnlock() discoverSupportedImageTypes() } // Check if image type is actually supported supported, ok := SupportedImageTypes[t] if !itShouldDiscover { imageMutex.RUnlock() } if ok { return supported } return SupportedImageType{Load: false, Save: false} }
go
func IsImageTypeSupportedByVips(t ImageType) SupportedImageType { imageMutex.RLock() // Discover supported image types and cache the result itShouldDiscover := len(SupportedImageTypes) == 0 if itShouldDiscover { imageMutex.RUnlock() discoverSupportedImageTypes() } // Check if image type is actually supported supported, ok := SupportedImageTypes[t] if !itShouldDiscover { imageMutex.RUnlock() } if ok { return supported } return SupportedImageType{Load: false, Save: false} }
[ "func", "IsImageTypeSupportedByVips", "(", "t", "ImageType", ")", "SupportedImageType", "{", "imageMutex", ".", "RLock", "(", ")", "\n\n", "// Discover supported image types and cache the result", "itShouldDiscover", ":=", "len", "(", "SupportedImageTypes", ")", "==", "0", "\n", "if", "itShouldDiscover", "{", "imageMutex", ".", "RUnlock", "(", ")", "\n", "discoverSupportedImageTypes", "(", ")", "\n", "}", "\n\n", "// Check if image type is actually supported", "supported", ",", "ok", ":=", "SupportedImageTypes", "[", "t", "]", "\n", "if", "!", "itShouldDiscover", "{", "imageMutex", ".", "RUnlock", "(", ")", "\n", "}", "\n\n", "if", "ok", "{", "return", "supported", "\n", "}", "\n", "return", "SupportedImageType", "{", "Load", ":", "false", ",", "Save", ":", "false", "}", "\n", "}" ]
// IsImageTypeSupportedByVips returns true if the given image type // is supported by current libvips compilation.
[ "IsImageTypeSupportedByVips", "returns", "true", "if", "the", "given", "image", "type", "is", "supported", "by", "current", "libvips", "compilation", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/type.go#L110-L130
train
h2non/bimg
type.go
IsTypeSupported
func IsTypeSupported(t ImageType) bool { _, ok := ImageTypes[t] return ok && IsImageTypeSupportedByVips(t).Load }
go
func IsTypeSupported(t ImageType) bool { _, ok := ImageTypes[t] return ok && IsImageTypeSupportedByVips(t).Load }
[ "func", "IsTypeSupported", "(", "t", "ImageType", ")", "bool", "{", "_", ",", "ok", ":=", "ImageTypes", "[", "t", "]", "\n", "return", "ok", "&&", "IsImageTypeSupportedByVips", "(", "t", ")", ".", "Load", "\n", "}" ]
// IsTypeSupported checks if a given image type is supported
[ "IsTypeSupported", "checks", "if", "a", "given", "image", "type", "is", "supported" ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/type.go#L133-L136
train
h2non/bimg
type.go
IsTypeNameSupported
func IsTypeNameSupported(t string) bool { for imageType, name := range ImageTypes { if name == t { return IsImageTypeSupportedByVips(imageType).Load } } return false }
go
func IsTypeNameSupported(t string) bool { for imageType, name := range ImageTypes { if name == t { return IsImageTypeSupportedByVips(imageType).Load } } return false }
[ "func", "IsTypeNameSupported", "(", "t", "string", ")", "bool", "{", "for", "imageType", ",", "name", ":=", "range", "ImageTypes", "{", "if", "name", "==", "t", "{", "return", "IsImageTypeSupportedByVips", "(", "imageType", ")", ".", "Load", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsTypeNameSupported checks if a given image type name is supported
[ "IsTypeNameSupported", "checks", "if", "a", "given", "image", "type", "name", "is", "supported" ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/type.go#L139-L146
train
h2non/bimg
type.go
IsTypeSupportedSave
func IsTypeSupportedSave(t ImageType) bool { _, ok := ImageTypes[t] return ok && IsImageTypeSupportedByVips(t).Save }
go
func IsTypeSupportedSave(t ImageType) bool { _, ok := ImageTypes[t] return ok && IsImageTypeSupportedByVips(t).Save }
[ "func", "IsTypeSupportedSave", "(", "t", "ImageType", ")", "bool", "{", "_", ",", "ok", ":=", "ImageTypes", "[", "t", "]", "\n", "return", "ok", "&&", "IsImageTypeSupportedByVips", "(", "t", ")", ".", "Save", "\n", "}" ]
// IsTypeSupportedSave checks if a given image type is support for saving
[ "IsTypeSupportedSave", "checks", "if", "a", "given", "image", "type", "is", "support", "for", "saving" ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/type.go#L149-L152
train
h2non/bimg
type.go
IsTypeNameSupportedSave
func IsTypeNameSupportedSave(t string) bool { for imageType, name := range ImageTypes { if name == t { return IsImageTypeSupportedByVips(imageType).Save } } return false }
go
func IsTypeNameSupportedSave(t string) bool { for imageType, name := range ImageTypes { if name == t { return IsImageTypeSupportedByVips(imageType).Save } } return false }
[ "func", "IsTypeNameSupportedSave", "(", "t", "string", ")", "bool", "{", "for", "imageType", ",", "name", ":=", "range", "ImageTypes", "{", "if", "name", "==", "t", "{", "return", "IsImageTypeSupportedByVips", "(", "imageType", ")", ".", "Save", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsTypeNameSupportedSave checks if a given image type name is supported for // saving
[ "IsTypeNameSupportedSave", "checks", "if", "a", "given", "image", "type", "name", "is", "supported", "for", "saving" ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/type.go#L156-L163
train
h2non/bimg
vips.go
Initialize
func Initialize() { if C.VIPS_MAJOR_VERSION <= 7 && C.VIPS_MINOR_VERSION < 40 { panic("unsupported libvips version!") } m.Lock() runtime.LockOSThread() defer m.Unlock() defer runtime.UnlockOSThread() err := C.vips_init(C.CString("bimg")) if err != 0 { panic("unable to start vips!") } // Set libvips cache params C.vips_cache_set_max_mem(maxCacheMem) C.vips_cache_set_max(maxCacheSize) // Define a custom thread concurrency limit in libvips (this may generate thread-unsafe issues) // See: https://github.com/jcupitt/libvips/issues/261#issuecomment-92850414 if os.Getenv("VIPS_CONCURRENCY") == "" { C.vips_concurrency_set(1) } // Enable libvips cache tracing if os.Getenv("VIPS_TRACE") != "" { C.vips_enable_cache_set_trace() } initialized = true }
go
func Initialize() { if C.VIPS_MAJOR_VERSION <= 7 && C.VIPS_MINOR_VERSION < 40 { panic("unsupported libvips version!") } m.Lock() runtime.LockOSThread() defer m.Unlock() defer runtime.UnlockOSThread() err := C.vips_init(C.CString("bimg")) if err != 0 { panic("unable to start vips!") } // Set libvips cache params C.vips_cache_set_max_mem(maxCacheMem) C.vips_cache_set_max(maxCacheSize) // Define a custom thread concurrency limit in libvips (this may generate thread-unsafe issues) // See: https://github.com/jcupitt/libvips/issues/261#issuecomment-92850414 if os.Getenv("VIPS_CONCURRENCY") == "" { C.vips_concurrency_set(1) } // Enable libvips cache tracing if os.Getenv("VIPS_TRACE") != "" { C.vips_enable_cache_set_trace() } initialized = true }
[ "func", "Initialize", "(", ")", "{", "if", "C", ".", "VIPS_MAJOR_VERSION", "<=", "7", "&&", "C", ".", "VIPS_MINOR_VERSION", "<", "40", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "m", ".", "Lock", "(", ")", "\n", "runtime", ".", "LockOSThread", "(", ")", "\n", "defer", "m", ".", "Unlock", "(", ")", "\n", "defer", "runtime", ".", "UnlockOSThread", "(", ")", "\n\n", "err", ":=", "C", ".", "vips_init", "(", "C", ".", "CString", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Set libvips cache params", "C", ".", "vips_cache_set_max_mem", "(", "maxCacheMem", ")", "\n", "C", ".", "vips_cache_set_max", "(", "maxCacheSize", ")", "\n\n", "// Define a custom thread concurrency limit in libvips (this may generate thread-unsafe issues)", "// See: https://github.com/jcupitt/libvips/issues/261#issuecomment-92850414", "if", "os", ".", "Getenv", "(", "\"", "\"", ")", "==", "\"", "\"", "{", "C", ".", "vips_concurrency_set", "(", "1", ")", "\n", "}", "\n\n", "// Enable libvips cache tracing", "if", "os", ".", "Getenv", "(", "\"", "\"", ")", "!=", "\"", "\"", "{", "C", ".", "vips_enable_cache_set_trace", "(", ")", "\n", "}", "\n\n", "initialized", "=", "true", "\n", "}" ]
// Initialize is used to explicitly start libvips in thread-safe way. // Only call this function if you have previously turned off libvips.
[ "Initialize", "is", "used", "to", "explicitly", "start", "libvips", "in", "thread", "-", "safe", "way", ".", "Only", "call", "this", "function", "if", "you", "have", "previously", "turned", "off", "libvips", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/vips.go#L85-L116
train
h2non/bimg
vips.go
Shutdown
func Shutdown() { m.Lock() defer m.Unlock() if initialized { C.vips_shutdown() initialized = false } }
go
func Shutdown() { m.Lock() defer m.Unlock() if initialized { C.vips_shutdown() initialized = false } }
[ "func", "Shutdown", "(", ")", "{", "m", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "Unlock", "(", ")", "\n\n", "if", "initialized", "{", "C", ".", "vips_shutdown", "(", ")", "\n", "initialized", "=", "false", "\n", "}", "\n", "}" ]
// Shutdown is used to shutdown libvips in a thread-safe way. // You can call this to drop caches as well. // If libvips was already initialized, the function is no-op
[ "Shutdown", "is", "used", "to", "shutdown", "libvips", "in", "a", "thread", "-", "safe", "way", ".", "You", "can", "call", "this", "to", "drop", "caches", "as", "well", ".", "If", "libvips", "was", "already", "initialized", "the", "function", "is", "no", "-", "op" ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/vips.go#L121-L129
train
h2non/bimg
vips.go
VipsIsTypeSupported
func VipsIsTypeSupported(t ImageType) bool { if t == JPEG { return int(C.vips_type_find_bridge(C.JPEG)) != 0 } if t == WEBP { return int(C.vips_type_find_bridge(C.WEBP)) != 0 } if t == PNG { return int(C.vips_type_find_bridge(C.PNG)) != 0 } if t == GIF { return int(C.vips_type_find_bridge(C.GIF)) != 0 } if t == PDF { return int(C.vips_type_find_bridge(C.PDF)) != 0 } if t == SVG { return int(C.vips_type_find_bridge(C.SVG)) != 0 } if t == TIFF { return int(C.vips_type_find_bridge(C.TIFF)) != 0 } if t == MAGICK { return int(C.vips_type_find_bridge(C.MAGICK)) != 0 } return false }
go
func VipsIsTypeSupported(t ImageType) bool { if t == JPEG { return int(C.vips_type_find_bridge(C.JPEG)) != 0 } if t == WEBP { return int(C.vips_type_find_bridge(C.WEBP)) != 0 } if t == PNG { return int(C.vips_type_find_bridge(C.PNG)) != 0 } if t == GIF { return int(C.vips_type_find_bridge(C.GIF)) != 0 } if t == PDF { return int(C.vips_type_find_bridge(C.PDF)) != 0 } if t == SVG { return int(C.vips_type_find_bridge(C.SVG)) != 0 } if t == TIFF { return int(C.vips_type_find_bridge(C.TIFF)) != 0 } if t == MAGICK { return int(C.vips_type_find_bridge(C.MAGICK)) != 0 } return false }
[ "func", "VipsIsTypeSupported", "(", "t", "ImageType", ")", "bool", "{", "if", "t", "==", "JPEG", "{", "return", "int", "(", "C", ".", "vips_type_find_bridge", "(", "C", ".", "JPEG", ")", ")", "!=", "0", "\n", "}", "\n", "if", "t", "==", "WEBP", "{", "return", "int", "(", "C", ".", "vips_type_find_bridge", "(", "C", ".", "WEBP", ")", ")", "!=", "0", "\n", "}", "\n", "if", "t", "==", "PNG", "{", "return", "int", "(", "C", ".", "vips_type_find_bridge", "(", "C", ".", "PNG", ")", ")", "!=", "0", "\n", "}", "\n", "if", "t", "==", "GIF", "{", "return", "int", "(", "C", ".", "vips_type_find_bridge", "(", "C", ".", "GIF", ")", ")", "!=", "0", "\n", "}", "\n", "if", "t", "==", "PDF", "{", "return", "int", "(", "C", ".", "vips_type_find_bridge", "(", "C", ".", "PDF", ")", ")", "!=", "0", "\n", "}", "\n", "if", "t", "==", "SVG", "{", "return", "int", "(", "C", ".", "vips_type_find_bridge", "(", "C", ".", "SVG", ")", ")", "!=", "0", "\n", "}", "\n", "if", "t", "==", "TIFF", "{", "return", "int", "(", "C", ".", "vips_type_find_bridge", "(", "C", ".", "TIFF", ")", ")", "!=", "0", "\n", "}", "\n", "if", "t", "==", "MAGICK", "{", "return", "int", "(", "C", ".", "vips_type_find_bridge", "(", "C", ".", "MAGICK", ")", ")", "!=", "0", "\n", "}", "\n", "return", "false", "\n", "}" ]
// VipsIsTypeSupported returns true if the given image type // is supported by the current libvips compilation.
[ "VipsIsTypeSupported", "returns", "true", "if", "the", "given", "image", "type", "is", "supported", "by", "the", "current", "libvips", "compilation", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/vips.go#L163-L189
train
h2non/bimg
vips.go
VipsIsTypeSupportedSave
func VipsIsTypeSupportedSave(t ImageType) bool { if t == JPEG { return int(C.vips_type_find_save_bridge(C.JPEG)) != 0 } if t == WEBP { return int(C.vips_type_find_save_bridge(C.WEBP)) != 0 } if t == PNG { return int(C.vips_type_find_save_bridge(C.PNG)) != 0 } if t == TIFF { return int(C.vips_type_find_save_bridge(C.TIFF)) != 0 } return false }
go
func VipsIsTypeSupportedSave(t ImageType) bool { if t == JPEG { return int(C.vips_type_find_save_bridge(C.JPEG)) != 0 } if t == WEBP { return int(C.vips_type_find_save_bridge(C.WEBP)) != 0 } if t == PNG { return int(C.vips_type_find_save_bridge(C.PNG)) != 0 } if t == TIFF { return int(C.vips_type_find_save_bridge(C.TIFF)) != 0 } return false }
[ "func", "VipsIsTypeSupportedSave", "(", "t", "ImageType", ")", "bool", "{", "if", "t", "==", "JPEG", "{", "return", "int", "(", "C", ".", "vips_type_find_save_bridge", "(", "C", ".", "JPEG", ")", ")", "!=", "0", "\n", "}", "\n", "if", "t", "==", "WEBP", "{", "return", "int", "(", "C", ".", "vips_type_find_save_bridge", "(", "C", ".", "WEBP", ")", ")", "!=", "0", "\n", "}", "\n", "if", "t", "==", "PNG", "{", "return", "int", "(", "C", ".", "vips_type_find_save_bridge", "(", "C", ".", "PNG", ")", ")", "!=", "0", "\n", "}", "\n", "if", "t", "==", "TIFF", "{", "return", "int", "(", "C", ".", "vips_type_find_save_bridge", "(", "C", ".", "TIFF", ")", ")", "!=", "0", "\n", "}", "\n", "return", "false", "\n", "}" ]
// VipsIsTypeSupportedSave returns true if the given image type // is supported by the current libvips compilation for the // save operation.
[ "VipsIsTypeSupportedSave", "returns", "true", "if", "the", "given", "image", "type", "is", "supported", "by", "the", "current", "libvips", "compilation", "for", "the", "save", "operation", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/vips.go#L194-L208
train
tylertreat/BoomFilters
inverse.go
NewInverseBloomFilter
func NewInverseBloomFilter(capacity uint) *InverseBloomFilter { return &InverseBloomFilter{ array: make([]*[]byte, capacity), hashPool: &sync.Pool{New: func() interface{} { return fnv.New32() }}, capacity: capacity, } }
go
func NewInverseBloomFilter(capacity uint) *InverseBloomFilter { return &InverseBloomFilter{ array: make([]*[]byte, capacity), hashPool: &sync.Pool{New: func() interface{} { return fnv.New32() }}, capacity: capacity, } }
[ "func", "NewInverseBloomFilter", "(", "capacity", "uint", ")", "*", "InverseBloomFilter", "{", "return", "&", "InverseBloomFilter", "{", "array", ":", "make", "(", "[", "]", "*", "[", "]", "byte", ",", "capacity", ")", ",", "hashPool", ":", "&", "sync", ".", "Pool", "{", "New", ":", "func", "(", ")", "interface", "{", "}", "{", "return", "fnv", ".", "New32", "(", ")", "}", "}", ",", "capacity", ":", "capacity", ",", "}", "\n", "}" ]
// NewInverseBloomFilter creates and returns a new InverseBloomFilter with the // specified capacity.
[ "NewInverseBloomFilter", "creates", "and", "returns", "a", "new", "InverseBloomFilter", "with", "the", "specified", "capacity", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/inverse.go#L68-L74
train
tylertreat/BoomFilters
inverse.go
Add
func (i *InverseBloomFilter) Add(data []byte) Filter { index := i.index(data) i.getAndSet(index, data) return i }
go
func (i *InverseBloomFilter) Add(data []byte) Filter { index := i.index(data) i.getAndSet(index, data) return i }
[ "func", "(", "i", "*", "InverseBloomFilter", ")", "Add", "(", "data", "[", "]", "byte", ")", "Filter", "{", "index", ":=", "i", ".", "index", "(", "data", ")", "\n", "i", ".", "getAndSet", "(", "index", ",", "data", ")", "\n", "return", "i", "\n", "}" ]
// Add will add the data to the filter. It returns the filter to allow for // chaining.
[ "Add", "will", "add", "the", "data", "to", "the", "filter", ".", "It", "returns", "the", "filter", "to", "allow", "for", "chaining", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/inverse.go#L93-L97
train
tylertreat/BoomFilters
inverse.go
getAndSet
func (i *InverseBloomFilter) getAndSet(index uint32, data []byte) []byte { indexPtr := (*unsafe.Pointer)(unsafe.Pointer(&i.array[index])) keyUnsafe := unsafe.Pointer(&data) var oldKey []byte for { oldKeyUnsafe := atomic.LoadPointer(indexPtr) if atomic.CompareAndSwapPointer(indexPtr, oldKeyUnsafe, keyUnsafe) { oldKeyPtr := (*[]byte)(oldKeyUnsafe) if oldKeyPtr != nil { oldKey = *oldKeyPtr } break } } return oldKey }
go
func (i *InverseBloomFilter) getAndSet(index uint32, data []byte) []byte { indexPtr := (*unsafe.Pointer)(unsafe.Pointer(&i.array[index])) keyUnsafe := unsafe.Pointer(&data) var oldKey []byte for { oldKeyUnsafe := atomic.LoadPointer(indexPtr) if atomic.CompareAndSwapPointer(indexPtr, oldKeyUnsafe, keyUnsafe) { oldKeyPtr := (*[]byte)(oldKeyUnsafe) if oldKeyPtr != nil { oldKey = *oldKeyPtr } break } } return oldKey }
[ "func", "(", "i", "*", "InverseBloomFilter", ")", "getAndSet", "(", "index", "uint32", ",", "data", "[", "]", "byte", ")", "[", "]", "byte", "{", "indexPtr", ":=", "(", "*", "unsafe", ".", "Pointer", ")", "(", "unsafe", ".", "Pointer", "(", "&", "i", ".", "array", "[", "index", "]", ")", ")", "\n", "keyUnsafe", ":=", "unsafe", ".", "Pointer", "(", "&", "data", ")", "\n", "var", "oldKey", "[", "]", "byte", "\n", "for", "{", "oldKeyUnsafe", ":=", "atomic", ".", "LoadPointer", "(", "indexPtr", ")", "\n", "if", "atomic", ".", "CompareAndSwapPointer", "(", "indexPtr", ",", "oldKeyUnsafe", ",", "keyUnsafe", ")", "{", "oldKeyPtr", ":=", "(", "*", "[", "]", "byte", ")", "(", "oldKeyUnsafe", ")", "\n", "if", "oldKeyPtr", "!=", "nil", "{", "oldKey", "=", "*", "oldKeyPtr", "\n", "}", "\n", "break", "\n", "}", "\n", "}", "\n", "return", "oldKey", "\n", "}" ]
// getAndSet returns the data that was in the slice at the given index after // putting the new data in the slice at that index, atomically.
[ "getAndSet", "returns", "the", "data", "that", "was", "in", "the", "slice", "at", "the", "given", "index", "after", "putting", "the", "new", "data", "in", "the", "slice", "at", "that", "index", "atomically", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/inverse.go#L113-L128
train
tylertreat/BoomFilters
inverse.go
index
func (i *InverseBloomFilter) index(data []byte) uint32 { hash := i.hashPool.Get().(hash.Hash32) hash.Write(data) index := hash.Sum32() % uint32(i.capacity) hash.Reset() i.hashPool.Put(hash) return index }
go
func (i *InverseBloomFilter) index(data []byte) uint32 { hash := i.hashPool.Get().(hash.Hash32) hash.Write(data) index := hash.Sum32() % uint32(i.capacity) hash.Reset() i.hashPool.Put(hash) return index }
[ "func", "(", "i", "*", "InverseBloomFilter", ")", "index", "(", "data", "[", "]", "byte", ")", "uint32", "{", "hash", ":=", "i", ".", "hashPool", ".", "Get", "(", ")", ".", "(", "hash", ".", "Hash32", ")", "\n", "hash", ".", "Write", "(", "data", ")", "\n", "index", ":=", "hash", ".", "Sum32", "(", ")", "%", "uint32", "(", "i", ".", "capacity", ")", "\n", "hash", ".", "Reset", "(", ")", "\n", "i", ".", "hashPool", ".", "Put", "(", "hash", ")", "\n", "return", "index", "\n", "}" ]
// index returns the array index for the given data.
[ "index", "returns", "the", "array", "index", "for", "the", "given", "data", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/inverse.go#L131-L138
train
tylertreat/BoomFilters
inverse.go
SetHashFactory
func (i *InverseBloomFilter) SetHashFactory(h func() hash.Hash32) { i.hashPool = &sync.Pool{New: func() interface{} { return h() }} }
go
func (i *InverseBloomFilter) SetHashFactory(h func() hash.Hash32) { i.hashPool = &sync.Pool{New: func() interface{} { return h() }} }
[ "func", "(", "i", "*", "InverseBloomFilter", ")", "SetHashFactory", "(", "h", "func", "(", ")", "hash", ".", "Hash32", ")", "{", "i", ".", "hashPool", "=", "&", "sync", ".", "Pool", "{", "New", ":", "func", "(", ")", "interface", "{", "}", "{", "return", "h", "(", ")", "}", "}", "\n", "}" ]
// SetHashFactory sets the hashing function factory used in the filter.
[ "SetHashFactory", "sets", "the", "hashing", "function", "factory", "used", "in", "the", "filter", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/inverse.go#L141-L143
train
tylertreat/BoomFilters
deletable.go
NewDeletableBloomFilter
func NewDeletableBloomFilter(n, r uint, fpRate float64) *DeletableBloomFilter { var ( m = OptimalM(n, fpRate) k = OptimalK(fpRate) ) return &DeletableBloomFilter{ buckets: NewBuckets(m-r, 1), collisions: NewBuckets(r+1, 1), hash: fnv.New64(), m: m - r, regionSize: (m - r) / r, k: k, indexBuffer: make([]uint, k), } }
go
func NewDeletableBloomFilter(n, r uint, fpRate float64) *DeletableBloomFilter { var ( m = OptimalM(n, fpRate) k = OptimalK(fpRate) ) return &DeletableBloomFilter{ buckets: NewBuckets(m-r, 1), collisions: NewBuckets(r+1, 1), hash: fnv.New64(), m: m - r, regionSize: (m - r) / r, k: k, indexBuffer: make([]uint, k), } }
[ "func", "NewDeletableBloomFilter", "(", "n", ",", "r", "uint", ",", "fpRate", "float64", ")", "*", "DeletableBloomFilter", "{", "var", "(", "m", "=", "OptimalM", "(", "n", ",", "fpRate", ")", "\n", "k", "=", "OptimalK", "(", "fpRate", ")", "\n", ")", "\n", "return", "&", "DeletableBloomFilter", "{", "buckets", ":", "NewBuckets", "(", "m", "-", "r", ",", "1", ")", ",", "collisions", ":", "NewBuckets", "(", "r", "+", "1", ",", "1", ")", ",", "hash", ":", "fnv", ".", "New64", "(", ")", ",", "m", ":", "m", "-", "r", ",", "regionSize", ":", "(", "m", "-", "r", ")", "/", "r", ",", "k", ":", "k", ",", "indexBuffer", ":", "make", "(", "[", "]", "uint", ",", "k", ")", ",", "}", "\n", "}" ]
// NewDeletableBloomFilter creates a new DeletableBloomFilter optimized to // store n items with a specified target false-positive rate. The r value // determines the number of bits to use to store collision information. This // controls the deletability of an element. Refer to the paper for selecting an // optimal value.
[ "NewDeletableBloomFilter", "creates", "a", "new", "DeletableBloomFilter", "optimized", "to", "store", "n", "items", "with", "a", "specified", "target", "false", "-", "positive", "rate", ".", "The", "r", "value", "determines", "the", "number", "of", "bits", "to", "use", "to", "store", "collision", "information", ".", "This", "controls", "the", "deletability", "of", "an", "element", ".", "Refer", "to", "the", "paper", "for", "selecting", "an", "optimal", "value", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/deletable.go#L38-L52
train
tylertreat/BoomFilters
counting.go
NewCountingBloomFilter
func NewCountingBloomFilter(n uint, b uint8, fpRate float64) *CountingBloomFilter { var ( m = OptimalM(n, fpRate) k = OptimalK(fpRate) ) return &CountingBloomFilter{ buckets: NewBuckets(m, b), hash: fnv.New64(), m: m, k: k, indexBuffer: make([]uint, k), } }
go
func NewCountingBloomFilter(n uint, b uint8, fpRate float64) *CountingBloomFilter { var ( m = OptimalM(n, fpRate) k = OptimalK(fpRate) ) return &CountingBloomFilter{ buckets: NewBuckets(m, b), hash: fnv.New64(), m: m, k: k, indexBuffer: make([]uint, k), } }
[ "func", "NewCountingBloomFilter", "(", "n", "uint", ",", "b", "uint8", ",", "fpRate", "float64", ")", "*", "CountingBloomFilter", "{", "var", "(", "m", "=", "OptimalM", "(", "n", ",", "fpRate", ")", "\n", "k", "=", "OptimalK", "(", "fpRate", ")", "\n", ")", "\n", "return", "&", "CountingBloomFilter", "{", "buckets", ":", "NewBuckets", "(", "m", ",", "b", ")", ",", "hash", ":", "fnv", ".", "New64", "(", ")", ",", "m", ":", "m", ",", "k", ":", "k", ",", "indexBuffer", ":", "make", "(", "[", "]", "uint", ",", "k", ")", ",", "}", "\n", "}" ]
// NewCountingBloomFilter creates a new Counting Bloom Filter optimized to // store n items with a specified target false-positive rate and bucket size. // If you don't know how many bits to use for buckets, use // NewDefaultCountingBloomFilter for a sensible default.
[ "NewCountingBloomFilter", "creates", "a", "new", "Counting", "Bloom", "Filter", "optimized", "to", "store", "n", "items", "with", "a", "specified", "target", "false", "-", "positive", "rate", "and", "bucket", "size", ".", "If", "you", "don", "t", "know", "how", "many", "bits", "to", "use", "for", "buckets", "use", "NewDefaultCountingBloomFilter", "for", "a", "sensible", "default", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/counting.go#L37-L49
train
tylertreat/BoomFilters
countmin.go
NewCountMinSketch
func NewCountMinSketch(epsilon, delta float64) *CountMinSketch { var ( width = uint(math.Ceil(math.E / epsilon)) depth = uint(math.Ceil(math.Log(1 / delta))) matrix = make([][]uint64, depth) ) for i := uint(0); i < depth; i++ { matrix[i] = make([]uint64, width) } return &CountMinSketch{ matrix: matrix, width: width, depth: depth, epsilon: epsilon, delta: delta, hash: fnv.New64(), } }
go
func NewCountMinSketch(epsilon, delta float64) *CountMinSketch { var ( width = uint(math.Ceil(math.E / epsilon)) depth = uint(math.Ceil(math.Log(1 / delta))) matrix = make([][]uint64, depth) ) for i := uint(0); i < depth; i++ { matrix[i] = make([]uint64, width) } return &CountMinSketch{ matrix: matrix, width: width, depth: depth, epsilon: epsilon, delta: delta, hash: fnv.New64(), } }
[ "func", "NewCountMinSketch", "(", "epsilon", ",", "delta", "float64", ")", "*", "CountMinSketch", "{", "var", "(", "width", "=", "uint", "(", "math", ".", "Ceil", "(", "math", ".", "E", "/", "epsilon", ")", ")", "\n", "depth", "=", "uint", "(", "math", ".", "Ceil", "(", "math", ".", "Log", "(", "1", "/", "delta", ")", ")", ")", "\n", "matrix", "=", "make", "(", "[", "]", "[", "]", "uint64", ",", "depth", ")", "\n", ")", "\n\n", "for", "i", ":=", "uint", "(", "0", ")", ";", "i", "<", "depth", ";", "i", "++", "{", "matrix", "[", "i", "]", "=", "make", "(", "[", "]", "uint64", ",", "width", ")", "\n", "}", "\n\n", "return", "&", "CountMinSketch", "{", "matrix", ":", "matrix", ",", "width", ":", "width", ",", "depth", ":", "depth", ",", "epsilon", ":", "epsilon", ",", "delta", ":", "delta", ",", "hash", ":", "fnv", ".", "New64", "(", ")", ",", "}", "\n", "}" ]
// NewCountMinSketch creates a new Count-Min Sketch whose relative accuracy is // within a factor of epsilon with probability delta. Both of these parameters // affect the space and time complexity.
[ "NewCountMinSketch", "creates", "a", "new", "Count", "-", "Min", "Sketch", "whose", "relative", "accuracy", "is", "within", "a", "factor", "of", "epsilon", "with", "probability", "delta", ".", "Both", "of", "these", "parameters", "affect", "the", "space", "and", "time", "complexity", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/countmin.go#L46-L65
train
tylertreat/BoomFilters
countmin.go
Add
func (c *CountMinSketch) Add(data []byte) *CountMinSketch { lower, upper := hashKernel(data, c.hash) // Increment count in each row. for i := uint(0); i < c.depth; i++ { c.matrix[i][(uint(lower)+uint(upper)*i)%c.width]++ } c.count++ return c }
go
func (c *CountMinSketch) Add(data []byte) *CountMinSketch { lower, upper := hashKernel(data, c.hash) // Increment count in each row. for i := uint(0); i < c.depth; i++ { c.matrix[i][(uint(lower)+uint(upper)*i)%c.width]++ } c.count++ return c }
[ "func", "(", "c", "*", "CountMinSketch", ")", "Add", "(", "data", "[", "]", "byte", ")", "*", "CountMinSketch", "{", "lower", ",", "upper", ":=", "hashKernel", "(", "data", ",", "c", ".", "hash", ")", "\n\n", "// Increment count in each row.", "for", "i", ":=", "uint", "(", "0", ")", ";", "i", "<", "c", ".", "depth", ";", "i", "++", "{", "c", ".", "matrix", "[", "i", "]", "[", "(", "uint", "(", "lower", ")", "+", "uint", "(", "upper", ")", "*", "i", ")", "%", "c", ".", "width", "]", "++", "\n", "}", "\n\n", "c", ".", "count", "++", "\n", "return", "c", "\n", "}" ]
// Add will add the data to the set. Returns the CountMinSketch to allow for // chaining.
[ "Add", "will", "add", "the", "data", "to", "the", "set", ".", "Returns", "the", "CountMinSketch", "to", "allow", "for", "chaining", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/countmin.go#L84-L94
train
tylertreat/BoomFilters
countmin.go
Merge
func (c *CountMinSketch) Merge(other *CountMinSketch) error { if c.depth != other.depth { return errors.New("matrix depth must match") } if c.width != other.width { return errors.New("matrix width must match") } for i := uint(0); i < c.depth; i++ { for j := uint(0); j < c.width; j++ { c.matrix[i][j] += other.matrix[i][j] } } c.count += other.count return nil }
go
func (c *CountMinSketch) Merge(other *CountMinSketch) error { if c.depth != other.depth { return errors.New("matrix depth must match") } if c.width != other.width { return errors.New("matrix width must match") } for i := uint(0); i < c.depth; i++ { for j := uint(0); j < c.width; j++ { c.matrix[i][j] += other.matrix[i][j] } } c.count += other.count return nil }
[ "func", "(", "c", "*", "CountMinSketch", ")", "Merge", "(", "other", "*", "CountMinSketch", ")", "error", "{", "if", "c", ".", "depth", "!=", "other", ".", "depth", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "c", ".", "width", "!=", "other", ".", "width", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "for", "i", ":=", "uint", "(", "0", ")", ";", "i", "<", "c", ".", "depth", ";", "i", "++", "{", "for", "j", ":=", "uint", "(", "0", ")", ";", "j", "<", "c", ".", "width", ";", "j", "++", "{", "c", ".", "matrix", "[", "i", "]", "[", "j", "]", "+=", "other", ".", "matrix", "[", "i", "]", "[", "j", "]", "\n", "}", "\n", "}", "\n\n", "c", ".", "count", "+=", "other", ".", "count", "\n", "return", "nil", "\n", "}" ]
// Merge combines this CountMinSketch with another. Returns an error if the // matrix width and depth are not equal.
[ "Merge", "combines", "this", "CountMinSketch", "with", "another", ".", "Returns", "an", "error", "if", "the", "matrix", "width", "and", "depth", "are", "not", "equal", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/countmin.go#L114-L131
train
tylertreat/BoomFilters
countmin.go
Reset
func (c *CountMinSketch) Reset() *CountMinSketch { matrix := make([][]uint64, c.depth) for i := uint(0); i < c.depth; i++ { matrix[i] = make([]uint64, c.width) } c.matrix = matrix c.count = 0 return c }
go
func (c *CountMinSketch) Reset() *CountMinSketch { matrix := make([][]uint64, c.depth) for i := uint(0); i < c.depth; i++ { matrix[i] = make([]uint64, c.width) } c.matrix = matrix c.count = 0 return c }
[ "func", "(", "c", "*", "CountMinSketch", ")", "Reset", "(", ")", "*", "CountMinSketch", "{", "matrix", ":=", "make", "(", "[", "]", "[", "]", "uint64", ",", "c", ".", "depth", ")", "\n", "for", "i", ":=", "uint", "(", "0", ")", ";", "i", "<", "c", ".", "depth", ";", "i", "++", "{", "matrix", "[", "i", "]", "=", "make", "(", "[", "]", "uint64", ",", "c", ".", "width", ")", "\n", "}", "\n\n", "c", ".", "matrix", "=", "matrix", "\n", "c", ".", "count", "=", "0", "\n", "return", "c", "\n", "}" ]
// Reset restores the CountMinSketch to its original state. It returns itself // to allow for chaining.
[ "Reset", "restores", "the", "CountMinSketch", "to", "its", "original", "state", ".", "It", "returns", "itself", "to", "allow", "for", "chaining", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/countmin.go#L135-L144
train
tylertreat/BoomFilters
countmin.go
WriteDataTo
func (c *CountMinSketch) WriteDataTo(stream io.Writer) (int, error) { buf := new(bytes.Buffer) // serialize epsilon and delta as cms configuration check err := binary.Write(buf, binary.LittleEndian, c.epsilon) if err != nil { return 0, err } err = binary.Write(buf, binary.LittleEndian, c.delta) if err != nil { return 0, err } err = binary.Write(buf, binary.LittleEndian, c.count) if err != nil { return 0, err } // encode matrix for i := range c.matrix { err = binary.Write(buf, binary.LittleEndian, c.matrix[i]) if err != nil { return 0, err } } return stream.Write(buf.Bytes()) }
go
func (c *CountMinSketch) WriteDataTo(stream io.Writer) (int, error) { buf := new(bytes.Buffer) // serialize epsilon and delta as cms configuration check err := binary.Write(buf, binary.LittleEndian, c.epsilon) if err != nil { return 0, err } err = binary.Write(buf, binary.LittleEndian, c.delta) if err != nil { return 0, err } err = binary.Write(buf, binary.LittleEndian, c.count) if err != nil { return 0, err } // encode matrix for i := range c.matrix { err = binary.Write(buf, binary.LittleEndian, c.matrix[i]) if err != nil { return 0, err } } return stream.Write(buf.Bytes()) }
[ "func", "(", "c", "*", "CountMinSketch", ")", "WriteDataTo", "(", "stream", "io", ".", "Writer", ")", "(", "int", ",", "error", ")", "{", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "// serialize epsilon and delta as cms configuration check", "err", ":=", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "c", ".", "epsilon", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "err", "=", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "c", ".", "delta", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "err", "=", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "c", ".", "count", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "// encode matrix", "for", "i", ":=", "range", "c", ".", "matrix", "{", "err", "=", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "c", ".", "matrix", "[", "i", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "stream", ".", "Write", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// WriteDataTo writes a binary representation of the CMS data to // an io stream. It returns the number of bytes written and error
[ "WriteDataTo", "writes", "a", "binary", "representation", "of", "the", "CMS", "data", "to", "an", "io", "stream", ".", "It", "returns", "the", "number", "of", "bytes", "written", "and", "error" ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/countmin.go#L153-L177
train
tylertreat/BoomFilters
cuckoo.go
indexOf
func (b bucket) indexOf(f []byte) int { for i, fingerprint := range b { if bytes.Equal(f, fingerprint) { return i } } return -1 }
go
func (b bucket) indexOf(f []byte) int { for i, fingerprint := range b { if bytes.Equal(f, fingerprint) { return i } } return -1 }
[ "func", "(", "b", "bucket", ")", "indexOf", "(", "f", "[", "]", "byte", ")", "int", "{", "for", "i", ",", "fingerprint", ":=", "range", "b", "{", "if", "bytes", ".", "Equal", "(", "f", ",", "fingerprint", ")", "{", "return", "i", "\n", "}", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// indexOf returns the entry index of the given fingerprint or -1 if it's not // in the bucket.
[ "indexOf", "returns", "the", "entry", "index", "of", "the", "given", "fingerprint", "or", "-", "1", "if", "it", "s", "not", "in", "the", "bucket", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/cuckoo.go#L28-L35
train
tylertreat/BoomFilters
cuckoo.go
getEmptyEntry
func (b bucket) getEmptyEntry() (int, error) { for i, fingerprint := range b { if fingerprint == nil { return i, nil } } return -1, errors.New("full") }
go
func (b bucket) getEmptyEntry() (int, error) { for i, fingerprint := range b { if fingerprint == nil { return i, nil } } return -1, errors.New("full") }
[ "func", "(", "b", "bucket", ")", "getEmptyEntry", "(", ")", "(", "int", ",", "error", ")", "{", "for", "i", ",", "fingerprint", ":=", "range", "b", "{", "if", "fingerprint", "==", "nil", "{", "return", "i", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "-", "1", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// getEmptyEntry returns the index of the next available entry in the bucket or // an error if it's full.
[ "getEmptyEntry", "returns", "the", "index", "of", "the", "next", "available", "entry", "in", "the", "bucket", "or", "an", "error", "if", "it", "s", "full", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/cuckoo.go#L39-L46
train
tylertreat/BoomFilters
cuckoo.go
NewCuckooFilter
func NewCuckooFilter(n uint, fpRate float64) *CuckooFilter { var ( b = uint(4) f = calculateF(b, fpRate) m = power2(n / f * 8) buckets = make([]bucket, m) ) for i := uint(0); i < m; i++ { buckets[i] = make(bucket, b) } return &CuckooFilter{ buckets: buckets, hash: fnv.New32(), m: m, b: b, f: f, n: n, } }
go
func NewCuckooFilter(n uint, fpRate float64) *CuckooFilter { var ( b = uint(4) f = calculateF(b, fpRate) m = power2(n / f * 8) buckets = make([]bucket, m) ) for i := uint(0); i < m; i++ { buckets[i] = make(bucket, b) } return &CuckooFilter{ buckets: buckets, hash: fnv.New32(), m: m, b: b, f: f, n: n, } }
[ "func", "NewCuckooFilter", "(", "n", "uint", ",", "fpRate", "float64", ")", "*", "CuckooFilter", "{", "var", "(", "b", "=", "uint", "(", "4", ")", "\n", "f", "=", "calculateF", "(", "b", ",", "fpRate", ")", "\n", "m", "=", "power2", "(", "n", "/", "f", "*", "8", ")", "\n", "buckets", "=", "make", "(", "[", "]", "bucket", ",", "m", ")", "\n", ")", "\n\n", "for", "i", ":=", "uint", "(", "0", ")", ";", "i", "<", "m", ";", "i", "++", "{", "buckets", "[", "i", "]", "=", "make", "(", "bucket", ",", "b", ")", "\n", "}", "\n\n", "return", "&", "CuckooFilter", "{", "buckets", ":", "buckets", ",", "hash", ":", "fnv", ".", "New32", "(", ")", ",", "m", ":", "m", ",", "b", ":", "b", ",", "f", ":", "f", ",", "n", ":", "n", ",", "}", "\n", "}" ]
// NewCuckooFilter creates a new Cuckoo Bloom filter optimized to store n items // with a specified target false-positive rate.
[ "NewCuckooFilter", "creates", "a", "new", "Cuckoo", "Bloom", "filter", "optimized", "to", "store", "n", "items", "with", "a", "specified", "target", "false", "-", "positive", "rate", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/cuckoo.go#L75-L95
train
tylertreat/BoomFilters
cuckoo.go
Add
func (c *CuckooFilter) Add(data []byte) error { return c.add(c.components(data)) }
go
func (c *CuckooFilter) Add(data []byte) error { return c.add(c.components(data)) }
[ "func", "(", "c", "*", "CuckooFilter", ")", "Add", "(", "data", "[", "]", "byte", ")", "error", "{", "return", "c", ".", "add", "(", "c", ".", "components", "(", "data", ")", ")", "\n", "}" ]
// Add will add the data to the Cuckoo Filter. It returns an error if the // filter is full. If the filter is full, an item is removed to make room for // the new item. This introduces a possibility for false negatives. To avoid // this, use Count and Capacity to check if the filter is full before adding an // item.
[ "Add", "will", "add", "the", "data", "to", "the", "Cuckoo", "Filter", ".", "It", "returns", "an", "error", "if", "the", "filter", "is", "full", ".", "If", "the", "filter", "is", "full", "an", "item", "is", "removed", "to", "make", "room", "for", "the", "new", "item", ".", "This", "introduces", "a", "possibility", "for", "false", "negatives", ".", "To", "avoid", "this", "use", "Count", "and", "Capacity", "to", "check", "if", "the", "filter", "is", "full", "before", "adding", "an", "item", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/cuckoo.go#L127-L129
train
tylertreat/BoomFilters
cuckoo.go
add
func (c *CuckooFilter) add(i1, i2 uint, f []byte) error { // Try to insert into bucket[i1]. b1 := c.buckets[i1%c.m] if idx, err := b1.getEmptyEntry(); err == nil { b1[idx] = f c.count++ return nil } // Try to insert into bucket[i2]. b2 := c.buckets[i2%c.m] if idx, err := b2.getEmptyEntry(); err == nil { b2[idx] = f c.count++ return nil } // Must relocate existing items. i := i1 for n := 0; n < maxNumKicks; n++ { bucketIdx := i % c.m entryIdx := rand.Intn(int(c.b)) f, c.buckets[bucketIdx][entryIdx] = c.buckets[bucketIdx][entryIdx], f i = i ^ uint(binary.BigEndian.Uint32(c.computeHash(f))) b := c.buckets[i%c.m] if idx, err := b.getEmptyEntry(); err == nil { b[idx] = f c.count++ return nil } } return errors.New("full") }
go
func (c *CuckooFilter) add(i1, i2 uint, f []byte) error { // Try to insert into bucket[i1]. b1 := c.buckets[i1%c.m] if idx, err := b1.getEmptyEntry(); err == nil { b1[idx] = f c.count++ return nil } // Try to insert into bucket[i2]. b2 := c.buckets[i2%c.m] if idx, err := b2.getEmptyEntry(); err == nil { b2[idx] = f c.count++ return nil } // Must relocate existing items. i := i1 for n := 0; n < maxNumKicks; n++ { bucketIdx := i % c.m entryIdx := rand.Intn(int(c.b)) f, c.buckets[bucketIdx][entryIdx] = c.buckets[bucketIdx][entryIdx], f i = i ^ uint(binary.BigEndian.Uint32(c.computeHash(f))) b := c.buckets[i%c.m] if idx, err := b.getEmptyEntry(); err == nil { b[idx] = f c.count++ return nil } } return errors.New("full") }
[ "func", "(", "c", "*", "CuckooFilter", ")", "add", "(", "i1", ",", "i2", "uint", ",", "f", "[", "]", "byte", ")", "error", "{", "// Try to insert into bucket[i1].", "b1", ":=", "c", ".", "buckets", "[", "i1", "%", "c", ".", "m", "]", "\n", "if", "idx", ",", "err", ":=", "b1", ".", "getEmptyEntry", "(", ")", ";", "err", "==", "nil", "{", "b1", "[", "idx", "]", "=", "f", "\n", "c", ".", "count", "++", "\n", "return", "nil", "\n", "}", "\n\n", "// Try to insert into bucket[i2].", "b2", ":=", "c", ".", "buckets", "[", "i2", "%", "c", ".", "m", "]", "\n", "if", "idx", ",", "err", ":=", "b2", ".", "getEmptyEntry", "(", ")", ";", "err", "==", "nil", "{", "b2", "[", "idx", "]", "=", "f", "\n", "c", ".", "count", "++", "\n", "return", "nil", "\n", "}", "\n\n", "// Must relocate existing items.", "i", ":=", "i1", "\n", "for", "n", ":=", "0", ";", "n", "<", "maxNumKicks", ";", "n", "++", "{", "bucketIdx", ":=", "i", "%", "c", ".", "m", "\n", "entryIdx", ":=", "rand", ".", "Intn", "(", "int", "(", "c", ".", "b", ")", ")", "\n", "f", ",", "c", ".", "buckets", "[", "bucketIdx", "]", "[", "entryIdx", "]", "=", "c", ".", "buckets", "[", "bucketIdx", "]", "[", "entryIdx", "]", ",", "f", "\n", "i", "=", "i", "^", "uint", "(", "binary", ".", "BigEndian", ".", "Uint32", "(", "c", ".", "computeHash", "(", "f", ")", ")", ")", "\n", "b", ":=", "c", ".", "buckets", "[", "i", "%", "c", ".", "m", "]", "\n", "if", "idx", ",", "err", ":=", "b", ".", "getEmptyEntry", "(", ")", ";", "err", "==", "nil", "{", "b", "[", "idx", "]", "=", "f", "\n", "c", ".", "count", "++", "\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// add will insert the fingerprint into the filter returning an error if the // filter is full.
[ "add", "will", "insert", "the", "fingerprint", "into", "the", "filter", "returning", "an", "error", "if", "the", "filter", "is", "full", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/cuckoo.go#L185-L218
train
tylertreat/BoomFilters
cuckoo.go
components
func (c *CuckooFilter) components(data []byte) (uint, uint, []byte) { var ( hash = c.computeHash(data) f = hash[0:c.f] i1 = uint(binary.BigEndian.Uint32(hash)) i2 = i1 ^ uint(binary.BigEndian.Uint32(c.computeHash(f))) ) return i1, i2, f }
go
func (c *CuckooFilter) components(data []byte) (uint, uint, []byte) { var ( hash = c.computeHash(data) f = hash[0:c.f] i1 = uint(binary.BigEndian.Uint32(hash)) i2 = i1 ^ uint(binary.BigEndian.Uint32(c.computeHash(f))) ) return i1, i2, f }
[ "func", "(", "c", "*", "CuckooFilter", ")", "components", "(", "data", "[", "]", "byte", ")", "(", "uint", ",", "uint", ",", "[", "]", "byte", ")", "{", "var", "(", "hash", "=", "c", ".", "computeHash", "(", "data", ")", "\n", "f", "=", "hash", "[", "0", ":", "c", ".", "f", "]", "\n", "i1", "=", "uint", "(", "binary", ".", "BigEndian", ".", "Uint32", "(", "hash", ")", ")", "\n", "i2", "=", "i1", "^", "uint", "(", "binary", ".", "BigEndian", ".", "Uint32", "(", "c", ".", "computeHash", "(", "f", ")", ")", ")", "\n", ")", "\n\n", "return", "i1", ",", "i2", ",", "f", "\n", "}" ]
// components returns the two hash values used to index into the buckets and // the fingerprint for the given element.
[ "components", "returns", "the", "two", "hash", "values", "used", "to", "index", "into", "the", "buckets", "and", "the", "fingerprint", "for", "the", "given", "element", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/cuckoo.go#L222-L231
train
tylertreat/BoomFilters
cuckoo.go
computeHash
func (c *CuckooFilter) computeHash(data []byte) []byte { c.hash.Write(data) hash := c.hash.Sum(nil) c.hash.Reset() return hash }
go
func (c *CuckooFilter) computeHash(data []byte) []byte { c.hash.Write(data) hash := c.hash.Sum(nil) c.hash.Reset() return hash }
[ "func", "(", "c", "*", "CuckooFilter", ")", "computeHash", "(", "data", "[", "]", "byte", ")", "[", "]", "byte", "{", "c", ".", "hash", ".", "Write", "(", "data", ")", "\n", "hash", ":=", "c", ".", "hash", ".", "Sum", "(", "nil", ")", "\n", "c", ".", "hash", ".", "Reset", "(", ")", "\n", "return", "hash", "\n", "}" ]
// computeHash returns a 32-bit hash value for the given data.
[ "computeHash", "returns", "a", "32", "-", "bit", "hash", "value", "for", "the", "given", "data", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/cuckoo.go#L234-L239
train
tylertreat/BoomFilters
cuckoo.go
calculateF
func calculateF(b uint, epsilon float64) uint { f := uint(math.Ceil(math.Log(2 * float64(b) / epsilon))) f = f / 8 if f <= 0 { f = 1 } return f }
go
func calculateF(b uint, epsilon float64) uint { f := uint(math.Ceil(math.Log(2 * float64(b) / epsilon))) f = f / 8 if f <= 0 { f = 1 } return f }
[ "func", "calculateF", "(", "b", "uint", ",", "epsilon", "float64", ")", "uint", "{", "f", ":=", "uint", "(", "math", ".", "Ceil", "(", "math", ".", "Log", "(", "2", "*", "float64", "(", "b", ")", "/", "epsilon", ")", ")", ")", "\n", "f", "=", "f", "/", "8", "\n", "if", "f", "<=", "0", "{", "f", "=", "1", "\n", "}", "\n", "return", "f", "\n", "}" ]
// calculateF returns the optimal fingerprint length in bytes for the given // bucket size and false-positive rate epsilon.
[ "calculateF", "returns", "the", "optimal", "fingerprint", "length", "in", "bytes", "for", "the", "given", "bucket", "size", "and", "false", "-", "positive", "rate", "epsilon", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/cuckoo.go#L249-L256
train
tylertreat/BoomFilters
cuckoo.go
power2
func power2(x uint) uint { x-- x |= x >> 1 x |= x >> 2 x |= x >> 4 x |= x >> 8 x |= x >> 16 x |= x >> 32 x++ return x }
go
func power2(x uint) uint { x-- x |= x >> 1 x |= x >> 2 x |= x >> 4 x |= x >> 8 x |= x >> 16 x |= x >> 32 x++ return x }
[ "func", "power2", "(", "x", "uint", ")", "uint", "{", "x", "--", "\n", "x", "|=", "x", ">>", "1", "\n", "x", "|=", "x", ">>", "2", "\n", "x", "|=", "x", ">>", "4", "\n", "x", "|=", "x", ">>", "8", "\n", "x", "|=", "x", ">>", "16", "\n", "x", "|=", "x", ">>", "32", "\n", "x", "++", "\n", "return", "x", "\n", "}" ]
// power2 calculates the next power of two for the given value.
[ "power2", "calculates", "the", "next", "power", "of", "two", "for", "the", "given", "value", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/cuckoo.go#L259-L269
train
tylertreat/BoomFilters
topk.go
NewTopK
func NewTopK(epsilon, delta float64, k uint) *TopK { elements := make(elementHeap, 0, k) heap.Init(&elements) return &TopK{ cms: NewCountMinSketch(epsilon, delta), k: k, elements: &elements, } }
go
func NewTopK(epsilon, delta float64, k uint) *TopK { elements := make(elementHeap, 0, k) heap.Init(&elements) return &TopK{ cms: NewCountMinSketch(epsilon, delta), k: k, elements: &elements, } }
[ "func", "NewTopK", "(", "epsilon", ",", "delta", "float64", ",", "k", "uint", ")", "*", "TopK", "{", "elements", ":=", "make", "(", "elementHeap", ",", "0", ",", "k", ")", "\n", "heap", ".", "Init", "(", "&", "elements", ")", "\n", "return", "&", "TopK", "{", "cms", ":", "NewCountMinSketch", "(", "epsilon", ",", "delta", ")", ",", "k", ":", "k", ",", "elements", ":", "&", "elements", ",", "}", "\n", "}" ]
// NewTopK creates a new TopK backed by a Count-Min sketch whose relative // accuracy is within a factor of epsilon with probability delta. It tracks the // k-most frequent elements.
[ "NewTopK", "creates", "a", "new", "TopK", "backed", "by", "a", "Count", "-", "Min", "sketch", "whose", "relative", "accuracy", "is", "within", "a", "factor", "of", "epsilon", "with", "probability", "delta", ".", "It", "tracks", "the", "k", "-", "most", "frequent", "elements", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/topk.go#L45-L53
train
tylertreat/BoomFilters
topk.go
Add
func (t *TopK) Add(data []byte) *TopK { t.cms.Add(data) t.n++ freq := t.cms.Count(data) if t.isTop(freq) { t.insert(data, freq) } return t }
go
func (t *TopK) Add(data []byte) *TopK { t.cms.Add(data) t.n++ freq := t.cms.Count(data) if t.isTop(freq) { t.insert(data, freq) } return t }
[ "func", "(", "t", "*", "TopK", ")", "Add", "(", "data", "[", "]", "byte", ")", "*", "TopK", "{", "t", ".", "cms", ".", "Add", "(", "data", ")", "\n", "t", ".", "n", "++", "\n\n", "freq", ":=", "t", ".", "cms", ".", "Count", "(", "data", ")", "\n", "if", "t", ".", "isTop", "(", "freq", ")", "{", "t", ".", "insert", "(", "data", ",", "freq", ")", "\n", "}", "\n\n", "return", "t", "\n", "}" ]
// Add will add the data to the Count-Min Sketch and update the top-k heap if // applicable. Returns the TopK to allow for chaining.
[ "Add", "will", "add", "the", "data", "to", "the", "Count", "-", "Min", "Sketch", "and", "update", "the", "top", "-", "k", "heap", "if", "applicable", ".", "Returns", "the", "TopK", "to", "allow", "for", "chaining", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/topk.go#L57-L67
train
tylertreat/BoomFilters
topk.go
Elements
func (t *TopK) Elements() []*Element { if t.elements.Len() == 0 { return make([]*Element, 0) } elements := make(elementHeap, t.elements.Len()) copy(elements, *t.elements) heap.Init(&elements) topK := make([]*Element, 0, t.k) for elements.Len() > 0 { topK = append(topK, heap.Pop(&elements).(*Element)) } return topK }
go
func (t *TopK) Elements() []*Element { if t.elements.Len() == 0 { return make([]*Element, 0) } elements := make(elementHeap, t.elements.Len()) copy(elements, *t.elements) heap.Init(&elements) topK := make([]*Element, 0, t.k) for elements.Len() > 0 { topK = append(topK, heap.Pop(&elements).(*Element)) } return topK }
[ "func", "(", "t", "*", "TopK", ")", "Elements", "(", ")", "[", "]", "*", "Element", "{", "if", "t", ".", "elements", ".", "Len", "(", ")", "==", "0", "{", "return", "make", "(", "[", "]", "*", "Element", ",", "0", ")", "\n", "}", "\n\n", "elements", ":=", "make", "(", "elementHeap", ",", "t", ".", "elements", ".", "Len", "(", ")", ")", "\n", "copy", "(", "elements", ",", "*", "t", ".", "elements", ")", "\n", "heap", ".", "Init", "(", "&", "elements", ")", "\n", "topK", ":=", "make", "(", "[", "]", "*", "Element", ",", "0", ",", "t", ".", "k", ")", "\n\n", "for", "elements", ".", "Len", "(", ")", ">", "0", "{", "topK", "=", "append", "(", "topK", ",", "heap", ".", "Pop", "(", "&", "elements", ")", ".", "(", "*", "Element", ")", ")", "\n", "}", "\n\n", "return", "topK", "\n", "}" ]
// Elements returns the top-k elements from lowest to highest frequency.
[ "Elements", "returns", "the", "top", "-", "k", "elements", "from", "lowest", "to", "highest", "frequency", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/topk.go#L70-L85
train
tylertreat/BoomFilters
topk.go
Reset
func (t *TopK) Reset() *TopK { t.cms.Reset() elements := make(elementHeap, 0, t.k) heap.Init(&elements) t.elements = &elements t.n = 0 return t }
go
func (t *TopK) Reset() *TopK { t.cms.Reset() elements := make(elementHeap, 0, t.k) heap.Init(&elements) t.elements = &elements t.n = 0 return t }
[ "func", "(", "t", "*", "TopK", ")", "Reset", "(", ")", "*", "TopK", "{", "t", ".", "cms", ".", "Reset", "(", ")", "\n", "elements", ":=", "make", "(", "elementHeap", ",", "0", ",", "t", ".", "k", ")", "\n", "heap", ".", "Init", "(", "&", "elements", ")", "\n", "t", ".", "elements", "=", "&", "elements", "\n", "t", ".", "n", "=", "0", "\n", "return", "t", "\n", "}" ]
// Reset restores the TopK to its original state. It returns itself to allow // for chaining.
[ "Reset", "restores", "the", "TopK", "to", "its", "original", "state", ".", "It", "returns", "itself", "to", "allow", "for", "chaining", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/topk.go#L89-L96
train
tylertreat/BoomFilters
topk.go
isTop
func (t *TopK) isTop(freq uint64) bool { if t.elements.Len() < int(t.k) { return true } return freq >= (*t.elements)[0].Freq }
go
func (t *TopK) isTop(freq uint64) bool { if t.elements.Len() < int(t.k) { return true } return freq >= (*t.elements)[0].Freq }
[ "func", "(", "t", "*", "TopK", ")", "isTop", "(", "freq", "uint64", ")", "bool", "{", "if", "t", ".", "elements", ".", "Len", "(", ")", "<", "int", "(", "t", ".", "k", ")", "{", "return", "true", "\n", "}", "\n\n", "return", "freq", ">=", "(", "*", "t", ".", "elements", ")", "[", "0", "]", ".", "Freq", "\n", "}" ]
// isTop indicates if the given frequency falls within the top-k heap.
[ "isTop", "indicates", "if", "the", "given", "frequency", "falls", "within", "the", "top", "-", "k", "heap", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/topk.go#L99-L105
train
tylertreat/BoomFilters
topk.go
insert
func (t *TopK) insert(data []byte, freq uint64) { for i, element := range *t.elements { if bytes.Equal(data, element.Data) { // Element already in top-k, replace it with new frequency. heap.Remove(t.elements, i) element.Freq = freq heap.Push(t.elements, element) return } } if t.elements.Len() == int(t.k) { // Remove minimum-frequency element. heap.Pop(t.elements) } // Add element to top-k. heap.Push(t.elements, &Element{Data: data, Freq: freq}) }
go
func (t *TopK) insert(data []byte, freq uint64) { for i, element := range *t.elements { if bytes.Equal(data, element.Data) { // Element already in top-k, replace it with new frequency. heap.Remove(t.elements, i) element.Freq = freq heap.Push(t.elements, element) return } } if t.elements.Len() == int(t.k) { // Remove minimum-frequency element. heap.Pop(t.elements) } // Add element to top-k. heap.Push(t.elements, &Element{Data: data, Freq: freq}) }
[ "func", "(", "t", "*", "TopK", ")", "insert", "(", "data", "[", "]", "byte", ",", "freq", "uint64", ")", "{", "for", "i", ",", "element", ":=", "range", "*", "t", ".", "elements", "{", "if", "bytes", ".", "Equal", "(", "data", ",", "element", ".", "Data", ")", "{", "// Element already in top-k, replace it with new frequency.", "heap", ".", "Remove", "(", "t", ".", "elements", ",", "i", ")", "\n", "element", ".", "Freq", "=", "freq", "\n", "heap", ".", "Push", "(", "t", ".", "elements", ",", "element", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "if", "t", ".", "elements", ".", "Len", "(", ")", "==", "int", "(", "t", ".", "k", ")", "{", "// Remove minimum-frequency element.", "heap", ".", "Pop", "(", "t", ".", "elements", ")", "\n", "}", "\n\n", "// Add element to top-k.", "heap", ".", "Push", "(", "t", ".", "elements", ",", "&", "Element", "{", "Data", ":", "data", ",", "Freq", ":", "freq", "}", ")", "\n", "}" ]
// insert adds the data to the top-k heap. If the data is already an element, // the frequency is updated. If the heap already has k elements, the element // with the minimum frequency is removed.
[ "insert", "adds", "the", "data", "to", "the", "top", "-", "k", "heap", ".", "If", "the", "data", "is", "already", "an", "element", "the", "frequency", "is", "updated", ".", "If", "the", "heap", "already", "has", "k", "elements", "the", "element", "with", "the", "minimum", "frequency", "is", "removed", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/topk.go#L110-L128
train
tylertreat/BoomFilters
buckets.go
NewBuckets
func NewBuckets(count uint, bucketSize uint8) *Buckets { return &Buckets{ count: count, data: make([]byte, (count*uint(bucketSize)+7)/8), bucketSize: bucketSize, max: (1 << bucketSize) - 1, } }
go
func NewBuckets(count uint, bucketSize uint8) *Buckets { return &Buckets{ count: count, data: make([]byte, (count*uint(bucketSize)+7)/8), bucketSize: bucketSize, max: (1 << bucketSize) - 1, } }
[ "func", "NewBuckets", "(", "count", "uint", ",", "bucketSize", "uint8", ")", "*", "Buckets", "{", "return", "&", "Buckets", "{", "count", ":", "count", ",", "data", ":", "make", "(", "[", "]", "byte", ",", "(", "count", "*", "uint", "(", "bucketSize", ")", "+", "7", ")", "/", "8", ")", ",", "bucketSize", ":", "bucketSize", ",", "max", ":", "(", "1", "<<", "bucketSize", ")", "-", "1", ",", "}", "\n", "}" ]
// NewBuckets creates a new Buckets with the provided number of buckets where // each bucket is the specified number of bits.
[ "NewBuckets", "creates", "a", "new", "Buckets", "with", "the", "provided", "number", "of", "buckets", "where", "each", "bucket", "is", "the", "specified", "number", "of", "bits", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/buckets.go#L20-L27
train
tylertreat/BoomFilters
buckets.go
Increment
func (b *Buckets) Increment(bucket uint, delta int32) *Buckets { val := int32(b.getBits(bucket*uint(b.bucketSize), uint(b.bucketSize))) + delta if val > int32(b.max) { val = int32(b.max) } else if val < 0 { val = 0 } b.setBits(uint32(bucket)*uint32(b.bucketSize), uint32(b.bucketSize), uint32(val)) return b }
go
func (b *Buckets) Increment(bucket uint, delta int32) *Buckets { val := int32(b.getBits(bucket*uint(b.bucketSize), uint(b.bucketSize))) + delta if val > int32(b.max) { val = int32(b.max) } else if val < 0 { val = 0 } b.setBits(uint32(bucket)*uint32(b.bucketSize), uint32(b.bucketSize), uint32(val)) return b }
[ "func", "(", "b", "*", "Buckets", ")", "Increment", "(", "bucket", "uint", ",", "delta", "int32", ")", "*", "Buckets", "{", "val", ":=", "int32", "(", "b", ".", "getBits", "(", "bucket", "*", "uint", "(", "b", ".", "bucketSize", ")", ",", "uint", "(", "b", ".", "bucketSize", ")", ")", ")", "+", "delta", "\n", "if", "val", ">", "int32", "(", "b", ".", "max", ")", "{", "val", "=", "int32", "(", "b", ".", "max", ")", "\n", "}", "else", "if", "val", "<", "0", "{", "val", "=", "0", "\n", "}", "\n\n", "b", ".", "setBits", "(", "uint32", "(", "bucket", ")", "*", "uint32", "(", "b", ".", "bucketSize", ")", ",", "uint32", "(", "b", ".", "bucketSize", ")", ",", "uint32", "(", "val", ")", ")", "\n", "return", "b", "\n", "}" ]
// Increment will increment the value in the specified bucket by the provided // delta. A bucket can be decremented by providing a negative delta. The value // is clamped to zero and the maximum bucket value. Returns itself to allow for // chaining.
[ "Increment", "will", "increment", "the", "value", "in", "the", "specified", "bucket", "by", "the", "provided", "delta", ".", "A", "bucket", "can", "be", "decremented", "by", "providing", "a", "negative", "delta", ".", "The", "value", "is", "clamped", "to", "zero", "and", "the", "maximum", "bucket", "value", ".", "Returns", "itself", "to", "allow", "for", "chaining", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/buckets.go#L43-L53
train
tylertreat/BoomFilters
buckets.go
Set
func (b *Buckets) Set(bucket uint, value uint8) *Buckets { if value > b.max { value = b.max } b.setBits(uint32(bucket)*uint32(b.bucketSize), uint32(b.bucketSize), uint32(value)) return b }
go
func (b *Buckets) Set(bucket uint, value uint8) *Buckets { if value > b.max { value = b.max } b.setBits(uint32(bucket)*uint32(b.bucketSize), uint32(b.bucketSize), uint32(value)) return b }
[ "func", "(", "b", "*", "Buckets", ")", "Set", "(", "bucket", "uint", ",", "value", "uint8", ")", "*", "Buckets", "{", "if", "value", ">", "b", ".", "max", "{", "value", "=", "b", ".", "max", "\n", "}", "\n\n", "b", ".", "setBits", "(", "uint32", "(", "bucket", ")", "*", "uint32", "(", "b", ".", "bucketSize", ")", ",", "uint32", "(", "b", ".", "bucketSize", ")", ",", "uint32", "(", "value", ")", ")", "\n", "return", "b", "\n", "}" ]
// Set will set the bucket value. The value is clamped to zero and the maximum // bucket value. Returns itself to allow for chaining.
[ "Set", "will", "set", "the", "bucket", "value", ".", "The", "value", "is", "clamped", "to", "zero", "and", "the", "maximum", "bucket", "value", ".", "Returns", "itself", "to", "allow", "for", "chaining", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/buckets.go#L57-L64
train
tylertreat/BoomFilters
buckets.go
Get
func (b *Buckets) Get(bucket uint) uint32 { return b.getBits(bucket*uint(b.bucketSize), uint(b.bucketSize)) }
go
func (b *Buckets) Get(bucket uint) uint32 { return b.getBits(bucket*uint(b.bucketSize), uint(b.bucketSize)) }
[ "func", "(", "b", "*", "Buckets", ")", "Get", "(", "bucket", "uint", ")", "uint32", "{", "return", "b", ".", "getBits", "(", "bucket", "*", "uint", "(", "b", ".", "bucketSize", ")", ",", "uint", "(", "b", ".", "bucketSize", ")", ")", "\n", "}" ]
// Get returns the value in the specified bucket.
[ "Get", "returns", "the", "value", "in", "the", "specified", "bucket", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/buckets.go#L67-L69
train
tylertreat/BoomFilters
buckets.go
Reset
func (b *Buckets) Reset() *Buckets { b.data = make([]byte, (b.count*uint(b.bucketSize)+7)/8) return b }
go
func (b *Buckets) Reset() *Buckets { b.data = make([]byte, (b.count*uint(b.bucketSize)+7)/8) return b }
[ "func", "(", "b", "*", "Buckets", ")", "Reset", "(", ")", "*", "Buckets", "{", "b", ".", "data", "=", "make", "(", "[", "]", "byte", ",", "(", "b", ".", "count", "*", "uint", "(", "b", ".", "bucketSize", ")", "+", "7", ")", "/", "8", ")", "\n", "return", "b", "\n", "}" ]
// Reset restores the Buckets to the original state. Returns itself to allow // for chaining.
[ "Reset", "restores", "the", "Buckets", "to", "the", "original", "state", ".", "Returns", "itself", "to", "allow", "for", "chaining", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/buckets.go#L73-L76
train
tylertreat/BoomFilters
buckets.go
getBits
func (b *Buckets) getBits(offset, length uint) uint32 { byteIndex := offset / 8 byteOffset := offset % 8 if byteOffset+length > 8 { rem := 8 - byteOffset return b.getBits(offset, rem) | (b.getBits(offset+rem, length-rem) << rem) } bitMask := uint32((1 << length) - 1) return (uint32(b.data[byteIndex]) & (bitMask << byteOffset)) >> byteOffset }
go
func (b *Buckets) getBits(offset, length uint) uint32 { byteIndex := offset / 8 byteOffset := offset % 8 if byteOffset+length > 8 { rem := 8 - byteOffset return b.getBits(offset, rem) | (b.getBits(offset+rem, length-rem) << rem) } bitMask := uint32((1 << length) - 1) return (uint32(b.data[byteIndex]) & (bitMask << byteOffset)) >> byteOffset }
[ "func", "(", "b", "*", "Buckets", ")", "getBits", "(", "offset", ",", "length", "uint", ")", "uint32", "{", "byteIndex", ":=", "offset", "/", "8", "\n", "byteOffset", ":=", "offset", "%", "8", "\n", "if", "byteOffset", "+", "length", ">", "8", "{", "rem", ":=", "8", "-", "byteOffset", "\n", "return", "b", ".", "getBits", "(", "offset", ",", "rem", ")", "|", "(", "b", ".", "getBits", "(", "offset", "+", "rem", ",", "length", "-", "rem", ")", "<<", "rem", ")", "\n", "}", "\n", "bitMask", ":=", "uint32", "(", "(", "1", "<<", "length", ")", "-", "1", ")", "\n", "return", "(", "uint32", "(", "b", ".", "data", "[", "byteIndex", "]", ")", "&", "(", "bitMask", "<<", "byteOffset", ")", ")", ">>", "byteOffset", "\n", "}" ]
// getBits returns the bits at the specified offset and length.
[ "getBits", "returns", "the", "bits", "at", "the", "specified", "offset", "and", "length", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/buckets.go#L79-L88
train
tylertreat/BoomFilters
buckets.go
setBits
func (b *Buckets) setBits(offset, length, bits uint32) { byteIndex := offset / 8 byteOffset := offset % 8 if byteOffset+length > 8 { rem := 8 - byteOffset b.setBits(offset, rem, bits) b.setBits(offset+rem, length-rem, bits>>rem) return } bitMask := uint32((1 << length) - 1) b.data[byteIndex] = byte(uint32(b.data[byteIndex]) & ^(bitMask << byteOffset)) b.data[byteIndex] = byte(uint32(b.data[byteIndex]) | ((bits & bitMask) << byteOffset)) }
go
func (b *Buckets) setBits(offset, length, bits uint32) { byteIndex := offset / 8 byteOffset := offset % 8 if byteOffset+length > 8 { rem := 8 - byteOffset b.setBits(offset, rem, bits) b.setBits(offset+rem, length-rem, bits>>rem) return } bitMask := uint32((1 << length) - 1) b.data[byteIndex] = byte(uint32(b.data[byteIndex]) & ^(bitMask << byteOffset)) b.data[byteIndex] = byte(uint32(b.data[byteIndex]) | ((bits & bitMask) << byteOffset)) }
[ "func", "(", "b", "*", "Buckets", ")", "setBits", "(", "offset", ",", "length", ",", "bits", "uint32", ")", "{", "byteIndex", ":=", "offset", "/", "8", "\n", "byteOffset", ":=", "offset", "%", "8", "\n", "if", "byteOffset", "+", "length", ">", "8", "{", "rem", ":=", "8", "-", "byteOffset", "\n", "b", ".", "setBits", "(", "offset", ",", "rem", ",", "bits", ")", "\n", "b", ".", "setBits", "(", "offset", "+", "rem", ",", "length", "-", "rem", ",", "bits", ">>", "rem", ")", "\n", "return", "\n", "}", "\n", "bitMask", ":=", "uint32", "(", "(", "1", "<<", "length", ")", "-", "1", ")", "\n", "b", ".", "data", "[", "byteIndex", "]", "=", "byte", "(", "uint32", "(", "b", ".", "data", "[", "byteIndex", "]", ")", "&", "^", "(", "bitMask", "<<", "byteOffset", ")", ")", "\n", "b", ".", "data", "[", "byteIndex", "]", "=", "byte", "(", "uint32", "(", "b", ".", "data", "[", "byteIndex", "]", ")", "|", "(", "(", "bits", "&", "bitMask", ")", "<<", "byteOffset", ")", ")", "\n", "}" ]
// setBits sets bits at the specified offset and length.
[ "setBits", "sets", "bits", "at", "the", "specified", "offset", "and", "length", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/buckets.go#L91-L103
train
tylertreat/BoomFilters
stable.go
NewStableBloomFilter
func NewStableBloomFilter(m uint, d uint8, fpRate float64) *StableBloomFilter { k := OptimalK(fpRate) / 2 if k > m { k = m } else if k <= 0 { k = 1 } cells := NewBuckets(m, d) return &StableBloomFilter{ hash: fnv.New64(), m: m, k: k, p: optimalStableP(m, k, d, fpRate), max: cells.MaxBucketValue(), cells: cells, indexBuffer: make([]uint, k), } }
go
func NewStableBloomFilter(m uint, d uint8, fpRate float64) *StableBloomFilter { k := OptimalK(fpRate) / 2 if k > m { k = m } else if k <= 0 { k = 1 } cells := NewBuckets(m, d) return &StableBloomFilter{ hash: fnv.New64(), m: m, k: k, p: optimalStableP(m, k, d, fpRate), max: cells.MaxBucketValue(), cells: cells, indexBuffer: make([]uint, k), } }
[ "func", "NewStableBloomFilter", "(", "m", "uint", ",", "d", "uint8", ",", "fpRate", "float64", ")", "*", "StableBloomFilter", "{", "k", ":=", "OptimalK", "(", "fpRate", ")", "/", "2", "\n", "if", "k", ">", "m", "{", "k", "=", "m", "\n", "}", "else", "if", "k", "<=", "0", "{", "k", "=", "1", "\n", "}", "\n\n", "cells", ":=", "NewBuckets", "(", "m", ",", "d", ")", "\n\n", "return", "&", "StableBloomFilter", "{", "hash", ":", "fnv", ".", "New64", "(", ")", ",", "m", ":", "m", ",", "k", ":", "k", ",", "p", ":", "optimalStableP", "(", "m", ",", "k", ",", "d", ",", "fpRate", ")", ",", "max", ":", "cells", ".", "MaxBucketValue", "(", ")", ",", "cells", ":", "cells", ",", "indexBuffer", ":", "make", "(", "[", "]", "uint", ",", "k", ")", ",", "}", "\n", "}" ]
// NewStableBloomFilter creates a new Stable Bloom Filter with m cells and d // bits allocated per cell optimized for the target false-positive rate. Use // NewDefaultStableFilter if you don't want to calculate d.
[ "NewStableBloomFilter", "creates", "a", "new", "Stable", "Bloom", "Filter", "with", "m", "cells", "and", "d", "bits", "allocated", "per", "cell", "optimized", "for", "the", "target", "false", "-", "positive", "rate", ".", "Use", "NewDefaultStableFilter", "if", "you", "don", "t", "want", "to", "calculate", "d", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/stable.go#L49-L68
train
tylertreat/BoomFilters
stable.go
NewUnstableBloomFilter
func NewUnstableBloomFilter(m uint, fpRate float64) *StableBloomFilter { var ( cells = NewBuckets(m, 1) k = OptimalK(fpRate) ) return &StableBloomFilter{ hash: fnv.New64(), m: m, k: k, p: 0, max: cells.MaxBucketValue(), cells: cells, indexBuffer: make([]uint, k), } }
go
func NewUnstableBloomFilter(m uint, fpRate float64) *StableBloomFilter { var ( cells = NewBuckets(m, 1) k = OptimalK(fpRate) ) return &StableBloomFilter{ hash: fnv.New64(), m: m, k: k, p: 0, max: cells.MaxBucketValue(), cells: cells, indexBuffer: make([]uint, k), } }
[ "func", "NewUnstableBloomFilter", "(", "m", "uint", ",", "fpRate", "float64", ")", "*", "StableBloomFilter", "{", "var", "(", "cells", "=", "NewBuckets", "(", "m", ",", "1", ")", "\n", "k", "=", "OptimalK", "(", "fpRate", ")", "\n", ")", "\n\n", "return", "&", "StableBloomFilter", "{", "hash", ":", "fnv", ".", "New64", "(", ")", ",", "m", ":", "m", ",", "k", ":", "k", ",", "p", ":", "0", ",", "max", ":", "cells", ".", "MaxBucketValue", "(", ")", ",", "cells", ":", "cells", ",", "indexBuffer", ":", "make", "(", "[", "]", "uint", ",", "k", ")", ",", "}", "\n", "}" ]
// NewUnstableBloomFilter creates a new special case of Stable Bloom Filter // which is a traditional Bloom filter with m bits and an optimal number of // hash functions for the target false-positive rate. Unlike the stable // variant, data is not evicted and a cell contains a maximum of 1 hash value.
[ "NewUnstableBloomFilter", "creates", "a", "new", "special", "case", "of", "Stable", "Bloom", "Filter", "which", "is", "a", "traditional", "Bloom", "filter", "with", "m", "bits", "and", "an", "optimal", "number", "of", "hash", "functions", "for", "the", "target", "false", "-", "positive", "rate", ".", "Unlike", "the", "stable", "variant", "data", "is", "not", "evicted", "and", "a", "cell", "contains", "a", "maximum", "of", "1", "hash", "value", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/stable.go#L82-L97
train
tylertreat/BoomFilters
stable.go
StablePoint
func (s *StableBloomFilter) StablePoint() float64 { var ( subDenom = float64(s.p) * (1/float64(s.k) - 1/float64(s.m)) denom = 1 + 1/subDenom base = 1 / denom ) return math.Pow(base, float64(s.max)) }
go
func (s *StableBloomFilter) StablePoint() float64 { var ( subDenom = float64(s.p) * (1/float64(s.k) - 1/float64(s.m)) denom = 1 + 1/subDenom base = 1 / denom ) return math.Pow(base, float64(s.max)) }
[ "func", "(", "s", "*", "StableBloomFilter", ")", "StablePoint", "(", ")", "float64", "{", "var", "(", "subDenom", "=", "float64", "(", "s", ".", "p", ")", "*", "(", "1", "/", "float64", "(", "s", ".", "k", ")", "-", "1", "/", "float64", "(", "s", ".", "m", ")", ")", "\n", "denom", "=", "1", "+", "1", "/", "subDenom", "\n", "base", "=", "1", "/", "denom", "\n", ")", "\n\n", "return", "math", ".", "Pow", "(", "base", ",", "float64", "(", "s", ".", "max", ")", ")", "\n", "}" ]
// StablePoint returns the limit of the expected fraction of zeros in the // Stable Bloom Filter when the number of iterations goes to infinity. When // this limit is reached, the Stable Bloom Filter is considered stable.
[ "StablePoint", "returns", "the", "limit", "of", "the", "expected", "fraction", "of", "zeros", "in", "the", "Stable", "Bloom", "Filter", "when", "the", "number", "of", "iterations", "goes", "to", "infinity", ".", "When", "this", "limit", "is", "reached", "the", "Stable", "Bloom", "Filter", "is", "considered", "stable", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/stable.go#L117-L125
train
tylertreat/BoomFilters
stable.go
FalsePositiveRate
func (s *StableBloomFilter) FalsePositiveRate() float64 { return math.Pow(1-s.StablePoint(), float64(s.k)) }
go
func (s *StableBloomFilter) FalsePositiveRate() float64 { return math.Pow(1-s.StablePoint(), float64(s.k)) }
[ "func", "(", "s", "*", "StableBloomFilter", ")", "FalsePositiveRate", "(", ")", "float64", "{", "return", "math", ".", "Pow", "(", "1", "-", "s", ".", "StablePoint", "(", ")", ",", "float64", "(", "s", ".", "k", ")", ")", "\n", "}" ]
// FalsePositiveRate returns the upper bound on false positives when the filter // has become stable.
[ "FalsePositiveRate", "returns", "the", "upper", "bound", "on", "false", "positives", "when", "the", "filter", "has", "become", "stable", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/stable.go#L129-L131
train
tylertreat/BoomFilters
stable.go
Add
func (s *StableBloomFilter) Add(data []byte) Filter { // Randomly decrement p cells to make room for new elements. s.decrement() lower, upper := hashKernel(data, s.hash) // Set the K cells to max. for i := uint(0); i < s.k; i++ { s.cells.Set((uint(lower)+uint(upper)*i)%s.m, s.max) } return s }
go
func (s *StableBloomFilter) Add(data []byte) Filter { // Randomly decrement p cells to make room for new elements. s.decrement() lower, upper := hashKernel(data, s.hash) // Set the K cells to max. for i := uint(0); i < s.k; i++ { s.cells.Set((uint(lower)+uint(upper)*i)%s.m, s.max) } return s }
[ "func", "(", "s", "*", "StableBloomFilter", ")", "Add", "(", "data", "[", "]", "byte", ")", "Filter", "{", "// Randomly decrement p cells to make room for new elements.", "s", ".", "decrement", "(", ")", "\n\n", "lower", ",", "upper", ":=", "hashKernel", "(", "data", ",", "s", ".", "hash", ")", "\n\n", "// Set the K cells to max.", "for", "i", ":=", "uint", "(", "0", ")", ";", "i", "<", "s", ".", "k", ";", "i", "++", "{", "s", ".", "cells", ".", "Set", "(", "(", "uint", "(", "lower", ")", "+", "uint", "(", "upper", ")", "*", "i", ")", "%", "s", ".", "m", ",", "s", ".", "max", ")", "\n", "}", "\n\n", "return", "s", "\n", "}" ]
// Add will add the data to the Stable Bloom Filter. It returns the filter to // allow for chaining.
[ "Add", "will", "add", "the", "data", "to", "the", "Stable", "Bloom", "Filter", ".", "It", "returns", "the", "filter", "to", "allow", "for", "chaining", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/stable.go#L151-L163
train
tylertreat/BoomFilters
stable.go
optimalStableP
func optimalStableP(m, k uint, d uint8, fpRate float64) uint { var ( max = math.Pow(2, float64(d)) - 1 subDenom = math.Pow(1-math.Pow(fpRate, 1/float64(k)), 1/max) denom = (1/subDenom - 1) * (1/float64(k) - 1/float64(m)) ) p := uint(1 / denom) if p <= 0 { p = 1 } return p }
go
func optimalStableP(m, k uint, d uint8, fpRate float64) uint { var ( max = math.Pow(2, float64(d)) - 1 subDenom = math.Pow(1-math.Pow(fpRate, 1/float64(k)), 1/max) denom = (1/subDenom - 1) * (1/float64(k) - 1/float64(m)) ) p := uint(1 / denom) if p <= 0 { p = 1 } return p }
[ "func", "optimalStableP", "(", "m", ",", "k", "uint", ",", "d", "uint8", ",", "fpRate", "float64", ")", "uint", "{", "var", "(", "max", "=", "math", ".", "Pow", "(", "2", ",", "float64", "(", "d", ")", ")", "-", "1", "\n", "subDenom", "=", "math", ".", "Pow", "(", "1", "-", "math", ".", "Pow", "(", "fpRate", ",", "1", "/", "float64", "(", "k", ")", ")", ",", "1", "/", "max", ")", "\n", "denom", "=", "(", "1", "/", "subDenom", "-", "1", ")", "*", "(", "1", "/", "float64", "(", "k", ")", "-", "1", "/", "float64", "(", "m", ")", ")", "\n", ")", "\n\n", "p", ":=", "uint", "(", "1", "/", "denom", ")", "\n", "if", "p", "<=", "0", "{", "p", "=", "1", "\n", "}", "\n\n", "return", "p", "\n", "}" ]
// optimalStableP returns the optimal number of cells to decrement, p, per // iteration for the provided parameters of an SBF.
[ "optimalStableP", "returns", "the", "optimal", "number", "of", "cells", "to", "decrement", "p", "per", "iteration", "for", "the", "provided", "parameters", "of", "an", "SBF", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/stable.go#L320-L333
train
tylertreat/BoomFilters
scalable.go
NewScalableBloomFilter
func NewScalableBloomFilter(hint uint, fpRate, r float64) *ScalableBloomFilter { s := &ScalableBloomFilter{ filters: make([]*PartitionedBloomFilter, 0, 1), r: r, fp: fpRate, p: fillRatio, hint: hint, } s.addFilter() return s }
go
func NewScalableBloomFilter(hint uint, fpRate, r float64) *ScalableBloomFilter { s := &ScalableBloomFilter{ filters: make([]*PartitionedBloomFilter, 0, 1), r: r, fp: fpRate, p: fillRatio, hint: hint, } s.addFilter() return s }
[ "func", "NewScalableBloomFilter", "(", "hint", "uint", ",", "fpRate", ",", "r", "float64", ")", "*", "ScalableBloomFilter", "{", "s", ":=", "&", "ScalableBloomFilter", "{", "filters", ":", "make", "(", "[", "]", "*", "PartitionedBloomFilter", ",", "0", ",", "1", ")", ",", "r", ":", "r", ",", "fp", ":", "fpRate", ",", "p", ":", "fillRatio", ",", "hint", ":", "hint", ",", "}", "\n\n", "s", ".", "addFilter", "(", ")", "\n", "return", "s", "\n", "}" ]
// NewScalableBloomFilter creates a new Scalable Bloom Filter with the // specified target false-positive rate and tightening ratio. Use // NewDefaultScalableBloomFilter if you don't want to calculate these // parameters.
[ "NewScalableBloomFilter", "creates", "a", "new", "Scalable", "Bloom", "Filter", "with", "the", "specified", "target", "false", "-", "positive", "rate", "and", "tightening", "ratio", ".", "Use", "NewDefaultScalableBloomFilter", "if", "you", "don", "t", "want", "to", "calculate", "these", "parameters", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/scalable.go#L54-L65
train
tylertreat/BoomFilters
scalable.go
Capacity
func (s *ScalableBloomFilter) Capacity() uint { capacity := uint(0) for _, bf := range s.filters { capacity += bf.Capacity() } return capacity }
go
func (s *ScalableBloomFilter) Capacity() uint { capacity := uint(0) for _, bf := range s.filters { capacity += bf.Capacity() } return capacity }
[ "func", "(", "s", "*", "ScalableBloomFilter", ")", "Capacity", "(", ")", "uint", "{", "capacity", ":=", "uint", "(", "0", ")", "\n", "for", "_", ",", "bf", ":=", "range", "s", ".", "filters", "{", "capacity", "+=", "bf", ".", "Capacity", "(", ")", "\n", "}", "\n", "return", "capacity", "\n", "}" ]
// Capacity returns the current Scalable Bloom Filter capacity, which is the // sum of the capacities for the contained series of Bloom filters.
[ "Capacity", "returns", "the", "current", "Scalable", "Bloom", "Filter", "capacity", "which", "is", "the", "sum", "of", "the", "capacities", "for", "the", "contained", "series", "of", "Bloom", "filters", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/scalable.go#L75-L81
train
tylertreat/BoomFilters
scalable.go
FillRatio
func (s *ScalableBloomFilter) FillRatio() float64 { sum := 0.0 for _, filter := range s.filters { sum += filter.FillRatio() } return sum / float64(len(s.filters)) }
go
func (s *ScalableBloomFilter) FillRatio() float64 { sum := 0.0 for _, filter := range s.filters { sum += filter.FillRatio() } return sum / float64(len(s.filters)) }
[ "func", "(", "s", "*", "ScalableBloomFilter", ")", "FillRatio", "(", ")", "float64", "{", "sum", ":=", "0.0", "\n", "for", "_", ",", "filter", ":=", "range", "s", ".", "filters", "{", "sum", "+=", "filter", ".", "FillRatio", "(", ")", "\n", "}", "\n", "return", "sum", "/", "float64", "(", "len", "(", "s", ".", "filters", ")", ")", "\n", "}" ]
// FillRatio returns the average ratio of set bits across every filter.
[ "FillRatio", "returns", "the", "average", "ratio", "of", "set", "bits", "across", "every", "filter", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/scalable.go#L90-L96
train
tylertreat/BoomFilters
scalable.go
addFilter
func (s *ScalableBloomFilter) addFilter() { fpRate := s.fp * math.Pow(s.r, float64(len(s.filters))) p := NewPartitionedBloomFilter(s.hint, fpRate) if len(s.filters) > 0 { p.SetHash(s.filters[0].hash) } s.filters = append(s.filters, p) }
go
func (s *ScalableBloomFilter) addFilter() { fpRate := s.fp * math.Pow(s.r, float64(len(s.filters))) p := NewPartitionedBloomFilter(s.hint, fpRate) if len(s.filters) > 0 { p.SetHash(s.filters[0].hash) } s.filters = append(s.filters, p) }
[ "func", "(", "s", "*", "ScalableBloomFilter", ")", "addFilter", "(", ")", "{", "fpRate", ":=", "s", ".", "fp", "*", "math", ".", "Pow", "(", "s", ".", "r", ",", "float64", "(", "len", "(", "s", ".", "filters", ")", ")", ")", "\n", "p", ":=", "NewPartitionedBloomFilter", "(", "s", ".", "hint", ",", "fpRate", ")", "\n", "if", "len", "(", "s", ".", "filters", ")", ">", "0", "{", "p", ".", "SetHash", "(", "s", ".", "filters", "[", "0", "]", ".", "hash", ")", "\n", "}", "\n", "s", ".", "filters", "=", "append", "(", "s", ".", "filters", ",", "p", ")", "\n", "}" ]
// addFilter adds a new Bloom filter with a restricted false-positive rate to // the Scalable Bloom Filter
[ "addFilter", "adds", "a", "new", "Bloom", "filter", "with", "a", "restricted", "false", "-", "positive", "rate", "to", "the", "Scalable", "Bloom", "Filter" ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/scalable.go#L146-L153
train
tylertreat/BoomFilters
hyperloglog.go
NewHyperLogLog
func NewHyperLogLog(m uint) (*HyperLogLog, error) { if (m & (m - 1)) != 0 { return nil, errors.New("m must be a power of two") } return &HyperLogLog{ registers: make([]uint8, m), m: m, b: uint32(math.Ceil(math.Log2(float64(m)))), alpha: calculateAlpha(m), hash: fnv.New32(), }, nil }
go
func NewHyperLogLog(m uint) (*HyperLogLog, error) { if (m & (m - 1)) != 0 { return nil, errors.New("m must be a power of two") } return &HyperLogLog{ registers: make([]uint8, m), m: m, b: uint32(math.Ceil(math.Log2(float64(m)))), alpha: calculateAlpha(m), hash: fnv.New32(), }, nil }
[ "func", "NewHyperLogLog", "(", "m", "uint", ")", "(", "*", "HyperLogLog", ",", "error", ")", "{", "if", "(", "m", "&", "(", "m", "-", "1", ")", ")", "!=", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "HyperLogLog", "{", "registers", ":", "make", "(", "[", "]", "uint8", ",", "m", ")", ",", "m", ":", "m", ",", "b", ":", "uint32", "(", "math", ".", "Ceil", "(", "math", ".", "Log2", "(", "float64", "(", "m", ")", ")", ")", ")", ",", "alpha", ":", "calculateAlpha", "(", "m", ")", ",", "hash", ":", "fnv", ".", "New32", "(", ")", ",", "}", ",", "nil", "\n", "}" ]
// NewHyperLogLog creates a new HyperLogLog with m registers. Returns an error // if m isn't a power of two.
[ "NewHyperLogLog", "creates", "a", "new", "HyperLogLog", "with", "m", "registers", ".", "Returns", "an", "error", "if", "m", "isn", "t", "a", "power", "of", "two", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/hyperloglog.go#L61-L73
train
tylertreat/BoomFilters
hyperloglog.go
NewDefaultHyperLogLog
func NewDefaultHyperLogLog(e float64) (*HyperLogLog, error) { m := math.Pow(1.04/e, 2) return NewHyperLogLog(uint(math.Pow(2, math.Ceil(math.Log2(m))))) }
go
func NewDefaultHyperLogLog(e float64) (*HyperLogLog, error) { m := math.Pow(1.04/e, 2) return NewHyperLogLog(uint(math.Pow(2, math.Ceil(math.Log2(m))))) }
[ "func", "NewDefaultHyperLogLog", "(", "e", "float64", ")", "(", "*", "HyperLogLog", ",", "error", ")", "{", "m", ":=", "math", ".", "Pow", "(", "1.04", "/", "e", ",", "2", ")", "\n", "return", "NewHyperLogLog", "(", "uint", "(", "math", ".", "Pow", "(", "2", ",", "math", ".", "Ceil", "(", "math", ".", "Log2", "(", "m", ")", ")", ")", ")", ")", "\n", "}" ]
// NewDefaultHyperLogLog creates a new HyperLogLog optimized for the specified // standard error. Returns an error if the number of registers can't be // calculated for the provided accuracy.
[ "NewDefaultHyperLogLog", "creates", "a", "new", "HyperLogLog", "optimized", "for", "the", "specified", "standard", "error", ".", "Returns", "an", "error", "if", "the", "number", "of", "registers", "can", "t", "be", "calculated", "for", "the", "provided", "accuracy", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/hyperloglog.go#L78-L81
train
tylertreat/BoomFilters
hyperloglog.go
Add
func (h *HyperLogLog) Add(data []byte) *HyperLogLog { var ( hash = h.calculateHash(data) k = 32 - h.b r = calculateRho(hash<<h.b, k) j = hash >> uint(k) ) if r > h.registers[j] { h.registers[j] = r } return h }
go
func (h *HyperLogLog) Add(data []byte) *HyperLogLog { var ( hash = h.calculateHash(data) k = 32 - h.b r = calculateRho(hash<<h.b, k) j = hash >> uint(k) ) if r > h.registers[j] { h.registers[j] = r } return h }
[ "func", "(", "h", "*", "HyperLogLog", ")", "Add", "(", "data", "[", "]", "byte", ")", "*", "HyperLogLog", "{", "var", "(", "hash", "=", "h", ".", "calculateHash", "(", "data", ")", "\n", "k", "=", "32", "-", "h", ".", "b", "\n", "r", "=", "calculateRho", "(", "hash", "<<", "h", ".", "b", ",", "k", ")", "\n", "j", "=", "hash", ">>", "uint", "(", "k", ")", "\n", ")", "\n\n", "if", "r", ">", "h", ".", "registers", "[", "j", "]", "{", "h", ".", "registers", "[", "j", "]", "=", "r", "\n", "}", "\n\n", "return", "h", "\n", "}" ]
// Add will add the data to the set. Returns the HyperLogLog to allow for // chaining.
[ "Add", "will", "add", "the", "data", "to", "the", "set", ".", "Returns", "the", "HyperLogLog", "to", "allow", "for", "chaining", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/hyperloglog.go#L85-L98
train
tylertreat/BoomFilters
hyperloglog.go
Count
func (h *HyperLogLog) Count() uint64 { sum := 0.0 m := float64(h.m) for _, val := range h.registers { sum += 1.0 / math.Pow(2.0, float64(val)) } estimate := h.alpha * m * m / sum if estimate <= 5.0/2.0*m { // Small range correction v := 0 for _, r := range h.registers { if r == 0 { v++ } } if v > 0 { estimate = m * math.Log(m/float64(v)) } } else if estimate > 1.0/30.0*exp32 { // Large range correction estimate = -exp32 * math.Log(1-estimate/exp32) } return uint64(estimate) }
go
func (h *HyperLogLog) Count() uint64 { sum := 0.0 m := float64(h.m) for _, val := range h.registers { sum += 1.0 / math.Pow(2.0, float64(val)) } estimate := h.alpha * m * m / sum if estimate <= 5.0/2.0*m { // Small range correction v := 0 for _, r := range h.registers { if r == 0 { v++ } } if v > 0 { estimate = m * math.Log(m/float64(v)) } } else if estimate > 1.0/30.0*exp32 { // Large range correction estimate = -exp32 * math.Log(1-estimate/exp32) } return uint64(estimate) }
[ "func", "(", "h", "*", "HyperLogLog", ")", "Count", "(", ")", "uint64", "{", "sum", ":=", "0.0", "\n", "m", ":=", "float64", "(", "h", ".", "m", ")", "\n", "for", "_", ",", "val", ":=", "range", "h", ".", "registers", "{", "sum", "+=", "1.0", "/", "math", ".", "Pow", "(", "2.0", ",", "float64", "(", "val", ")", ")", "\n", "}", "\n", "estimate", ":=", "h", ".", "alpha", "*", "m", "*", "m", "/", "sum", "\n", "if", "estimate", "<=", "5.0", "/", "2.0", "*", "m", "{", "// Small range correction", "v", ":=", "0", "\n", "for", "_", ",", "r", ":=", "range", "h", ".", "registers", "{", "if", "r", "==", "0", "{", "v", "++", "\n", "}", "\n", "}", "\n", "if", "v", ">", "0", "{", "estimate", "=", "m", "*", "math", ".", "Log", "(", "m", "/", "float64", "(", "v", ")", ")", "\n", "}", "\n", "}", "else", "if", "estimate", ">", "1.0", "/", "30.0", "*", "exp32", "{", "// Large range correction", "estimate", "=", "-", "exp32", "*", "math", ".", "Log", "(", "1", "-", "estimate", "/", "exp32", ")", "\n", "}", "\n", "return", "uint64", "(", "estimate", ")", "\n", "}" ]
// Count returns the approximated cardinality of the set.
[ "Count", "returns", "the", "approximated", "cardinality", "of", "the", "set", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/hyperloglog.go#L101-L124
train
tylertreat/BoomFilters
hyperloglog.go
Merge
func (h *HyperLogLog) Merge(other *HyperLogLog) error { if h.m != other.m { return errors.New("number of registers must match") } for j, r := range other.registers { if r > h.registers[j] { h.registers[j] = r } } return nil }
go
func (h *HyperLogLog) Merge(other *HyperLogLog) error { if h.m != other.m { return errors.New("number of registers must match") } for j, r := range other.registers { if r > h.registers[j] { h.registers[j] = r } } return nil }
[ "func", "(", "h", "*", "HyperLogLog", ")", "Merge", "(", "other", "*", "HyperLogLog", ")", "error", "{", "if", "h", ".", "m", "!=", "other", ".", "m", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "for", "j", ",", "r", ":=", "range", "other", ".", "registers", "{", "if", "r", ">", "h", ".", "registers", "[", "j", "]", "{", "h", ".", "registers", "[", "j", "]", "=", "r", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Merge combines this HyperLogLog with another. Returns an error if the number // of registers in the two HyperLogLogs are not equal.
[ "Merge", "combines", "this", "HyperLogLog", "with", "another", ".", "Returns", "an", "error", "if", "the", "number", "of", "registers", "in", "the", "two", "HyperLogLogs", "are", "not", "equal", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/hyperloglog.go#L128-L140
train
tylertreat/BoomFilters
hyperloglog.go
Reset
func (h *HyperLogLog) Reset() *HyperLogLog { h.registers = make([]uint8, h.m) return h }
go
func (h *HyperLogLog) Reset() *HyperLogLog { h.registers = make([]uint8, h.m) return h }
[ "func", "(", "h", "*", "HyperLogLog", ")", "Reset", "(", ")", "*", "HyperLogLog", "{", "h", ".", "registers", "=", "make", "(", "[", "]", "uint8", ",", "h", ".", "m", ")", "\n", "return", "h", "\n", "}" ]
// Reset restores the HyperLogLog to its original state. It returns itself to // allow for chaining.
[ "Reset", "restores", "the", "HyperLogLog", "to", "its", "original", "state", ".", "It", "returns", "itself", "to", "allow", "for", "chaining", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/hyperloglog.go#L144-L147
train
tylertreat/BoomFilters
hyperloglog.go
calculateHash
func (h *HyperLogLog) calculateHash(data []byte) uint32 { h.hash.Write(data) sum := h.hash.Sum32() h.hash.Reset() return sum }
go
func (h *HyperLogLog) calculateHash(data []byte) uint32 { h.hash.Write(data) sum := h.hash.Sum32() h.hash.Reset() return sum }
[ "func", "(", "h", "*", "HyperLogLog", ")", "calculateHash", "(", "data", "[", "]", "byte", ")", "uint32", "{", "h", ".", "hash", ".", "Write", "(", "data", ")", "\n", "sum", ":=", "h", ".", "hash", ".", "Sum32", "(", ")", "\n", "h", ".", "hash", ".", "Reset", "(", ")", "\n", "return", "sum", "\n", "}" ]
// calculateHash calculates the 32-bit hash value for the provided data.
[ "calculateHash", "calculates", "the", "32", "-", "bit", "hash", "value", "for", "the", "provided", "data", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/hyperloglog.go#L150-L155
train
tylertreat/BoomFilters
hyperloglog.go
calculateAlpha
func calculateAlpha(m uint) (result float64) { switch m { case 16: result = 0.673 case 32: result = 0.697 case 64: result = 0.709 default: result = 0.7213 / (1.0 + 1.079/float64(m)) } return result }
go
func calculateAlpha(m uint) (result float64) { switch m { case 16: result = 0.673 case 32: result = 0.697 case 64: result = 0.709 default: result = 0.7213 / (1.0 + 1.079/float64(m)) } return result }
[ "func", "calculateAlpha", "(", "m", "uint", ")", "(", "result", "float64", ")", "{", "switch", "m", "{", "case", "16", ":", "result", "=", "0.673", "\n", "case", "32", ":", "result", "=", "0.697", "\n", "case", "64", ":", "result", "=", "0.709", "\n", "default", ":", "result", "=", "0.7213", "/", "(", "1.0", "+", "1.079", "/", "float64", "(", "m", ")", ")", "\n", "}", "\n", "return", "result", "\n", "}" ]
// calculateAlpha calculates the bias-correction constant alpha based on the // number of registers, m.
[ "calculateAlpha", "calculates", "the", "bias", "-", "correction", "constant", "alpha", "based", "on", "the", "number", "of", "registers", "m", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/hyperloglog.go#L164-L176
train
tylertreat/BoomFilters
hyperloglog.go
calculateRho
func calculateRho(val, max uint32) uint8 { r := uint32(1) for val&0x80000000 == 0 && r <= max { r++ val <<= 1 } return uint8(r) }
go
func calculateRho(val, max uint32) uint8 { r := uint32(1) for val&0x80000000 == 0 && r <= max { r++ val <<= 1 } return uint8(r) }
[ "func", "calculateRho", "(", "val", ",", "max", "uint32", ")", "uint8", "{", "r", ":=", "uint32", "(", "1", ")", "\n", "for", "val", "&", "0x80000000", "==", "0", "&&", "r", "<=", "max", "{", "r", "++", "\n", "val", "<<=", "1", "\n", "}", "\n", "return", "uint8", "(", "r", ")", "\n", "}" ]
// calculateRho calculates the position of the leftmost 1-bit.
[ "calculateRho", "calculates", "the", "position", "of", "the", "leftmost", "1", "-", "bit", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/hyperloglog.go#L179-L186
train
tylertreat/BoomFilters
hyperloglog.go
WriteDataTo
func (h *HyperLogLog) WriteDataTo(stream io.Writer) (n int, err error) { buf := new(bytes.Buffer) // write register number first err = binary.Write(buf, binary.LittleEndian, uint64(h.m)) if err != nil { return } err = binary.Write(buf, binary.LittleEndian, h.b) if err != nil { return } err = binary.Write(buf, binary.LittleEndian, h.alpha) if err != nil { return } err = binary.Write(buf, binary.LittleEndian, h.registers) if err != nil { return } n, err = stream.Write(buf.Bytes()) return }
go
func (h *HyperLogLog) WriteDataTo(stream io.Writer) (n int, err error) { buf := new(bytes.Buffer) // write register number first err = binary.Write(buf, binary.LittleEndian, uint64(h.m)) if err != nil { return } err = binary.Write(buf, binary.LittleEndian, h.b) if err != nil { return } err = binary.Write(buf, binary.LittleEndian, h.alpha) if err != nil { return } err = binary.Write(buf, binary.LittleEndian, h.registers) if err != nil { return } n, err = stream.Write(buf.Bytes()) return }
[ "func", "(", "h", "*", "HyperLogLog", ")", "WriteDataTo", "(", "stream", "io", ".", "Writer", ")", "(", "n", "int", ",", "err", "error", ")", "{", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "// write register number first", "err", "=", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "uint64", "(", "h", ".", "m", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "err", "=", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "h", ".", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "err", "=", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "h", ".", "alpha", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "err", "=", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "h", ".", "registers", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "n", ",", "err", "=", "stream", ".", "Write", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "return", "\n", "}" ]
// WriteDataTo writes a binary representation of the Hll data to // an io stream. It returns the number of bytes written and error
[ "WriteDataTo", "writes", "a", "binary", "representation", "of", "the", "Hll", "data", "to", "an", "io", "stream", ".", "It", "returns", "the", "number", "of", "bytes", "written", "and", "error" ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/hyperloglog.go#L190-L215
train
tylertreat/BoomFilters
boom.go
OptimalM
func OptimalM(n uint, fpRate float64) uint { return uint(math.Ceil(float64(n) / ((math.Log(fillRatio) * math.Log(1-fillRatio)) / math.Abs(math.Log(fpRate))))) }
go
func OptimalM(n uint, fpRate float64) uint { return uint(math.Ceil(float64(n) / ((math.Log(fillRatio) * math.Log(1-fillRatio)) / math.Abs(math.Log(fpRate))))) }
[ "func", "OptimalM", "(", "n", "uint", ",", "fpRate", "float64", ")", "uint", "{", "return", "uint", "(", "math", ".", "Ceil", "(", "float64", "(", "n", ")", "/", "(", "(", "math", ".", "Log", "(", "fillRatio", ")", "*", "math", ".", "Log", "(", "1", "-", "fillRatio", ")", ")", "/", "math", ".", "Abs", "(", "math", ".", "Log", "(", "fpRate", ")", ")", ")", ")", ")", "\n", "}" ]
// OptimalM calculates the optimal Bloom filter size, m, based on the number of // items and the desired rate of false positives.
[ "OptimalM", "calculates", "the", "optimal", "Bloom", "filter", "size", "m", "based", "on", "the", "number", "of", "items", "and", "the", "desired", "rate", "of", "false", "positives", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/boom.go#L65-L68
train
tylertreat/BoomFilters
boom.go
OptimalK
func OptimalK(fpRate float64) uint { return uint(math.Ceil(math.Log2(1 / fpRate))) }
go
func OptimalK(fpRate float64) uint { return uint(math.Ceil(math.Log2(1 / fpRate))) }
[ "func", "OptimalK", "(", "fpRate", "float64", ")", "uint", "{", "return", "uint", "(", "math", ".", "Ceil", "(", "math", ".", "Log2", "(", "1", "/", "fpRate", ")", ")", ")", "\n", "}" ]
// OptimalK calculates the optimal number of hash functions to use for a Bloom // filter based on the desired rate of false positives.
[ "OptimalK", "calculates", "the", "optimal", "number", "of", "hash", "functions", "to", "use", "for", "a", "Bloom", "filter", "based", "on", "the", "desired", "rate", "of", "false", "positives", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/boom.go#L72-L74
train
tylertreat/BoomFilters
boom.go
hashKernel
func hashKernel(data []byte, hash hash.Hash64) (uint32, uint32) { hash.Write(data) sum := hash.Sum(nil) hash.Reset() return binary.BigEndian.Uint32(sum[4:8]), binary.BigEndian.Uint32(sum[0:4]) }
go
func hashKernel(data []byte, hash hash.Hash64) (uint32, uint32) { hash.Write(data) sum := hash.Sum(nil) hash.Reset() return binary.BigEndian.Uint32(sum[4:8]), binary.BigEndian.Uint32(sum[0:4]) }
[ "func", "hashKernel", "(", "data", "[", "]", "byte", ",", "hash", "hash", ".", "Hash64", ")", "(", "uint32", ",", "uint32", ")", "{", "hash", ".", "Write", "(", "data", ")", "\n", "sum", ":=", "hash", ".", "Sum", "(", "nil", ")", "\n", "hash", ".", "Reset", "(", ")", "\n", "return", "binary", ".", "BigEndian", ".", "Uint32", "(", "sum", "[", "4", ":", "8", "]", ")", ",", "binary", ".", "BigEndian", ".", "Uint32", "(", "sum", "[", "0", ":", "4", "]", ")", "\n", "}" ]
// hashKernel returns the upper and lower base hash values from which the k // hashes are derived.
[ "hashKernel", "returns", "the", "upper", "and", "lower", "base", "hash", "values", "from", "which", "the", "k", "hashes", "are", "derived", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/boom.go#L78-L83
train
tylertreat/BoomFilters
partitioned.go
NewPartitionedBloomFilter
func NewPartitionedBloomFilter(n uint, fpRate float64) *PartitionedBloomFilter { var ( m = OptimalM(n, fpRate) k = OptimalK(fpRate) partitions = make([]*Buckets, k) s = uint(math.Ceil(float64(m) / float64(k))) ) for i := uint(0); i < k; i++ { partitions[i] = NewBuckets(s, 1) } return &PartitionedBloomFilter{ partitions: partitions, hash: fnv.New64(), m: m, k: k, s: s, } }
go
func NewPartitionedBloomFilter(n uint, fpRate float64) *PartitionedBloomFilter { var ( m = OptimalM(n, fpRate) k = OptimalK(fpRate) partitions = make([]*Buckets, k) s = uint(math.Ceil(float64(m) / float64(k))) ) for i := uint(0); i < k; i++ { partitions[i] = NewBuckets(s, 1) } return &PartitionedBloomFilter{ partitions: partitions, hash: fnv.New64(), m: m, k: k, s: s, } }
[ "func", "NewPartitionedBloomFilter", "(", "n", "uint", ",", "fpRate", "float64", ")", "*", "PartitionedBloomFilter", "{", "var", "(", "m", "=", "OptimalM", "(", "n", ",", "fpRate", ")", "\n", "k", "=", "OptimalK", "(", "fpRate", ")", "\n", "partitions", "=", "make", "(", "[", "]", "*", "Buckets", ",", "k", ")", "\n", "s", "=", "uint", "(", "math", ".", "Ceil", "(", "float64", "(", "m", ")", "/", "float64", "(", "k", ")", ")", ")", "\n", ")", "\n\n", "for", "i", ":=", "uint", "(", "0", ")", ";", "i", "<", "k", ";", "i", "++", "{", "partitions", "[", "i", "]", "=", "NewBuckets", "(", "s", ",", "1", ")", "\n", "}", "\n\n", "return", "&", "PartitionedBloomFilter", "{", "partitions", ":", "partitions", ",", "hash", ":", "fnv", ".", "New64", "(", ")", ",", "m", ":", "m", ",", "k", ":", "k", ",", "s", ":", "s", ",", "}", "\n", "}" ]
// NewPartitionedBloomFilter creates a new partitioned Bloom filter optimized // to store n items with a specified target false-positive rate.
[ "NewPartitionedBloomFilter", "creates", "a", "new", "partitioned", "Bloom", "filter", "optimized", "to", "store", "n", "items", "with", "a", "specified", "target", "false", "-", "positive", "rate", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/partitioned.go#L48-L67
train
tylertreat/BoomFilters
partitioned.go
FillRatio
func (p *PartitionedBloomFilter) FillRatio() float64 { t := float64(0) for i := uint(0); i < p.k; i++ { sum := uint32(0) for j := uint(0); j < p.partitions[i].Count(); j++ { sum += p.partitions[i].Get(j) } t += (float64(sum) / float64(p.s)) } return t / float64(p.k) }
go
func (p *PartitionedBloomFilter) FillRatio() float64 { t := float64(0) for i := uint(0); i < p.k; i++ { sum := uint32(0) for j := uint(0); j < p.partitions[i].Count(); j++ { sum += p.partitions[i].Get(j) } t += (float64(sum) / float64(p.s)) } return t / float64(p.k) }
[ "func", "(", "p", "*", "PartitionedBloomFilter", ")", "FillRatio", "(", ")", "float64", "{", "t", ":=", "float64", "(", "0", ")", "\n", "for", "i", ":=", "uint", "(", "0", ")", ";", "i", "<", "p", ".", "k", ";", "i", "++", "{", "sum", ":=", "uint32", "(", "0", ")", "\n", "for", "j", ":=", "uint", "(", "0", ")", ";", "j", "<", "p", ".", "partitions", "[", "i", "]", ".", "Count", "(", ")", ";", "j", "++", "{", "sum", "+=", "p", ".", "partitions", "[", "i", "]", ".", "Get", "(", "j", ")", "\n", "}", "\n", "t", "+=", "(", "float64", "(", "sum", ")", "/", "float64", "(", "p", ".", "s", ")", ")", "\n", "}", "\n", "return", "t", "/", "float64", "(", "p", ".", "k", ")", "\n", "}" ]
// FillRatio returns the average ratio of set bits across all partitions.
[ "FillRatio", "returns", "the", "average", "ratio", "of", "set", "bits", "across", "all", "partitions", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/partitioned.go#L90-L100
train
tylertreat/BoomFilters
classic.go
NewBloomFilter
func NewBloomFilter(n uint, fpRate float64) *BloomFilter { m := OptimalM(n, fpRate) return &BloomFilter{ buckets: NewBuckets(m, 1), hash: fnv.New64(), m: m, k: OptimalK(fpRate), } }
go
func NewBloomFilter(n uint, fpRate float64) *BloomFilter { m := OptimalM(n, fpRate) return &BloomFilter{ buckets: NewBuckets(m, 1), hash: fnv.New64(), m: m, k: OptimalK(fpRate), } }
[ "func", "NewBloomFilter", "(", "n", "uint", ",", "fpRate", "float64", ")", "*", "BloomFilter", "{", "m", ":=", "OptimalM", "(", "n", ",", "fpRate", ")", "\n", "return", "&", "BloomFilter", "{", "buckets", ":", "NewBuckets", "(", "m", ",", "1", ")", ",", "hash", ":", "fnv", ".", "New64", "(", ")", ",", "m", ":", "m", ",", "k", ":", "OptimalK", "(", "fpRate", ")", ",", "}", "\n", "}" ]
// NewBloomFilter creates a new Bloom filter optimized to store n items with a // specified target false-positive rate.
[ "NewBloomFilter", "creates", "a", "new", "Bloom", "filter", "optimized", "to", "store", "n", "items", "with", "a", "specified", "target", "false", "-", "positive", "rate", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/classic.go#L24-L32
train
tylertreat/BoomFilters
classic.go
FillRatio
func (b *BloomFilter) FillRatio() float64 { sum := uint32(0) for i := uint(0); i < b.buckets.Count(); i++ { sum += b.buckets.Get(i) } return float64(sum) / float64(b.m) }
go
func (b *BloomFilter) FillRatio() float64 { sum := uint32(0) for i := uint(0); i < b.buckets.Count(); i++ { sum += b.buckets.Get(i) } return float64(sum) / float64(b.m) }
[ "func", "(", "b", "*", "BloomFilter", ")", "FillRatio", "(", ")", "float64", "{", "sum", ":=", "uint32", "(", "0", ")", "\n", "for", "i", ":=", "uint", "(", "0", ")", ";", "i", "<", "b", ".", "buckets", ".", "Count", "(", ")", ";", "i", "++", "{", "sum", "+=", "b", ".", "buckets", ".", "Get", "(", "i", ")", "\n", "}", "\n", "return", "float64", "(", "sum", ")", "/", "float64", "(", "b", ".", "m", ")", "\n", "}" ]
// FillRatio returns the ratio of set bits.
[ "FillRatio", "returns", "the", "ratio", "of", "set", "bits", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/classic.go#L55-L61
train
howeyc/fsnotify
fsnotify_windows.go
NewWatcher
func NewWatcher() (*Watcher, error) { port, e := syscall.CreateIoCompletionPort(syscall.InvalidHandle, 0, 0, 0) if e != nil { return nil, os.NewSyscallError("CreateIoCompletionPort", e) } w := &Watcher{ port: port, watches: make(watchMap), fsnFlags: make(map[string]uint32), input: make(chan *input, 1), Event: make(chan *FileEvent, 50), internalEvent: make(chan *FileEvent), Error: make(chan error), quit: make(chan chan<- error, 1), } go w.readEvents() go w.purgeEvents() return w, nil }
go
func NewWatcher() (*Watcher, error) { port, e := syscall.CreateIoCompletionPort(syscall.InvalidHandle, 0, 0, 0) if e != nil { return nil, os.NewSyscallError("CreateIoCompletionPort", e) } w := &Watcher{ port: port, watches: make(watchMap), fsnFlags: make(map[string]uint32), input: make(chan *input, 1), Event: make(chan *FileEvent, 50), internalEvent: make(chan *FileEvent), Error: make(chan error), quit: make(chan chan<- error, 1), } go w.readEvents() go w.purgeEvents() return w, nil }
[ "func", "NewWatcher", "(", ")", "(", "*", "Watcher", ",", "error", ")", "{", "port", ",", "e", ":=", "syscall", ".", "CreateIoCompletionPort", "(", "syscall", ".", "InvalidHandle", ",", "0", ",", "0", ",", "0", ")", "\n", "if", "e", "!=", "nil", "{", "return", "nil", ",", "os", ".", "NewSyscallError", "(", "\"", "\"", ",", "e", ")", "\n", "}", "\n", "w", ":=", "&", "Watcher", "{", "port", ":", "port", ",", "watches", ":", "make", "(", "watchMap", ")", ",", "fsnFlags", ":", "make", "(", "map", "[", "string", "]", "uint32", ")", ",", "input", ":", "make", "(", "chan", "*", "input", ",", "1", ")", ",", "Event", ":", "make", "(", "chan", "*", "FileEvent", ",", "50", ")", ",", "internalEvent", ":", "make", "(", "chan", "*", "FileEvent", ")", ",", "Error", ":", "make", "(", "chan", "error", ")", ",", "quit", ":", "make", "(", "chan", "chan", "<-", "error", ",", "1", ")", ",", "}", "\n", "go", "w", ".", "readEvents", "(", ")", "\n", "go", "w", ".", "purgeEvents", "(", ")", "\n", "return", "w", ",", "nil", "\n", "}" ]
// NewWatcher creates and returns a Watcher.
[ "NewWatcher", "creates", "and", "returns", "a", "Watcher", "." ]
f0c08ee9c60704c1879025f2ae0ff3e000082c13
https://github.com/howeyc/fsnotify/blob/f0c08ee9c60704c1879025f2ae0ff3e000082c13/fsnotify_windows.go#L133-L151
train
howeyc/fsnotify
fsnotify.go
purgeEvents
func (w *Watcher) purgeEvents() { for ev := range w.internalEvent { sendEvent := false w.fsnmut.Lock() fsnFlags := w.fsnFlags[ev.Name] w.fsnmut.Unlock() if (fsnFlags&FSN_CREATE == FSN_CREATE) && ev.IsCreate() { sendEvent = true } if (fsnFlags&FSN_MODIFY == FSN_MODIFY) && ev.IsModify() { sendEvent = true } if (fsnFlags&FSN_DELETE == FSN_DELETE) && ev.IsDelete() { sendEvent = true } if (fsnFlags&FSN_RENAME == FSN_RENAME) && ev.IsRename() { sendEvent = true } if sendEvent { w.Event <- ev } // If there's no file, then no more events for user // BSD must keep watch for internal use (watches DELETEs to keep track // what files exist for create events) if ev.IsDelete() { w.fsnmut.Lock() delete(w.fsnFlags, ev.Name) w.fsnmut.Unlock() } } close(w.Event) }
go
func (w *Watcher) purgeEvents() { for ev := range w.internalEvent { sendEvent := false w.fsnmut.Lock() fsnFlags := w.fsnFlags[ev.Name] w.fsnmut.Unlock() if (fsnFlags&FSN_CREATE == FSN_CREATE) && ev.IsCreate() { sendEvent = true } if (fsnFlags&FSN_MODIFY == FSN_MODIFY) && ev.IsModify() { sendEvent = true } if (fsnFlags&FSN_DELETE == FSN_DELETE) && ev.IsDelete() { sendEvent = true } if (fsnFlags&FSN_RENAME == FSN_RENAME) && ev.IsRename() { sendEvent = true } if sendEvent { w.Event <- ev } // If there's no file, then no more events for user // BSD must keep watch for internal use (watches DELETEs to keep track // what files exist for create events) if ev.IsDelete() { w.fsnmut.Lock() delete(w.fsnFlags, ev.Name) w.fsnmut.Unlock() } } close(w.Event) }
[ "func", "(", "w", "*", "Watcher", ")", "purgeEvents", "(", ")", "{", "for", "ev", ":=", "range", "w", ".", "internalEvent", "{", "sendEvent", ":=", "false", "\n", "w", ".", "fsnmut", ".", "Lock", "(", ")", "\n", "fsnFlags", ":=", "w", ".", "fsnFlags", "[", "ev", ".", "Name", "]", "\n", "w", ".", "fsnmut", ".", "Unlock", "(", ")", "\n\n", "if", "(", "fsnFlags", "&", "FSN_CREATE", "==", "FSN_CREATE", ")", "&&", "ev", ".", "IsCreate", "(", ")", "{", "sendEvent", "=", "true", "\n", "}", "\n\n", "if", "(", "fsnFlags", "&", "FSN_MODIFY", "==", "FSN_MODIFY", ")", "&&", "ev", ".", "IsModify", "(", ")", "{", "sendEvent", "=", "true", "\n", "}", "\n\n", "if", "(", "fsnFlags", "&", "FSN_DELETE", "==", "FSN_DELETE", ")", "&&", "ev", ".", "IsDelete", "(", ")", "{", "sendEvent", "=", "true", "\n", "}", "\n\n", "if", "(", "fsnFlags", "&", "FSN_RENAME", "==", "FSN_RENAME", ")", "&&", "ev", ".", "IsRename", "(", ")", "{", "sendEvent", "=", "true", "\n", "}", "\n\n", "if", "sendEvent", "{", "w", ".", "Event", "<-", "ev", "\n", "}", "\n\n", "// If there's no file, then no more events for user", "// BSD must keep watch for internal use (watches DELETEs to keep track", "// what files exist for create events)", "if", "ev", ".", "IsDelete", "(", ")", "{", "w", ".", "fsnmut", ".", "Lock", "(", ")", "\n", "delete", "(", "w", ".", "fsnFlags", ",", "ev", ".", "Name", ")", "\n", "w", ".", "fsnmut", ".", "Unlock", "(", ")", "\n", "}", "\n", "}", "\n\n", "close", "(", "w", ".", "Event", ")", "\n", "}" ]
// Purge events from interal chan to external chan if passes filter
[ "Purge", "events", "from", "interal", "chan", "to", "external", "chan", "if", "passes", "filter" ]
f0c08ee9c60704c1879025f2ae0ff3e000082c13
https://github.com/howeyc/fsnotify/blob/f0c08ee9c60704c1879025f2ae0ff3e000082c13/fsnotify.go#L20-L58
train
howeyc/fsnotify
fsnotify.go
Watch
func (w *Watcher) Watch(path string) error { return w.WatchFlags(path, FSN_ALL) }
go
func (w *Watcher) Watch(path string) error { return w.WatchFlags(path, FSN_ALL) }
[ "func", "(", "w", "*", "Watcher", ")", "Watch", "(", "path", "string", ")", "error", "{", "return", "w", ".", "WatchFlags", "(", "path", ",", "FSN_ALL", ")", "\n", "}" ]
// Watch a given file path
[ "Watch", "a", "given", "file", "path" ]
f0c08ee9c60704c1879025f2ae0ff3e000082c13
https://github.com/howeyc/fsnotify/blob/f0c08ee9c60704c1879025f2ae0ff3e000082c13/fsnotify.go#L61-L63
train
howeyc/fsnotify
fsnotify.go
RemoveWatch
func (w *Watcher) RemoveWatch(path string) error { w.fsnmut.Lock() delete(w.fsnFlags, path) w.fsnmut.Unlock() return w.removeWatch(path) }
go
func (w *Watcher) RemoveWatch(path string) error { w.fsnmut.Lock() delete(w.fsnFlags, path) w.fsnmut.Unlock() return w.removeWatch(path) }
[ "func", "(", "w", "*", "Watcher", ")", "RemoveWatch", "(", "path", "string", ")", "error", "{", "w", ".", "fsnmut", ".", "Lock", "(", ")", "\n", "delete", "(", "w", ".", "fsnFlags", ",", "path", ")", "\n", "w", ".", "fsnmut", ".", "Unlock", "(", ")", "\n", "return", "w", ".", "removeWatch", "(", "path", ")", "\n", "}" ]
// Remove a watch on a file
[ "Remove", "a", "watch", "on", "a", "file" ]
f0c08ee9c60704c1879025f2ae0ff3e000082c13
https://github.com/howeyc/fsnotify/blob/f0c08ee9c60704c1879025f2ae0ff3e000082c13/fsnotify.go#L74-L79
train
howeyc/fsnotify
fsnotify_linux.go
IsCreate
func (e *FileEvent) IsCreate() bool { return (e.mask&sys_IN_CREATE) == sys_IN_CREATE || (e.mask&sys_IN_MOVED_TO) == sys_IN_MOVED_TO }
go
func (e *FileEvent) IsCreate() bool { return (e.mask&sys_IN_CREATE) == sys_IN_CREATE || (e.mask&sys_IN_MOVED_TO) == sys_IN_MOVED_TO }
[ "func", "(", "e", "*", "FileEvent", ")", "IsCreate", "(", ")", "bool", "{", "return", "(", "e", ".", "mask", "&", "sys_IN_CREATE", ")", "==", "sys_IN_CREATE", "||", "(", "e", ".", "mask", "&", "sys_IN_MOVED_TO", ")", "==", "sys_IN_MOVED_TO", "\n", "}" ]
// IsCreate reports whether the FileEvent was triggered by a creation
[ "IsCreate", "reports", "whether", "the", "FileEvent", "was", "triggered", "by", "a", "creation" ]
f0c08ee9c60704c1879025f2ae0ff3e000082c13
https://github.com/howeyc/fsnotify/blob/f0c08ee9c60704c1879025f2ae0ff3e000082c13/fsnotify_linux.go#L66-L68
train
howeyc/fsnotify
fsnotify_linux.go
Close
func (w *Watcher) Close() error { if w.isClosed { return nil } w.isClosed = true // Remove all watches for path := range w.watches { w.RemoveWatch(path) } // Send "quit" message to the reader goroutine w.done <- true return nil }
go
func (w *Watcher) Close() error { if w.isClosed { return nil } w.isClosed = true // Remove all watches for path := range w.watches { w.RemoveWatch(path) } // Send "quit" message to the reader goroutine w.done <- true return nil }
[ "func", "(", "w", "*", "Watcher", ")", "Close", "(", ")", "error", "{", "if", "w", ".", "isClosed", "{", "return", "nil", "\n", "}", "\n", "w", ".", "isClosed", "=", "true", "\n\n", "// Remove all watches", "for", "path", ":=", "range", "w", ".", "watches", "{", "w", ".", "RemoveWatch", "(", "path", ")", "\n", "}", "\n\n", "// Send \"quit\" message to the reader goroutine", "w", ".", "done", "<-", "true", "\n\n", "return", "nil", "\n", "}" ]
// Close closes an inotify watcher instance // It sends a message to the reader goroutine to quit and removes all watches // associated with the inotify instance
[ "Close", "closes", "an", "inotify", "watcher", "instance", "It", "sends", "a", "message", "to", "the", "reader", "goroutine", "to", "quit", "and", "removes", "all", "watches", "associated", "with", "the", "inotify", "instance" ]
f0c08ee9c60704c1879025f2ae0ff3e000082c13
https://github.com/howeyc/fsnotify/blob/f0c08ee9c60704c1879025f2ae0ff3e000082c13/fsnotify_linux.go#L134-L149
train
howeyc/fsnotify
fsnotify_linux.go
readEvents
func (w *Watcher) readEvents() { var ( buf [syscall.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events n int // Number of bytes read with read() errno error // Syscall errno ) for { // See if there is a message on the "done" channel select { case <-w.done: syscall.Close(w.fd) close(w.internalEvent) close(w.Error) return default: } n, errno = syscall.Read(w.fd, buf[:]) // If EOF is received if n == 0 { syscall.Close(w.fd) close(w.internalEvent) close(w.Error) return } if n < 0 { w.Error <- os.NewSyscallError("read", errno) continue } if n < syscall.SizeofInotifyEvent { w.Error <- errors.New("inotify: short read in readEvents()") continue } var offset uint32 = 0 // We don't know how many events we just read into the buffer // While the offset points to at least one whole event... for offset <= uint32(n-syscall.SizeofInotifyEvent) { // Point "raw" to the event in the buffer raw := (*syscall.InotifyEvent)(unsafe.Pointer(&buf[offset])) event := new(FileEvent) event.mask = uint32(raw.Mask) event.cookie = uint32(raw.Cookie) nameLen := uint32(raw.Len) // If the event happened to the watched directory or the watched file, the kernel // doesn't append the filename to the event, but we would like to always fill the // the "Name" field with a valid filename. We retrieve the path of the watch from // the "paths" map. w.mu.Lock() event.Name = w.paths[int(raw.Wd)] w.mu.Unlock() watchedName := event.Name if nameLen > 0 { // Point "bytes" at the first byte of the filename bytes := (*[syscall.PathMax]byte)(unsafe.Pointer(&buf[offset+syscall.SizeofInotifyEvent])) // The filename is padded with NUL bytes. TrimRight() gets rid of those. event.Name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\000") } // Send the events that are not ignored on the events channel if !event.ignoreLinux() { // Setup FSNotify flags (inherit from directory watch) w.fsnmut.Lock() if _, fsnFound := w.fsnFlags[event.Name]; !fsnFound { if fsnFlags, watchFound := w.fsnFlags[watchedName]; watchFound { w.fsnFlags[event.Name] = fsnFlags } else { w.fsnFlags[event.Name] = FSN_ALL } } w.fsnmut.Unlock() w.internalEvent <- event } // Move to the next event in the buffer offset += syscall.SizeofInotifyEvent + nameLen } } }
go
func (w *Watcher) readEvents() { var ( buf [syscall.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events n int // Number of bytes read with read() errno error // Syscall errno ) for { // See if there is a message on the "done" channel select { case <-w.done: syscall.Close(w.fd) close(w.internalEvent) close(w.Error) return default: } n, errno = syscall.Read(w.fd, buf[:]) // If EOF is received if n == 0 { syscall.Close(w.fd) close(w.internalEvent) close(w.Error) return } if n < 0 { w.Error <- os.NewSyscallError("read", errno) continue } if n < syscall.SizeofInotifyEvent { w.Error <- errors.New("inotify: short read in readEvents()") continue } var offset uint32 = 0 // We don't know how many events we just read into the buffer // While the offset points to at least one whole event... for offset <= uint32(n-syscall.SizeofInotifyEvent) { // Point "raw" to the event in the buffer raw := (*syscall.InotifyEvent)(unsafe.Pointer(&buf[offset])) event := new(FileEvent) event.mask = uint32(raw.Mask) event.cookie = uint32(raw.Cookie) nameLen := uint32(raw.Len) // If the event happened to the watched directory or the watched file, the kernel // doesn't append the filename to the event, but we would like to always fill the // the "Name" field with a valid filename. We retrieve the path of the watch from // the "paths" map. w.mu.Lock() event.Name = w.paths[int(raw.Wd)] w.mu.Unlock() watchedName := event.Name if nameLen > 0 { // Point "bytes" at the first byte of the filename bytes := (*[syscall.PathMax]byte)(unsafe.Pointer(&buf[offset+syscall.SizeofInotifyEvent])) // The filename is padded with NUL bytes. TrimRight() gets rid of those. event.Name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\000") } // Send the events that are not ignored on the events channel if !event.ignoreLinux() { // Setup FSNotify flags (inherit from directory watch) w.fsnmut.Lock() if _, fsnFound := w.fsnFlags[event.Name]; !fsnFound { if fsnFlags, watchFound := w.fsnFlags[watchedName]; watchFound { w.fsnFlags[event.Name] = fsnFlags } else { w.fsnFlags[event.Name] = FSN_ALL } } w.fsnmut.Unlock() w.internalEvent <- event } // Move to the next event in the buffer offset += syscall.SizeofInotifyEvent + nameLen } } }
[ "func", "(", "w", "*", "Watcher", ")", "readEvents", "(", ")", "{", "var", "(", "buf", "[", "syscall", ".", "SizeofInotifyEvent", "*", "4096", "]", "byte", "// Buffer for a maximum of 4096 raw events", "\n", "n", "int", "// Number of bytes read with read()", "\n", "errno", "error", "// Syscall errno", "\n", ")", "\n\n", "for", "{", "// See if there is a message on the \"done\" channel", "select", "{", "case", "<-", "w", ".", "done", ":", "syscall", ".", "Close", "(", "w", ".", "fd", ")", "\n", "close", "(", "w", ".", "internalEvent", ")", "\n", "close", "(", "w", ".", "Error", ")", "\n", "return", "\n", "default", ":", "}", "\n\n", "n", ",", "errno", "=", "syscall", ".", "Read", "(", "w", ".", "fd", ",", "buf", "[", ":", "]", ")", "\n\n", "// If EOF is received", "if", "n", "==", "0", "{", "syscall", ".", "Close", "(", "w", ".", "fd", ")", "\n", "close", "(", "w", ".", "internalEvent", ")", "\n", "close", "(", "w", ".", "Error", ")", "\n", "return", "\n", "}", "\n\n", "if", "n", "<", "0", "{", "w", ".", "Error", "<-", "os", ".", "NewSyscallError", "(", "\"", "\"", ",", "errno", ")", "\n", "continue", "\n", "}", "\n", "if", "n", "<", "syscall", ".", "SizeofInotifyEvent", "{", "w", ".", "Error", "<-", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "continue", "\n", "}", "\n\n", "var", "offset", "uint32", "=", "0", "\n", "// We don't know how many events we just read into the buffer", "// While the offset points to at least one whole event...", "for", "offset", "<=", "uint32", "(", "n", "-", "syscall", ".", "SizeofInotifyEvent", ")", "{", "// Point \"raw\" to the event in the buffer", "raw", ":=", "(", "*", "syscall", ".", "InotifyEvent", ")", "(", "unsafe", ".", "Pointer", "(", "&", "buf", "[", "offset", "]", ")", ")", "\n", "event", ":=", "new", "(", "FileEvent", ")", "\n", "event", ".", "mask", "=", "uint32", "(", "raw", ".", "Mask", ")", "\n", "event", ".", "cookie", "=", "uint32", "(", "raw", ".", "Cookie", ")", "\n", "nameLen", ":=", "uint32", "(", "raw", ".", "Len", ")", "\n", "// If the event happened to the watched directory or the watched file, the kernel", "// doesn't append the filename to the event, but we would like to always fill the", "// the \"Name\" field with a valid filename. We retrieve the path of the watch from", "// the \"paths\" map.", "w", ".", "mu", ".", "Lock", "(", ")", "\n", "event", ".", "Name", "=", "w", ".", "paths", "[", "int", "(", "raw", ".", "Wd", ")", "]", "\n", "w", ".", "mu", ".", "Unlock", "(", ")", "\n", "watchedName", ":=", "event", ".", "Name", "\n", "if", "nameLen", ">", "0", "{", "// Point \"bytes\" at the first byte of the filename", "bytes", ":=", "(", "*", "[", "syscall", ".", "PathMax", "]", "byte", ")", "(", "unsafe", ".", "Pointer", "(", "&", "buf", "[", "offset", "+", "syscall", ".", "SizeofInotifyEvent", "]", ")", ")", "\n", "// The filename is padded with NUL bytes. TrimRight() gets rid of those.", "event", ".", "Name", "+=", "\"", "\"", "+", "strings", ".", "TrimRight", "(", "string", "(", "bytes", "[", "0", ":", "nameLen", "]", ")", ",", "\"", "\\000", "\"", ")", "\n", "}", "\n\n", "// Send the events that are not ignored on the events channel", "if", "!", "event", ".", "ignoreLinux", "(", ")", "{", "// Setup FSNotify flags (inherit from directory watch)", "w", ".", "fsnmut", ".", "Lock", "(", ")", "\n", "if", "_", ",", "fsnFound", ":=", "w", ".", "fsnFlags", "[", "event", ".", "Name", "]", ";", "!", "fsnFound", "{", "if", "fsnFlags", ",", "watchFound", ":=", "w", ".", "fsnFlags", "[", "watchedName", "]", ";", "watchFound", "{", "w", ".", "fsnFlags", "[", "event", ".", "Name", "]", "=", "fsnFlags", "\n", "}", "else", "{", "w", ".", "fsnFlags", "[", "event", ".", "Name", "]", "=", "FSN_ALL", "\n", "}", "\n", "}", "\n", "w", ".", "fsnmut", ".", "Unlock", "(", ")", "\n\n", "w", ".", "internalEvent", "<-", "event", "\n", "}", "\n\n", "// Move to the next event in the buffer", "offset", "+=", "syscall", ".", "SizeofInotifyEvent", "+", "nameLen", "\n", "}", "\n", "}", "\n", "}" ]
// readEvents reads from the inotify file descriptor, converts the // received events into Event objects and sends them via the Event channel
[ "readEvents", "reads", "from", "the", "inotify", "file", "descriptor", "converts", "the", "received", "events", "into", "Event", "objects", "and", "sends", "them", "via", "the", "Event", "channel" ]
f0c08ee9c60704c1879025f2ae0ff3e000082c13
https://github.com/howeyc/fsnotify/blob/f0c08ee9c60704c1879025f2ae0ff3e000082c13/fsnotify_linux.go#L201-L283
train
howeyc/fsnotify
fsnotify_linux.go
ignoreLinux
func (e *FileEvent) ignoreLinux() bool { // Ignore anything the inotify API says to ignore if e.mask&sys_IN_IGNORED == sys_IN_IGNORED { return true } // If the event is not a DELETE or RENAME, the file must exist. // Otherwise the event is ignored. // *Note*: this was put in place because it was seen that a MODIFY // event was sent after the DELETE. This ignores that MODIFY and // assumes a DELETE will come or has come if the file doesn't exist. if !(e.IsDelete() || e.IsRename()) { _, statErr := os.Lstat(e.Name) return os.IsNotExist(statErr) } return false }
go
func (e *FileEvent) ignoreLinux() bool { // Ignore anything the inotify API says to ignore if e.mask&sys_IN_IGNORED == sys_IN_IGNORED { return true } // If the event is not a DELETE or RENAME, the file must exist. // Otherwise the event is ignored. // *Note*: this was put in place because it was seen that a MODIFY // event was sent after the DELETE. This ignores that MODIFY and // assumes a DELETE will come or has come if the file doesn't exist. if !(e.IsDelete() || e.IsRename()) { _, statErr := os.Lstat(e.Name) return os.IsNotExist(statErr) } return false }
[ "func", "(", "e", "*", "FileEvent", ")", "ignoreLinux", "(", ")", "bool", "{", "// Ignore anything the inotify API says to ignore", "if", "e", ".", "mask", "&", "sys_IN_IGNORED", "==", "sys_IN_IGNORED", "{", "return", "true", "\n", "}", "\n\n", "// If the event is not a DELETE or RENAME, the file must exist.", "// Otherwise the event is ignored.", "// *Note*: this was put in place because it was seen that a MODIFY", "// event was sent after the DELETE. This ignores that MODIFY and", "// assumes a DELETE will come or has come if the file doesn't exist.", "if", "!", "(", "e", ".", "IsDelete", "(", ")", "||", "e", ".", "IsRename", "(", ")", ")", "{", "_", ",", "statErr", ":=", "os", ".", "Lstat", "(", "e", ".", "Name", ")", "\n", "return", "os", ".", "IsNotExist", "(", "statErr", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Certain types of events can be "ignored" and not sent over the Event // channel. Such as events marked ignore by the kernel, or MODIFY events // against files that do not exist.
[ "Certain", "types", "of", "events", "can", "be", "ignored", "and", "not", "sent", "over", "the", "Event", "channel", ".", "Such", "as", "events", "marked", "ignore", "by", "the", "kernel", "or", "MODIFY", "events", "against", "files", "that", "do", "not", "exist", "." ]
f0c08ee9c60704c1879025f2ae0ff3e000082c13
https://github.com/howeyc/fsnotify/blob/f0c08ee9c60704c1879025f2ae0ff3e000082c13/fsnotify_linux.go#L288-L304
train
howeyc/fsnotify
fsnotify_bsd.go
IsModify
func (e *FileEvent) IsModify() bool { return ((e.mask&sys_NOTE_WRITE) == sys_NOTE_WRITE || (e.mask&sys_NOTE_ATTRIB) == sys_NOTE_ATTRIB) }
go
func (e *FileEvent) IsModify() bool { return ((e.mask&sys_NOTE_WRITE) == sys_NOTE_WRITE || (e.mask&sys_NOTE_ATTRIB) == sys_NOTE_ATTRIB) }
[ "func", "(", "e", "*", "FileEvent", ")", "IsModify", "(", ")", "bool", "{", "return", "(", "(", "e", ".", "mask", "&", "sys_NOTE_WRITE", ")", "==", "sys_NOTE_WRITE", "||", "(", "e", ".", "mask", "&", "sys_NOTE_ATTRIB", ")", "==", "sys_NOTE_ATTRIB", ")", "\n", "}" ]
// IsModify reports whether the FileEvent was triggered by a file modification
[ "IsModify", "reports", "whether", "the", "FileEvent", "was", "triggered", "by", "a", "file", "modification" ]
f0c08ee9c60704c1879025f2ae0ff3e000082c13
https://github.com/howeyc/fsnotify/blob/f0c08ee9c60704c1879025f2ae0ff3e000082c13/fsnotify_bsd.go#L49-L51
train