id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
151,700
twpayne/go-geom
geometrycollection.go
Push
func (g *GeometryCollection) Push(gs ...T) error { g.geoms = append(g.geoms, gs...) return nil }
go
func (g *GeometryCollection) Push(gs ...T) error { g.geoms = append(g.geoms, gs...) return nil }
[ "func", "(", "g", "*", "GeometryCollection", ")", "Push", "(", "gs", "...", "T", ")", "error", "{", "g", ".", "geoms", "=", "append", "(", "g", ".", "geoms", ",", "gs", "...", ")", "\n", "return", "nil", "\n", "}" ]
// Push appends geometries.
[ "Push", "appends", "geometries", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/geometrycollection.go#L106-L109
151,701
twpayne/go-geom
geometrycollection.go
SetSRID
func (g *GeometryCollection) SetSRID(srid int) *GeometryCollection { g.srid = srid return g }
go
func (g *GeometryCollection) SetSRID(srid int) *GeometryCollection { g.srid = srid return g }
[ "func", "(", "g", "*", "GeometryCollection", ")", "SetSRID", "(", "srid", "int", ")", "*", "GeometryCollection", "{", "g", ".", "srid", "=", "srid", "\n", "return", "g", "\n", "}" ]
// SetSRID sets g's SRID and the SRID of all its elements.
[ "SetSRID", "sets", "g", "s", "SRID", "and", "the", "SRID", "of", "all", "its", "elements", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/geometrycollection.go#L112-L115
151,702
twpayne/go-geom
encoding/igc/encode.go
Encode
func (enc *Encoder) Encode(ls *geom.LineString) error { if enc.a != "" { if _, err := fmt.Fprintf(enc.w, "A%s\n", enc.a); err != nil { return err } } var t0 time.Time for i, n := 0, ls.NumCoords(); i < n; i++ { coord := ls.Coord(i) t := time.Unix(int64(coord[3]), 0).UTC() if t.Day() != t0.Day() || t.Month() != t0.Month() || t.Year() != t0.Year() { if _, err := fmt.Fprintf(enc.w, "HFDTE%02d%02d%02d\n", t.Day(), t.Month(), t.Year()%100); err != nil { return err } t0 = t } latMMin := int(math.Abs(60000 * coord[1])) if latMMin > 90*60000 { latMMin = 90 * 60000 } latDeg, latMMin := latMMin/60000, latMMin%60000 var latHemi string if coord[1] < 0 { latHemi = "S" } else { latHemi = "N" } lngMMin := int(math.Abs(60000 * coord[0])) if lngMMin > 180*60000 { lngMMin = 180 * 60000 } lngDeg, lngMMin := lngMMin/60000, lngMMin%60000 var lngHemi string if coord[0] < 0 { lngHemi = "W" } else { lngHemi = "E" } alt := clamp(int(coord[2]), 0, 10000) if _, err := fmt.Fprintf(enc.w, "B%02d%02d%02d%02d%05d%s%03d%05d%sA%05d%05d\n", t.Hour(), t.Minute(), t.Second(), latDeg, latMMin, latHemi, lngDeg, lngMMin, lngHemi, alt, alt); err != nil { return err } } return nil }
go
func (enc *Encoder) Encode(ls *geom.LineString) error { if enc.a != "" { if _, err := fmt.Fprintf(enc.w, "A%s\n", enc.a); err != nil { return err } } var t0 time.Time for i, n := 0, ls.NumCoords(); i < n; i++ { coord := ls.Coord(i) t := time.Unix(int64(coord[3]), 0).UTC() if t.Day() != t0.Day() || t.Month() != t0.Month() || t.Year() != t0.Year() { if _, err := fmt.Fprintf(enc.w, "HFDTE%02d%02d%02d\n", t.Day(), t.Month(), t.Year()%100); err != nil { return err } t0 = t } latMMin := int(math.Abs(60000 * coord[1])) if latMMin > 90*60000 { latMMin = 90 * 60000 } latDeg, latMMin := latMMin/60000, latMMin%60000 var latHemi string if coord[1] < 0 { latHemi = "S" } else { latHemi = "N" } lngMMin := int(math.Abs(60000 * coord[0])) if lngMMin > 180*60000 { lngMMin = 180 * 60000 } lngDeg, lngMMin := lngMMin/60000, lngMMin%60000 var lngHemi string if coord[0] < 0 { lngHemi = "W" } else { lngHemi = "E" } alt := clamp(int(coord[2]), 0, 10000) if _, err := fmt.Fprintf(enc.w, "B%02d%02d%02d%02d%05d%s%03d%05d%sA%05d%05d\n", t.Hour(), t.Minute(), t.Second(), latDeg, latMMin, latHemi, lngDeg, lngMMin, lngHemi, alt, alt); err != nil { return err } } return nil }
[ "func", "(", "enc", "*", "Encoder", ")", "Encode", "(", "ls", "*", "geom", ".", "LineString", ")", "error", "{", "if", "enc", ".", "a", "!=", "\"", "\"", "{", "if", "_", ",", "err", ":=", "fmt", ".", "Fprintf", "(", "enc", ".", "w", ",", "\"", "\\n", "\"", ",", "enc", ".", "a", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "var", "t0", "time", ".", "Time", "\n", "for", "i", ",", "n", ":=", "0", ",", "ls", ".", "NumCoords", "(", ")", ";", "i", "<", "n", ";", "i", "++", "{", "coord", ":=", "ls", ".", "Coord", "(", "i", ")", "\n", "t", ":=", "time", ".", "Unix", "(", "int64", "(", "coord", "[", "3", "]", ")", ",", "0", ")", ".", "UTC", "(", ")", "\n", "if", "t", ".", "Day", "(", ")", "!=", "t0", ".", "Day", "(", ")", "||", "t", ".", "Month", "(", ")", "!=", "t0", ".", "Month", "(", ")", "||", "t", ".", "Year", "(", ")", "!=", "t0", ".", "Year", "(", ")", "{", "if", "_", ",", "err", ":=", "fmt", ".", "Fprintf", "(", "enc", ".", "w", ",", "\"", "\\n", "\"", ",", "t", ".", "Day", "(", ")", ",", "t", ".", "Month", "(", ")", ",", "t", ".", "Year", "(", ")", "%", "100", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "t0", "=", "t", "\n", "}", "\n", "latMMin", ":=", "int", "(", "math", ".", "Abs", "(", "60000", "*", "coord", "[", "1", "]", ")", ")", "\n", "if", "latMMin", ">", "90", "*", "60000", "{", "latMMin", "=", "90", "*", "60000", "\n", "}", "\n", "latDeg", ",", "latMMin", ":=", "latMMin", "/", "60000", ",", "latMMin", "%", "60000", "\n", "var", "latHemi", "string", "\n", "if", "coord", "[", "1", "]", "<", "0", "{", "latHemi", "=", "\"", "\"", "\n", "}", "else", "{", "latHemi", "=", "\"", "\"", "\n", "}", "\n", "lngMMin", ":=", "int", "(", "math", ".", "Abs", "(", "60000", "*", "coord", "[", "0", "]", ")", ")", "\n", "if", "lngMMin", ">", "180", "*", "60000", "{", "lngMMin", "=", "180", "*", "60000", "\n", "}", "\n", "lngDeg", ",", "lngMMin", ":=", "lngMMin", "/", "60000", ",", "lngMMin", "%", "60000", "\n", "var", "lngHemi", "string", "\n", "if", "coord", "[", "0", "]", "<", "0", "{", "lngHemi", "=", "\"", "\"", "\n", "}", "else", "{", "lngHemi", "=", "\"", "\"", "\n", "}", "\n", "alt", ":=", "clamp", "(", "int", "(", "coord", "[", "2", "]", ")", ",", "0", ",", "10000", ")", "\n", "if", "_", ",", "err", ":=", "fmt", ".", "Fprintf", "(", "enc", ".", "w", ",", "\"", "\\n", "\"", ",", "t", ".", "Hour", "(", ")", ",", "t", ".", "Minute", "(", ")", ",", "t", ".", "Second", "(", ")", ",", "latDeg", ",", "latMMin", ",", "latHemi", ",", "lngDeg", ",", "lngMMin", ",", "lngHemi", ",", "alt", ",", "alt", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Encode encodes a LineString.
[ "Encode", "encodes", "a", "LineString", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/encoding/igc/encode.go#L42-L86
151,703
twpayne/go-geom
multilinestring.go
NewMultiLineStringFlat
func NewMultiLineStringFlat(layout Layout, flatCoords []float64, ends []int) *MultiLineString { g := new(MultiLineString) g.layout = layout g.stride = layout.Stride() g.flatCoords = flatCoords g.ends = ends return g }
go
func NewMultiLineStringFlat(layout Layout, flatCoords []float64, ends []int) *MultiLineString { g := new(MultiLineString) g.layout = layout g.stride = layout.Stride() g.flatCoords = flatCoords g.ends = ends return g }
[ "func", "NewMultiLineStringFlat", "(", "layout", "Layout", ",", "flatCoords", "[", "]", "float64", ",", "ends", "[", "]", "int", ")", "*", "MultiLineString", "{", "g", ":=", "new", "(", "MultiLineString", ")", "\n", "g", ".", "layout", "=", "layout", "\n", "g", ".", "stride", "=", "layout", ".", "Stride", "(", ")", "\n", "g", ".", "flatCoords", "=", "flatCoords", "\n", "g", ".", "ends", "=", "ends", "\n", "return", "g", "\n", "}" ]
// NewMultiLineStringFlat returns a new MultiLineString with the given flat coordinates.
[ "NewMultiLineStringFlat", "returns", "a", "new", "MultiLineString", "with", "the", "given", "flat", "coordinates", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/multilinestring.go#L14-L21
151,704
twpayne/go-geom
multilinestring.go
Length
func (g *MultiLineString) Length() float64 { return length2(g.flatCoords, 0, g.ends, g.stride) }
go
func (g *MultiLineString) Length() float64 { return length2(g.flatCoords, 0, g.ends, g.stride) }
[ "func", "(", "g", "*", "MultiLineString", ")", "Length", "(", ")", "float64", "{", "return", "length2", "(", "g", ".", "flatCoords", ",", "0", ",", "g", ".", "ends", ",", "g", ".", "stride", ")", "\n", "}" ]
// Length returns the sum of the length of the LineStrings.
[ "Length", "returns", "the", "sum", "of", "the", "length", "of", "the", "LineStrings", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/multilinestring.go#L39-L41
151,705
twpayne/go-geom
multilinestring.go
LineString
func (g *MultiLineString) LineString(i int) *LineString { offset := 0 if i > 0 { offset = g.ends[i-1] } return NewLineStringFlat(g.layout, g.flatCoords[offset:g.ends[i]]) }
go
func (g *MultiLineString) LineString(i int) *LineString { offset := 0 if i > 0 { offset = g.ends[i-1] } return NewLineStringFlat(g.layout, g.flatCoords[offset:g.ends[i]]) }
[ "func", "(", "g", "*", "MultiLineString", ")", "LineString", "(", "i", "int", ")", "*", "LineString", "{", "offset", ":=", "0", "\n", "if", "i", ">", "0", "{", "offset", "=", "g", ".", "ends", "[", "i", "-", "1", "]", "\n", "}", "\n", "return", "NewLineStringFlat", "(", "g", ".", "layout", ",", "g", ".", "flatCoords", "[", "offset", ":", "g", ".", "ends", "[", "i", "]", "]", ")", "\n", "}" ]
// LineString returns the ith LineString.
[ "LineString", "returns", "the", "ith", "LineString", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/multilinestring.go#L44-L50
151,706
twpayne/go-geom
multilinestring.go
Push
func (g *MultiLineString) Push(ls *LineString) error { if ls.layout != g.layout { return ErrLayoutMismatch{Got: ls.layout, Want: g.layout} } g.flatCoords = append(g.flatCoords, ls.flatCoords...) g.ends = append(g.ends, len(g.flatCoords)) return nil }
go
func (g *MultiLineString) Push(ls *LineString) error { if ls.layout != g.layout { return ErrLayoutMismatch{Got: ls.layout, Want: g.layout} } g.flatCoords = append(g.flatCoords, ls.flatCoords...) g.ends = append(g.ends, len(g.flatCoords)) return nil }
[ "func", "(", "g", "*", "MultiLineString", ")", "Push", "(", "ls", "*", "LineString", ")", "error", "{", "if", "ls", ".", "layout", "!=", "g", ".", "layout", "{", "return", "ErrLayoutMismatch", "{", "Got", ":", "ls", ".", "layout", ",", "Want", ":", "g", ".", "layout", "}", "\n", "}", "\n", "g", ".", "flatCoords", "=", "append", "(", "g", ".", "flatCoords", ",", "ls", ".", "flatCoords", "...", ")", "\n", "g", ".", "ends", "=", "append", "(", "g", ".", "ends", ",", "len", "(", "g", ".", "flatCoords", ")", ")", "\n", "return", "nil", "\n", "}" ]
// Push appends a LineString.
[ "Push", "appends", "a", "LineString", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/multilinestring.go#L64-L71
151,707
twpayne/go-geom
encoding/geojson/geojson.go
Encode
func Encode(g geom.T) (*Geometry, error) { switch g := g.(type) { case *geom.Point: var coords json.RawMessage coords, err := json.Marshal(g.Coords()) if err != nil { return nil, err } return &Geometry{ Type: "Point", Coordinates: &coords, }, nil case *geom.LineString: var coords json.RawMessage coords, err := json.Marshal(g.Coords()) if err != nil { return nil, err } return &Geometry{ Type: "LineString", Coordinates: &coords, }, nil case *geom.Polygon: var coords json.RawMessage coords, err := json.Marshal(g.Coords()) if err != nil { return nil, err } return &Geometry{ Type: "Polygon", Coordinates: &coords, }, nil case *geom.MultiPoint: var coords json.RawMessage coords, err := json.Marshal(g.Coords()) if err != nil { return nil, err } return &Geometry{ Type: "MultiPoint", Coordinates: &coords, }, nil case *geom.MultiLineString: var coords json.RawMessage coords, err := json.Marshal(g.Coords()) if err != nil { return nil, err } return &Geometry{ Type: "MultiLineString", Coordinates: &coords, }, nil case *geom.MultiPolygon: var coords json.RawMessage coords, err := json.Marshal(g.Coords()) if err != nil { return nil, err } return &Geometry{ Type: "MultiPolygon", Coordinates: &coords, }, nil case *geom.GeometryCollection: geometries := make([]*Geometry, len(g.Geoms())) for i, subGeometry := range g.Geoms() { var err error geometries[i], err = Encode(subGeometry) if err != nil { return nil, err } } return &Geometry{ Type: "GeometryCollection", Geometries: geometries, }, nil default: return nil, geom.ErrUnsupportedType{Value: g} } }
go
func Encode(g geom.T) (*Geometry, error) { switch g := g.(type) { case *geom.Point: var coords json.RawMessage coords, err := json.Marshal(g.Coords()) if err != nil { return nil, err } return &Geometry{ Type: "Point", Coordinates: &coords, }, nil case *geom.LineString: var coords json.RawMessage coords, err := json.Marshal(g.Coords()) if err != nil { return nil, err } return &Geometry{ Type: "LineString", Coordinates: &coords, }, nil case *geom.Polygon: var coords json.RawMessage coords, err := json.Marshal(g.Coords()) if err != nil { return nil, err } return &Geometry{ Type: "Polygon", Coordinates: &coords, }, nil case *geom.MultiPoint: var coords json.RawMessage coords, err := json.Marshal(g.Coords()) if err != nil { return nil, err } return &Geometry{ Type: "MultiPoint", Coordinates: &coords, }, nil case *geom.MultiLineString: var coords json.RawMessage coords, err := json.Marshal(g.Coords()) if err != nil { return nil, err } return &Geometry{ Type: "MultiLineString", Coordinates: &coords, }, nil case *geom.MultiPolygon: var coords json.RawMessage coords, err := json.Marshal(g.Coords()) if err != nil { return nil, err } return &Geometry{ Type: "MultiPolygon", Coordinates: &coords, }, nil case *geom.GeometryCollection: geometries := make([]*Geometry, len(g.Geoms())) for i, subGeometry := range g.Geoms() { var err error geometries[i], err = Encode(subGeometry) if err != nil { return nil, err } } return &Geometry{ Type: "GeometryCollection", Geometries: geometries, }, nil default: return nil, geom.ErrUnsupportedType{Value: g} } }
[ "func", "Encode", "(", "g", "geom", ".", "T", ")", "(", "*", "Geometry", ",", "error", ")", "{", "switch", "g", ":=", "g", ".", "(", "type", ")", "{", "case", "*", "geom", ".", "Point", ":", "var", "coords", "json", ".", "RawMessage", "\n", "coords", ",", "err", ":=", "json", ".", "Marshal", "(", "g", ".", "Coords", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Geometry", "{", "Type", ":", "\"", "\"", ",", "Coordinates", ":", "&", "coords", ",", "}", ",", "nil", "\n", "case", "*", "geom", ".", "LineString", ":", "var", "coords", "json", ".", "RawMessage", "\n", "coords", ",", "err", ":=", "json", ".", "Marshal", "(", "g", ".", "Coords", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Geometry", "{", "Type", ":", "\"", "\"", ",", "Coordinates", ":", "&", "coords", ",", "}", ",", "nil", "\n", "case", "*", "geom", ".", "Polygon", ":", "var", "coords", "json", ".", "RawMessage", "\n", "coords", ",", "err", ":=", "json", ".", "Marshal", "(", "g", ".", "Coords", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Geometry", "{", "Type", ":", "\"", "\"", ",", "Coordinates", ":", "&", "coords", ",", "}", ",", "nil", "\n", "case", "*", "geom", ".", "MultiPoint", ":", "var", "coords", "json", ".", "RawMessage", "\n", "coords", ",", "err", ":=", "json", ".", "Marshal", "(", "g", ".", "Coords", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Geometry", "{", "Type", ":", "\"", "\"", ",", "Coordinates", ":", "&", "coords", ",", "}", ",", "nil", "\n", "case", "*", "geom", ".", "MultiLineString", ":", "var", "coords", "json", ".", "RawMessage", "\n", "coords", ",", "err", ":=", "json", ".", "Marshal", "(", "g", ".", "Coords", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Geometry", "{", "Type", ":", "\"", "\"", ",", "Coordinates", ":", "&", "coords", ",", "}", ",", "nil", "\n", "case", "*", "geom", ".", "MultiPolygon", ":", "var", "coords", "json", ".", "RawMessage", "\n", "coords", ",", "err", ":=", "json", ".", "Marshal", "(", "g", ".", "Coords", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Geometry", "{", "Type", ":", "\"", "\"", ",", "Coordinates", ":", "&", "coords", ",", "}", ",", "nil", "\n", "case", "*", "geom", ".", "GeometryCollection", ":", "geometries", ":=", "make", "(", "[", "]", "*", "Geometry", ",", "len", "(", "g", ".", "Geoms", "(", ")", ")", ")", "\n", "for", "i", ",", "subGeometry", ":=", "range", "g", ".", "Geoms", "(", ")", "{", "var", "err", "error", "\n", "geometries", "[", "i", "]", ",", "err", "=", "Encode", "(", "subGeometry", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "&", "Geometry", "{", "Type", ":", "\"", "\"", ",", "Geometries", ":", "geometries", ",", "}", ",", "nil", "\n", "default", ":", "return", "nil", ",", "geom", ".", "ErrUnsupportedType", "{", "Value", ":", "g", "}", "\n", "}", "\n", "}" ]
// Encode encodes g as a GeoJSON geometry.
[ "Encode", "encodes", "g", "as", "a", "GeoJSON", "geometry", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/encoding/geojson/geojson.go#L197-L275
151,708
twpayne/go-geom
encoding/geojson/geojson.go
UnmarshalJSON
func (f *Feature) UnmarshalJSON(data []byte) error { var gf geojsonFeature if err := json.Unmarshal(data, &gf); err != nil { return err } if gf.Type != "Feature" { return ErrUnsupportedType(gf.Type) } f.ID = gf.ID var err error f.Geometry, err = gf.Geometry.Decode() if err != nil { return err } f.Properties = gf.Properties return nil }
go
func (f *Feature) UnmarshalJSON(data []byte) error { var gf geojsonFeature if err := json.Unmarshal(data, &gf); err != nil { return err } if gf.Type != "Feature" { return ErrUnsupportedType(gf.Type) } f.ID = gf.ID var err error f.Geometry, err = gf.Geometry.Decode() if err != nil { return err } f.Properties = gf.Properties return nil }
[ "func", "(", "f", "*", "Feature", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "var", "gf", "geojsonFeature", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "gf", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "gf", ".", "Type", "!=", "\"", "\"", "{", "return", "ErrUnsupportedType", "(", "gf", ".", "Type", ")", "\n", "}", "\n", "f", ".", "ID", "=", "gf", ".", "ID", "\n", "var", "err", "error", "\n", "f", ".", "Geometry", ",", "err", "=", "gf", ".", "Geometry", ".", "Decode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "f", ".", "Properties", "=", "gf", ".", "Properties", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON implements json.Unmarshaler.UnmarshalJSON.
[ "UnmarshalJSON", "implements", "json", ".", "Unmarshaler", ".", "UnmarshalJSON", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/encoding/geojson/geojson.go#L312-L328
151,709
twpayne/go-geom
encoding/geojson/geojson.go
UnmarshalJSON
func (fc *FeatureCollection) UnmarshalJSON(data []byte) error { var gfc geojsonFeatureCollection if err := json.Unmarshal(data, &gfc); err != nil { return err } if gfc.Type != "FeatureCollection" { return ErrUnsupportedType(gfc.Type) } fc.Features = gfc.Features return nil }
go
func (fc *FeatureCollection) UnmarshalJSON(data []byte) error { var gfc geojsonFeatureCollection if err := json.Unmarshal(data, &gfc); err != nil { return err } if gfc.Type != "FeatureCollection" { return ErrUnsupportedType(gfc.Type) } fc.Features = gfc.Features return nil }
[ "func", "(", "fc", "*", "FeatureCollection", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "var", "gfc", "geojsonFeatureCollection", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "gfc", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "gfc", ".", "Type", "!=", "\"", "\"", "{", "return", "ErrUnsupportedType", "(", "gfc", ".", "Type", ")", "\n", "}", "\n", "fc", ".", "Features", "=", "gfc", ".", "Features", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON implements json.Unmarshaler.UnmarshalJSON
[ "UnmarshalJSON", "implements", "json", ".", "Unmarshaler", ".", "UnmarshalJSON" ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/encoding/geojson/geojson.go#L343-L353
151,710
twpayne/go-geom
xy/internal/centralendpoint/intersector.go
GetIntersection
func GetIntersection(line1End1, line1End2, line2End1, line2End2 geom.Coord) geom.Coord { intersector := centralEndpointIntersector{ line1End1: line1End1, line1End2: line1End2, line2End1: line2End1, line2End2: line2End2, } intersector.compute() return intersector.intersectionPoint }
go
func GetIntersection(line1End1, line1End2, line2End1, line2End2 geom.Coord) geom.Coord { intersector := centralEndpointIntersector{ line1End1: line1End1, line1End2: line1End2, line2End1: line2End1, line2End2: line2End2, } intersector.compute() return intersector.intersectionPoint }
[ "func", "GetIntersection", "(", "line1End1", ",", "line1End2", ",", "line2End1", ",", "line2End2", "geom", ".", "Coord", ")", "geom", ".", "Coord", "{", "intersector", ":=", "centralEndpointIntersector", "{", "line1End1", ":", "line1End1", ",", "line1End2", ":", "line1End2", ",", "line2End1", ":", "line2End1", ",", "line2End2", ":", "line2End2", ",", "}", "\n", "intersector", ".", "compute", "(", ")", "\n", "return", "intersector", ".", "intersectionPoint", "\n", "}" ]
// GetIntersection computes an approximate intersection of two line segments by taking the most central of the endpoints of the segments. // // This is effective in cases where the segments are nearly parallel and should intersect at an endpoint. // It is also a reasonable strategy for cases where the endpoint of one segment lies on or almost on the interior of another one. // Taking the most central endpoint ensures that the computed intersection point lies in the envelope of the segments. // // Also, by always returning one of the input points, this should result in reducing segment fragmentation. // Intended to be used as a last resort for computing ill-conditioned intersection situations which cause other methods to fail.
[ "GetIntersection", "computes", "an", "approximate", "intersection", "of", "two", "line", "segments", "by", "taking", "the", "most", "central", "of", "the", "endpoints", "of", "the", "segments", ".", "This", "is", "effective", "in", "cases", "where", "the", "segments", "are", "nearly", "parallel", "and", "should", "intersect", "at", "an", "endpoint", ".", "It", "is", "also", "a", "reasonable", "strategy", "for", "cases", "where", "the", "endpoint", "of", "one", "segment", "lies", "on", "or", "almost", "on", "the", "interior", "of", "another", "one", ".", "Taking", "the", "most", "central", "endpoint", "ensures", "that", "the", "computed", "intersection", "point", "lies", "in", "the", "envelope", "of", "the", "segments", ".", "Also", "by", "always", "returning", "one", "of", "the", "input", "points", "this", "should", "result", "in", "reducing", "segment", "fragmentation", ".", "Intended", "to", "be", "used", "as", "a", "last", "resort", "for", "computing", "ill", "-", "conditioned", "intersection", "situations", "which", "cause", "other", "methods", "to", "fail", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/internal/centralendpoint/intersector.go#L18-L27
151,711
twpayne/go-geom
xy/internal/raycrossing/ray-crossing-counter.go
LocatePointInRing
func LocatePointInRing(layout geom.Layout, p geom.Coord, ring []float64) location.Type { counter := rayCrossingCounter{p: p} stride := layout.Stride() for i := stride; i < len(ring); i += stride { p1 := geom.Coord(ring[i : i+2]) p2 := geom.Coord(ring[i-stride : i-stride+2]) counter.countSegment(p1, p2) if counter.isPointOnSegment { return counter.getLocation() } } return counter.getLocation() }
go
func LocatePointInRing(layout geom.Layout, p geom.Coord, ring []float64) location.Type { counter := rayCrossingCounter{p: p} stride := layout.Stride() for i := stride; i < len(ring); i += stride { p1 := geom.Coord(ring[i : i+2]) p2 := geom.Coord(ring[i-stride : i-stride+2]) counter.countSegment(p1, p2) if counter.isPointOnSegment { return counter.getLocation() } } return counter.getLocation() }
[ "func", "LocatePointInRing", "(", "layout", "geom", ".", "Layout", ",", "p", "geom", ".", "Coord", ",", "ring", "[", "]", "float64", ")", "location", ".", "Type", "{", "counter", ":=", "rayCrossingCounter", "{", "p", ":", "p", "}", "\n\n", "stride", ":=", "layout", ".", "Stride", "(", ")", "\n\n", "for", "i", ":=", "stride", ";", "i", "<", "len", "(", "ring", ")", ";", "i", "+=", "stride", "{", "p1", ":=", "geom", ".", "Coord", "(", "ring", "[", "i", ":", "i", "+", "2", "]", ")", "\n", "p2", ":=", "geom", ".", "Coord", "(", "ring", "[", "i", "-", "stride", ":", "i", "-", "stride", "+", "2", "]", ")", "\n\n", "counter", ".", "countSegment", "(", "p1", ",", "p2", ")", "\n", "if", "counter", ".", "isPointOnSegment", "{", "return", "counter", ".", "getLocation", "(", ")", "\n", "}", "\n", "}", "\n", "return", "counter", ".", "getLocation", "(", ")", "\n", "}" ]
// LocatePointInRing determine where the point is with regards to the ring
[ "LocatePointInRing", "determine", "where", "the", "point", "is", "with", "regards", "to", "the", "ring" ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/internal/raycrossing/ray-crossing-counter.go#L10-L25
151,712
twpayne/go-geom
xy/internal/raycrossing/ray-crossing-counter.go
countSegment
func (counter *rayCrossingCounter) countSegment(p1, p2 geom.Coord) { /** * For each segment, check if it crosses * a horizontal ray running from the test point in the positive x direction. */ // check if the segment is strictly to the left of the test point if p1[0] < counter.p[0] && p2[0] < counter.p[0] { return } // check if the point is equal to the current ring vertex if counter.p[0] == p2[0] && counter.p[1] == p2[1] { counter.isPointOnSegment = true return } /** * For horizontal segments, check if the point is on the segment. * Otherwise, horizontal segments are not counted. */ if p1[1] == counter.p[1] && p2[1] == counter.p[1] { minx := p1[0] maxx := p2[0] if minx > maxx { minx = p2[0] maxx = p1[0] } if counter.p[0] >= minx && counter.p[0] <= maxx { counter.isPointOnSegment = true } return } /** * Evaluate all non-horizontal segments which cross a horizontal ray to the * right of the test pt. To avoid double-counting shared vertices, we use the * convention that * <ul> * <li>an upward edge includes its starting endpoint, and excludes its * final endpoint * <li>a downward edge excludes its starting endpoint, and includes its * final endpoint * </ul> */ if ((p1[1] > counter.p[1]) && (p2[1] <= counter.p[1])) || ((p2[1] > counter.p[1]) && (p1[1] <= counter.p[1])) { // translate the segment so that the test point lies on the origin x1 := p1[0] - counter.p[0] y1 := p1[1] - counter.p[1] x2 := p2[0] - counter.p[0] y2 := p2[1] - counter.p[1] /** * The translated segment straddles the x-axis. Compute the sign of the * ordinate of intersection with the x-axis. (y2 != y1, so denominator * will never be 0.0) */ // double xIntSign = RobustDeterminant.signOfDet2x2(x1, y1, x2, y2) / (y2 // - y1); // MD - faster & more robust computation? xIntSign := robustdeterminate.SignOfDet2x2(x1, y1, x2, y2) if xIntSign == 0.0 { counter.isPointOnSegment = true return } if y2 < y1 { xIntSign = -xIntSign } // xsave = xInt; // System.out.println("xIntSign(" + x1 + ", " + y1 + ", " + x2 + ", " + y2 + " = " + xIntSign); // The segment crosses the ray if the sign is strictly positive. if xIntSign > 0.0 { counter.crossingCount++ } } }
go
func (counter *rayCrossingCounter) countSegment(p1, p2 geom.Coord) { /** * For each segment, check if it crosses * a horizontal ray running from the test point in the positive x direction. */ // check if the segment is strictly to the left of the test point if p1[0] < counter.p[0] && p2[0] < counter.p[0] { return } // check if the point is equal to the current ring vertex if counter.p[0] == p2[0] && counter.p[1] == p2[1] { counter.isPointOnSegment = true return } /** * For horizontal segments, check if the point is on the segment. * Otherwise, horizontal segments are not counted. */ if p1[1] == counter.p[1] && p2[1] == counter.p[1] { minx := p1[0] maxx := p2[0] if minx > maxx { minx = p2[0] maxx = p1[0] } if counter.p[0] >= minx && counter.p[0] <= maxx { counter.isPointOnSegment = true } return } /** * Evaluate all non-horizontal segments which cross a horizontal ray to the * right of the test pt. To avoid double-counting shared vertices, we use the * convention that * <ul> * <li>an upward edge includes its starting endpoint, and excludes its * final endpoint * <li>a downward edge excludes its starting endpoint, and includes its * final endpoint * </ul> */ if ((p1[1] > counter.p[1]) && (p2[1] <= counter.p[1])) || ((p2[1] > counter.p[1]) && (p1[1] <= counter.p[1])) { // translate the segment so that the test point lies on the origin x1 := p1[0] - counter.p[0] y1 := p1[1] - counter.p[1] x2 := p2[0] - counter.p[0] y2 := p2[1] - counter.p[1] /** * The translated segment straddles the x-axis. Compute the sign of the * ordinate of intersection with the x-axis. (y2 != y1, so denominator * will never be 0.0) */ // double xIntSign = RobustDeterminant.signOfDet2x2(x1, y1, x2, y2) / (y2 // - y1); // MD - faster & more robust computation? xIntSign := robustdeterminate.SignOfDet2x2(x1, y1, x2, y2) if xIntSign == 0.0 { counter.isPointOnSegment = true return } if y2 < y1 { xIntSign = -xIntSign } // xsave = xInt; // System.out.println("xIntSign(" + x1 + ", " + y1 + ", " + x2 + ", " + y2 + " = " + xIntSign); // The segment crosses the ray if the sign is strictly positive. if xIntSign > 0.0 { counter.crossingCount++ } } }
[ "func", "(", "counter", "*", "rayCrossingCounter", ")", "countSegment", "(", "p1", ",", "p2", "geom", ".", "Coord", ")", "{", "/**\n\t * For each segment, check if it crosses\n\t * a horizontal ray running from the test point in the positive x direction.\n\t */", "// check if the segment is strictly to the left of the test point", "if", "p1", "[", "0", "]", "<", "counter", ".", "p", "[", "0", "]", "&&", "p2", "[", "0", "]", "<", "counter", ".", "p", "[", "0", "]", "{", "return", "\n", "}", "\n\n", "// check if the point is equal to the current ring vertex", "if", "counter", ".", "p", "[", "0", "]", "==", "p2", "[", "0", "]", "&&", "counter", ".", "p", "[", "1", "]", "==", "p2", "[", "1", "]", "{", "counter", ".", "isPointOnSegment", "=", "true", "\n", "return", "\n", "}", "\n\n", "/**\n\t * For horizontal segments, check if the point is on the segment.\n\t * Otherwise, horizontal segments are not counted.\n\t */", "if", "p1", "[", "1", "]", "==", "counter", ".", "p", "[", "1", "]", "&&", "p2", "[", "1", "]", "==", "counter", ".", "p", "[", "1", "]", "{", "minx", ":=", "p1", "[", "0", "]", "\n", "maxx", ":=", "p2", "[", "0", "]", "\n", "if", "minx", ">", "maxx", "{", "minx", "=", "p2", "[", "0", "]", "\n", "maxx", "=", "p1", "[", "0", "]", "\n", "}", "\n", "if", "counter", ".", "p", "[", "0", "]", ">=", "minx", "&&", "counter", ".", "p", "[", "0", "]", "<=", "maxx", "{", "counter", ".", "isPointOnSegment", "=", "true", "\n", "}", "\n", "return", "\n", "}", "\n", "/**\n\t * Evaluate all non-horizontal segments which cross a horizontal ray to the\n\t * right of the test pt. To avoid double-counting shared vertices, we use the\n\t * convention that\n\t * <ul>\n\t * <li>an upward edge includes its starting endpoint, and excludes its\n\t * final endpoint\n\t * <li>a downward edge excludes its starting endpoint, and includes its\n\t * final endpoint\n\t * </ul>\n\t */", "if", "(", "(", "p1", "[", "1", "]", ">", "counter", ".", "p", "[", "1", "]", ")", "&&", "(", "p2", "[", "1", "]", "<=", "counter", ".", "p", "[", "1", "]", ")", ")", "||", "(", "(", "p2", "[", "1", "]", ">", "counter", ".", "p", "[", "1", "]", ")", "&&", "(", "p1", "[", "1", "]", "<=", "counter", ".", "p", "[", "1", "]", ")", ")", "{", "// translate the segment so that the test point lies on the origin", "x1", ":=", "p1", "[", "0", "]", "-", "counter", ".", "p", "[", "0", "]", "\n", "y1", ":=", "p1", "[", "1", "]", "-", "counter", ".", "p", "[", "1", "]", "\n", "x2", ":=", "p2", "[", "0", "]", "-", "counter", ".", "p", "[", "0", "]", "\n", "y2", ":=", "p2", "[", "1", "]", "-", "counter", ".", "p", "[", "1", "]", "\n\n", "/**\n\t\t * The translated segment straddles the x-axis. Compute the sign of the\n\t\t * ordinate of intersection with the x-axis. (y2 != y1, so denominator\n\t\t * will never be 0.0)\n\t\t */", "// double xIntSign = RobustDeterminant.signOfDet2x2(x1, y1, x2, y2) / (y2", "// - y1);", "// MD - faster & more robust computation?", "xIntSign", ":=", "robustdeterminate", ".", "SignOfDet2x2", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ")", "\n", "if", "xIntSign", "==", "0.0", "{", "counter", ".", "isPointOnSegment", "=", "true", "\n", "return", "\n", "}", "\n", "if", "y2", "<", "y1", "{", "xIntSign", "=", "-", "xIntSign", "\n", "}", "\n", "// xsave = xInt;", "// System.out.println(\"xIntSign(\" + x1 + \", \" + y1 + \", \" + x2 + \", \" + y2 + \" = \" + xIntSign);", "// The segment crosses the ray if the sign is strictly positive.", "if", "xIntSign", ">", "0.0", "{", "counter", ".", "crossingCount", "++", "\n", "}", "\n", "}", "\n", "}" ]
/** * Counts a segment * * @param p1 an endpoint of the segment * @param p2 another endpoint of the segment */
[ "Counts", "a", "segment" ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/internal/raycrossing/ray-crossing-counter.go#L62-L137
151,713
twpayne/go-geom
xy/line_centroid.go
NewLineCentroidCalculator
func NewLineCentroidCalculator(layout geom.Layout) *LineCentroidCalculator { return &LineCentroidCalculator{ layout: layout, stride: layout.Stride(), centSum: geom.Coord(make([]float64, layout.Stride())), } }
go
func NewLineCentroidCalculator(layout geom.Layout) *LineCentroidCalculator { return &LineCentroidCalculator{ layout: layout, stride: layout.Stride(), centSum: geom.Coord(make([]float64, layout.Stride())), } }
[ "func", "NewLineCentroidCalculator", "(", "layout", "geom", ".", "Layout", ")", "*", "LineCentroidCalculator", "{", "return", "&", "LineCentroidCalculator", "{", "layout", ":", "layout", ",", "stride", ":", "layout", ".", "Stride", "(", ")", ",", "centSum", ":", "geom", ".", "Coord", "(", "make", "(", "[", "]", "float64", ",", "layout", ".", "Stride", "(", ")", ")", ")", ",", "}", "\n", "}" ]
// NewLineCentroidCalculator creates a new instance of the calculator. // Once a calculator is created polygons, linestrings or linear rings can be added and the // GetCentroid method can be used at any point to get the current centroid // the centroid will naturally change each time a geometry is added
[ "NewLineCentroidCalculator", "creates", "a", "new", "instance", "of", "the", "calculator", ".", "Once", "a", "calculator", "is", "created", "polygons", "linestrings", "or", "linear", "rings", "can", "be", "added", "and", "the", "GetCentroid", "method", "can", "be", "used", "at", "any", "point", "to", "get", "the", "current", "centroid", "the", "centroid", "will", "naturally", "change", "each", "time", "a", "geometry", "is", "added" ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/line_centroid.go#L64-L70
151,714
twpayne/go-geom
xy/line_centroid.go
AddPolygon
func (calc *LineCentroidCalculator) AddPolygon(polygon *geom.Polygon) *LineCentroidCalculator { for i := 0; i < polygon.NumLinearRings(); i++ { calc.AddLinearRing(polygon.LinearRing(i)) } return calc }
go
func (calc *LineCentroidCalculator) AddPolygon(polygon *geom.Polygon) *LineCentroidCalculator { for i := 0; i < polygon.NumLinearRings(); i++ { calc.AddLinearRing(polygon.LinearRing(i)) } return calc }
[ "func", "(", "calc", "*", "LineCentroidCalculator", ")", "AddPolygon", "(", "polygon", "*", "geom", ".", "Polygon", ")", "*", "LineCentroidCalculator", "{", "for", "i", ":=", "0", ";", "i", "<", "polygon", ".", "NumLinearRings", "(", ")", ";", "i", "++", "{", "calc", ".", "AddLinearRing", "(", "polygon", ".", "LinearRing", "(", "i", ")", ")", "\n", "}", "\n\n", "return", "calc", "\n", "}" ]
// AddPolygon adds a Polygon to the calculation.
[ "AddPolygon", "adds", "a", "Polygon", "to", "the", "calculation", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/line_centroid.go#L81-L87
151,715
twpayne/go-geom
xy/line_centroid.go
AddLine
func (calc *LineCentroidCalculator) AddLine(line *geom.LineString) *LineCentroidCalculator { coords := line.FlatCoords() calc.addLine(coords, 0, len(coords)) return calc }
go
func (calc *LineCentroidCalculator) AddLine(line *geom.LineString) *LineCentroidCalculator { coords := line.FlatCoords() calc.addLine(coords, 0, len(coords)) return calc }
[ "func", "(", "calc", "*", "LineCentroidCalculator", ")", "AddLine", "(", "line", "*", "geom", ".", "LineString", ")", "*", "LineCentroidCalculator", "{", "coords", ":=", "line", ".", "FlatCoords", "(", ")", "\n", "calc", ".", "addLine", "(", "coords", ",", "0", ",", "len", "(", "coords", ")", ")", "\n", "return", "calc", "\n", "}" ]
// AddLine adds a LineString to the current calculation
[ "AddLine", "adds", "a", "LineString", "to", "the", "current", "calculation" ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/line_centroid.go#L90-L94
151,716
twpayne/go-geom
xy/line_centroid.go
AddLinearRing
func (calc *LineCentroidCalculator) AddLinearRing(line *geom.LinearRing) *LineCentroidCalculator { coords := line.FlatCoords() calc.addLine(coords, 0, len(coords)) return calc }
go
func (calc *LineCentroidCalculator) AddLinearRing(line *geom.LinearRing) *LineCentroidCalculator { coords := line.FlatCoords() calc.addLine(coords, 0, len(coords)) return calc }
[ "func", "(", "calc", "*", "LineCentroidCalculator", ")", "AddLinearRing", "(", "line", "*", "geom", ".", "LinearRing", ")", "*", "LineCentroidCalculator", "{", "coords", ":=", "line", ".", "FlatCoords", "(", ")", "\n", "calc", ".", "addLine", "(", "coords", ",", "0", ",", "len", "(", "coords", ")", ")", "\n", "return", "calc", "\n", "}" ]
// AddLinearRing adds a LinearRing to the current calculation
[ "AddLinearRing", "adds", "a", "LinearRing", "to", "the", "current", "calculation" ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/line_centroid.go#L97-L101
151,717
twpayne/go-geom
xy/cga.go
IsOnLine
func IsOnLine(layout geom.Layout, point geom.Coord, lineSegmentCoordinates []float64) bool { stride := layout.Stride() if len(lineSegmentCoordinates) < (2 * stride) { panic(fmt.Sprintf("At least two coordinates are required in the lineSegmentsCoordinates array in 'algorithms.IsOnLine', was: %v", lineSegmentCoordinates)) } strategy := lineintersector.RobustLineIntersector{} for i := stride; i < len(lineSegmentCoordinates); i += stride { segmentStart := lineSegmentCoordinates[i-stride : i-stride+2] segmentEnd := lineSegmentCoordinates[i : i+2] if lineintersector.PointIntersectsLine(strategy, point, geom.Coord(segmentStart), geom.Coord(segmentEnd)) { return true } } return false }
go
func IsOnLine(layout geom.Layout, point geom.Coord, lineSegmentCoordinates []float64) bool { stride := layout.Stride() if len(lineSegmentCoordinates) < (2 * stride) { panic(fmt.Sprintf("At least two coordinates are required in the lineSegmentsCoordinates array in 'algorithms.IsOnLine', was: %v", lineSegmentCoordinates)) } strategy := lineintersector.RobustLineIntersector{} for i := stride; i < len(lineSegmentCoordinates); i += stride { segmentStart := lineSegmentCoordinates[i-stride : i-stride+2] segmentEnd := lineSegmentCoordinates[i : i+2] if lineintersector.PointIntersectsLine(strategy, point, geom.Coord(segmentStart), geom.Coord(segmentEnd)) { return true } } return false }
[ "func", "IsOnLine", "(", "layout", "geom", ".", "Layout", ",", "point", "geom", ".", "Coord", ",", "lineSegmentCoordinates", "[", "]", "float64", ")", "bool", "{", "stride", ":=", "layout", ".", "Stride", "(", ")", "\n", "if", "len", "(", "lineSegmentCoordinates", ")", "<", "(", "2", "*", "stride", ")", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "lineSegmentCoordinates", ")", ")", "\n", "}", "\n", "strategy", ":=", "lineintersector", ".", "RobustLineIntersector", "{", "}", "\n\n", "for", "i", ":=", "stride", ";", "i", "<", "len", "(", "lineSegmentCoordinates", ")", ";", "i", "+=", "stride", "{", "segmentStart", ":=", "lineSegmentCoordinates", "[", "i", "-", "stride", ":", "i", "-", "stride", "+", "2", "]", "\n", "segmentEnd", ":=", "lineSegmentCoordinates", "[", "i", ":", "i", "+", "2", "]", "\n\n", "if", "lineintersector", ".", "PointIntersectsLine", "(", "strategy", ",", "point", ",", "geom", ".", "Coord", "(", "segmentStart", ")", ",", "geom", ".", "Coord", "(", "segmentEnd", ")", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsOnLine tests whether a point lies on the line segments defined by a list of // coordinates. // // Returns true if the point is a vertex of the line or lies in the interior // of a line segment in the linestring
[ "IsOnLine", "tests", "whether", "a", "point", "lies", "on", "the", "line", "segments", "defined", "by", "a", "list", "of", "coordinates", ".", "Returns", "true", "if", "the", "point", "is", "a", "vertex", "of", "the", "line", "or", "lies", "in", "the", "interior", "of", "a", "line", "segment", "in", "the", "linestring" ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/cga.go#L63-L79
151,718
twpayne/go-geom
xy/cga.go
DistanceFromPointToLineString
func DistanceFromPointToLineString(layout geom.Layout, p geom.Coord, line []float64) float64 { if len(line) < 2 { panic(fmt.Sprintf("Line array must contain at least one vertex: %v", line)) } // this handles the case of length = 1 firstPoint := line[0:2] minDistance := internal.Distance2D(p, firstPoint) stride := layout.Stride() for i := 0; i < len(line)-stride; i += stride { point1 := geom.Coord(line[i : i+2]) point2 := geom.Coord(line[i+stride : i+stride+2]) dist := DistanceFromPointToLine(p, point1, point2) if dist < minDistance { minDistance = dist } } return minDistance }
go
func DistanceFromPointToLineString(layout geom.Layout, p geom.Coord, line []float64) float64 { if len(line) < 2 { panic(fmt.Sprintf("Line array must contain at least one vertex: %v", line)) } // this handles the case of length = 1 firstPoint := line[0:2] minDistance := internal.Distance2D(p, firstPoint) stride := layout.Stride() for i := 0; i < len(line)-stride; i += stride { point1 := geom.Coord(line[i : i+2]) point2 := geom.Coord(line[i+stride : i+stride+2]) dist := DistanceFromPointToLine(p, point1, point2) if dist < minDistance { minDistance = dist } } return minDistance }
[ "func", "DistanceFromPointToLineString", "(", "layout", "geom", ".", "Layout", ",", "p", "geom", ".", "Coord", ",", "line", "[", "]", "float64", ")", "float64", "{", "if", "len", "(", "line", ")", "<", "2", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "line", ")", ")", "\n", "}", "\n", "// this handles the case of length = 1", "firstPoint", ":=", "line", "[", "0", ":", "2", "]", "\n", "minDistance", ":=", "internal", ".", "Distance2D", "(", "p", ",", "firstPoint", ")", "\n", "stride", ":=", "layout", ".", "Stride", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "line", ")", "-", "stride", ";", "i", "+=", "stride", "{", "point1", ":=", "geom", ".", "Coord", "(", "line", "[", "i", ":", "i", "+", "2", "]", ")", "\n", "point2", ":=", "geom", ".", "Coord", "(", "line", "[", "i", "+", "stride", ":", "i", "+", "stride", "+", "2", "]", ")", "\n", "dist", ":=", "DistanceFromPointToLine", "(", "p", ",", "point1", ",", "point2", ")", "\n", "if", "dist", "<", "minDistance", "{", "minDistance", "=", "dist", "\n", "}", "\n", "}", "\n", "return", "minDistance", "\n", "}" ]
// DistanceFromPointToLineString computes the distance from a point to a sequence of line segments. // // Param p - a point // Param line - a sequence of contiguous line segments defined by their vertices
[ "DistanceFromPointToLineString", "computes", "the", "distance", "from", "a", "point", "to", "a", "sequence", "of", "line", "segments", ".", "Param", "p", "-", "a", "point", "Param", "line", "-", "a", "sequence", "of", "contiguous", "line", "segments", "defined", "by", "their", "vertices" ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/cga.go#L231-L248
151,719
twpayne/go-geom
xy/cga.go
SignedArea
func SignedArea(layout geom.Layout, ring []float64) float64 { stride := layout.Stride() if len(ring) < 3*stride { return 0.0 } sum := 0.0 // Based on the Shoelace formula. // http://en.wikipedia.org/wiki/Shoelace_formula x0 := ring[0] lenMinusOnePoint := len(ring) - stride for i := stride; i < lenMinusOnePoint; i += stride { x := ring[i] - x0 y1 := ring[i+stride+1] y2 := ring[i-stride+1] sum += x * (y2 - y1) } return sum / 2.0 }
go
func SignedArea(layout geom.Layout, ring []float64) float64 { stride := layout.Stride() if len(ring) < 3*stride { return 0.0 } sum := 0.0 // Based on the Shoelace formula. // http://en.wikipedia.org/wiki/Shoelace_formula x0 := ring[0] lenMinusOnePoint := len(ring) - stride for i := stride; i < lenMinusOnePoint; i += stride { x := ring[i] - x0 y1 := ring[i+stride+1] y2 := ring[i-stride+1] sum += x * (y2 - y1) } return sum / 2.0 }
[ "func", "SignedArea", "(", "layout", "geom", ".", "Layout", ",", "ring", "[", "]", "float64", ")", "float64", "{", "stride", ":=", "layout", ".", "Stride", "(", ")", "\n", "if", "len", "(", "ring", ")", "<", "3", "*", "stride", "{", "return", "0.0", "\n", "}", "\n", "sum", ":=", "0.0", "\n", "// Based on the Shoelace formula.", "// http://en.wikipedia.org/wiki/Shoelace_formula", "x0", ":=", "ring", "[", "0", "]", "\n", "lenMinusOnePoint", ":=", "len", "(", "ring", ")", "-", "stride", "\n", "for", "i", ":=", "stride", ";", "i", "<", "lenMinusOnePoint", ";", "i", "+=", "stride", "{", "x", ":=", "ring", "[", "i", "]", "-", "x0", "\n", "y1", ":=", "ring", "[", "i", "+", "stride", "+", "1", "]", "\n", "y2", ":=", "ring", "[", "i", "-", "stride", "+", "1", "]", "\n", "sum", "+=", "x", "*", "(", "y2", "-", "y1", ")", "\n", "}", "\n", "return", "sum", "/", "2.0", "\n", "}" ]
// SignedArea computes the signed area for a ring. The signed area is positive if the // ring is oriented CW, negative if the ring is oriented CCW, and zero if the // ring is degenerate or flat.
[ "SignedArea", "computes", "the", "signed", "area", "for", "a", "ring", ".", "The", "signed", "area", "is", "positive", "if", "the", "ring", "is", "oriented", "CW", "negative", "if", "the", "ring", "is", "oriented", "CCW", "and", "zero", "if", "the", "ring", "is", "degenerate", "or", "flat", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/cga.go#L328-L345
151,720
twpayne/go-geom
xy/cga.go
Distance
func Distance(c1, c2 geom.Coord) float64 { return internal.Distance2D(c1, c2) }
go
func Distance(c1, c2 geom.Coord) float64 { return internal.Distance2D(c1, c2) }
[ "func", "Distance", "(", "c1", ",", "c2", "geom", ".", "Coord", ")", "float64", "{", "return", "internal", ".", "Distance2D", "(", "c1", ",", "c2", ")", "\n", "}" ]
// Distance calculates the 2d distance between the two coordinates
[ "Distance", "calculates", "the", "2d", "distance", "between", "the", "two", "coordinates" ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/cga.go#L369-L371
151,721
twpayne/go-geom
xy/convex_hull.go
ConvexHull
func ConvexHull(geometry geom.T) geom.T { // copy coords because the algorithm reorders them calc := convexHullCalculator{ layout: geometry.Layout(), stride: geometry.Layout().Stride(), inputPts: geometry.FlatCoords(), } return calc.getConvexHull() }
go
func ConvexHull(geometry geom.T) geom.T { // copy coords because the algorithm reorders them calc := convexHullCalculator{ layout: geometry.Layout(), stride: geometry.Layout().Stride(), inputPts: geometry.FlatCoords(), } return calc.getConvexHull() }
[ "func", "ConvexHull", "(", "geometry", "geom", ".", "T", ")", "geom", ".", "T", "{", "// copy coords because the algorithm reorders them", "calc", ":=", "convexHullCalculator", "{", "layout", ":", "geometry", ".", "Layout", "(", ")", ",", "stride", ":", "geometry", ".", "Layout", "(", ")", ".", "Stride", "(", ")", ",", "inputPts", ":", "geometry", ".", "FlatCoords", "(", ")", ",", "}", "\n\n", "return", "calc", ".", "getConvexHull", "(", ")", "\n", "}" ]
// ConvexHull computes the convex hull of the geometry. // A convex hull is the smallest convex geometry that contains // all the points in the input geometry // Uses the Graham Scan algorithm
[ "ConvexHull", "computes", "the", "convex", "hull", "of", "the", "geometry", ".", "A", "convex", "hull", "is", "the", "smallest", "convex", "geometry", "that", "contains", "all", "the", "points", "in", "the", "input", "geometry", "Uses", "the", "Graham", "Scan", "algorithm" ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/convex_hull.go#L24-L33
151,722
twpayne/go-geom
xy/convex_hull.go
ConvexHullFlat
func ConvexHullFlat(layout geom.Layout, coords []float64) geom.T { calc := convexHullCalculator{ inputPts: coords, layout: layout, stride: layout.Stride(), } return calc.getConvexHull() }
go
func ConvexHullFlat(layout geom.Layout, coords []float64) geom.T { calc := convexHullCalculator{ inputPts: coords, layout: layout, stride: layout.Stride(), } return calc.getConvexHull() }
[ "func", "ConvexHullFlat", "(", "layout", "geom", ".", "Layout", ",", "coords", "[", "]", "float64", ")", "geom", ".", "T", "{", "calc", ":=", "convexHullCalculator", "{", "inputPts", ":", "coords", ",", "layout", ":", "layout", ",", "stride", ":", "layout", ".", "Stride", "(", ")", ",", "}", "\n", "return", "calc", ".", "getConvexHull", "(", ")", "\n", "}" ]
// ConvexHullFlat computes the convex hull of the geometry. // A convex hull is the smallest convex geometry that contains // all the points in the input coordinates // Uses the Graham Scan algorithm
[ "ConvexHullFlat", "computes", "the", "convex", "hull", "of", "the", "geometry", ".", "A", "convex", "hull", "is", "the", "smallest", "convex", "geometry", "that", "contains", "all", "the", "points", "in", "the", "input", "coordinates", "Uses", "the", "Graham", "Scan", "algorithm" ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/convex_hull.go#L39-L46
151,723
twpayne/go-geom
flat.go
Bounds
func (g *geom0) Bounds() *Bounds { return NewBounds(g.layout).extendFlatCoords(g.flatCoords, 0, len(g.flatCoords), g.stride) }
go
func (g *geom0) Bounds() *Bounds { return NewBounds(g.layout).extendFlatCoords(g.flatCoords, 0, len(g.flatCoords), g.stride) }
[ "func", "(", "g", "*", "geom0", ")", "Bounds", "(", ")", "*", "Bounds", "{", "return", "NewBounds", "(", "g", ".", "layout", ")", ".", "extendFlatCoords", "(", "g", ".", "flatCoords", ",", "0", ",", "len", "(", "g", ".", "flatCoords", ")", ",", "g", ".", "stride", ")", "\n", "}" ]
// Bounds returns the bounds of g.
[ "Bounds", "returns", "the", "bounds", "of", "g", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/flat.go#L27-L29
151,724
twpayne/go-geom
flat.go
Coords
func (g *geom0) Coords() Coord { return inflate0(g.flatCoords, 0, len(g.flatCoords), g.stride) }
go
func (g *geom0) Coords() Coord { return inflate0(g.flatCoords, 0, len(g.flatCoords), g.stride) }
[ "func", "(", "g", "*", "geom0", ")", "Coords", "(", ")", "Coord", "{", "return", "inflate0", "(", "g", ".", "flatCoords", ",", "0", ",", "len", "(", "g", ".", "flatCoords", ")", ",", "g", ".", "stride", ")", "\n", "}" ]
// Coords returns all the coordinates in g, i.e. a single coordinate.
[ "Coords", "returns", "all", "the", "coordinates", "in", "g", "i", ".", "e", ".", "a", "single", "coordinate", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/flat.go#L32-L34
151,725
twpayne/go-geom
flat.go
Reserve
func (g *geom0) Reserve(n int) { if cap(g.flatCoords) < n*g.stride { fcs := make([]float64, len(g.flatCoords), n*g.stride) copy(fcs, g.flatCoords) g.flatCoords = fcs } }
go
func (g *geom0) Reserve(n int) { if cap(g.flatCoords) < n*g.stride { fcs := make([]float64, len(g.flatCoords), n*g.stride) copy(fcs, g.flatCoords) g.flatCoords = fcs } }
[ "func", "(", "g", "*", "geom0", ")", "Reserve", "(", "n", "int", ")", "{", "if", "cap", "(", "g", ".", "flatCoords", ")", "<", "n", "*", "g", ".", "stride", "{", "fcs", ":=", "make", "(", "[", "]", "float64", ",", "len", "(", "g", ".", "flatCoords", ")", ",", "n", "*", "g", ".", "stride", ")", "\n", "copy", "(", "fcs", ",", "g", ".", "flatCoords", ")", "\n", "g", ".", "flatCoords", "=", "fcs", "\n", "}", "\n", "}" ]
// Reserve reserves space in g for n coordinates.
[ "Reserve", "reserves", "space", "in", "g", "for", "n", "coordinates", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/flat.go#L63-L69
151,726
twpayne/go-geom
flat.go
Coord
func (g *geom1) Coord(i int) Coord { return g.flatCoords[i*g.stride : (i+1)*g.stride] }
go
func (g *geom1) Coord(i int) Coord { return g.flatCoords[i*g.stride : (i+1)*g.stride] }
[ "func", "(", "g", "*", "geom1", ")", "Coord", "(", "i", "int", ")", "Coord", "{", "return", "g", ".", "flatCoords", "[", "i", "*", "g", ".", "stride", ":", "(", "i", "+", "1", ")", "*", "g", ".", "stride", "]", "\n", "}" ]
// Coord returns the ith coord of g.
[ "Coord", "returns", "the", "ith", "coord", "of", "g", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/flat.go#L104-L106
151,727
twpayne/go-geom
flat.go
Coords
func (g *geom1) Coords() []Coord { return inflate1(g.flatCoords, 0, len(g.flatCoords), g.stride) }
go
func (g *geom1) Coords() []Coord { return inflate1(g.flatCoords, 0, len(g.flatCoords), g.stride) }
[ "func", "(", "g", "*", "geom1", ")", "Coords", "(", ")", "[", "]", "Coord", "{", "return", "inflate1", "(", "g", ".", "flatCoords", ",", "0", ",", "len", "(", "g", ".", "flatCoords", ")", ",", "g", ".", "stride", ")", "\n", "}" ]
// Coords unpacks and returns all of g's coordinates.
[ "Coords", "unpacks", "and", "returns", "all", "of", "g", "s", "coordinates", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/flat.go#L109-L111
151,728
twpayne/go-geom
flat.go
Coords
func (g *geom2) Coords() [][]Coord { return inflate2(g.flatCoords, 0, g.ends, g.stride) }
go
func (g *geom2) Coords() [][]Coord { return inflate2(g.flatCoords, 0, g.ends, g.stride) }
[ "func", "(", "g", "*", "geom2", ")", "Coords", "(", ")", "[", "]", "[", "]", "Coord", "{", "return", "inflate2", "(", "g", ".", "flatCoords", ",", "0", ",", "g", ".", "ends", ",", "g", ".", "stride", ")", "\n", "}" ]
// Coords returns all of g's coordinates.
[ "Coords", "returns", "all", "of", "g", "s", "coordinates", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/flat.go#L141-L143
151,729
twpayne/go-geom
flat.go
Coords
func (g *geom3) Coords() [][][]Coord { return inflate3(g.flatCoords, 0, g.endss, g.stride) }
go
func (g *geom3) Coords() [][][]Coord { return inflate3(g.flatCoords, 0, g.endss, g.stride) }
[ "func", "(", "g", "*", "geom3", ")", "Coords", "(", ")", "[", "]", "[", "]", "[", "]", "Coord", "{", "return", "inflate3", "(", "g", ".", "flatCoords", ",", "0", ",", "g", ".", "endss", ",", "g", ".", "stride", ")", "\n", "}" ]
// Coords returns all the coordinates in g.
[ "Coords", "returns", "all", "the", "coordinates", "in", "g", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/flat.go#L189-L191
151,730
twpayne/go-geom
xyz/vector.go
VectorDot
func VectorDot(v1Start, v1End, v2Start, v2End geom.Coord) float64 { v1Startv2Endx := v1End[0] - v1Start[0] v1Startv2Endy := v1End[1] - v1Start[1] v1Startv2Endz := v1End[2] - v1Start[2] v2Startv2Endx := v2End[0] - v2Start[0] v2Startv2Endy := v2End[1] - v2Start[1] v2Startv2Endz := v2End[2] - v2Start[2] return v1Startv2Endx*v2Startv2Endx + v1Startv2Endy*v2Startv2Endy + v1Startv2Endz*v2Startv2Endz }
go
func VectorDot(v1Start, v1End, v2Start, v2End geom.Coord) float64 { v1Startv2Endx := v1End[0] - v1Start[0] v1Startv2Endy := v1End[1] - v1Start[1] v1Startv2Endz := v1End[2] - v1Start[2] v2Startv2Endx := v2End[0] - v2Start[0] v2Startv2Endy := v2End[1] - v2Start[1] v2Startv2Endz := v2End[2] - v2Start[2] return v1Startv2Endx*v2Startv2Endx + v1Startv2Endy*v2Startv2Endy + v1Startv2Endz*v2Startv2Endz }
[ "func", "VectorDot", "(", "v1Start", ",", "v1End", ",", "v2Start", ",", "v2End", "geom", ".", "Coord", ")", "float64", "{", "v1Startv2Endx", ":=", "v1End", "[", "0", "]", "-", "v1Start", "[", "0", "]", "\n", "v1Startv2Endy", ":=", "v1End", "[", "1", "]", "-", "v1Start", "[", "1", "]", "\n", "v1Startv2Endz", ":=", "v1End", "[", "2", "]", "-", "v1Start", "[", "2", "]", "\n", "v2Startv2Endx", ":=", "v2End", "[", "0", "]", "-", "v2Start", "[", "0", "]", "\n", "v2Startv2Endy", ":=", "v2End", "[", "1", "]", "-", "v2Start", "[", "1", "]", "\n", "v2Startv2Endz", ":=", "v2End", "[", "2", "]", "-", "v2Start", "[", "2", "]", "\n", "return", "v1Startv2Endx", "*", "v2Startv2Endx", "+", "v1Startv2Endy", "*", "v2Startv2Endy", "+", "v1Startv2Endz", "*", "v2Startv2Endz", "\n", "}" ]
// VectorDot calculates the dot product of two vectors
[ "VectorDot", "calculates", "the", "dot", "product", "of", "two", "vectors" ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xyz/vector.go#L10-L18
151,731
twpayne/go-geom
xyz/vector.go
VectorNormalize
func VectorNormalize(vector geom.Coord) geom.Coord { vLen := VectorLength(vector) return geom.Coord{vector[0] / vLen, vector[1] / vLen, vector[2] / vLen} }
go
func VectorNormalize(vector geom.Coord) geom.Coord { vLen := VectorLength(vector) return geom.Coord{vector[0] / vLen, vector[1] / vLen, vector[2] / vLen} }
[ "func", "VectorNormalize", "(", "vector", "geom", ".", "Coord", ")", "geom", ".", "Coord", "{", "vLen", ":=", "VectorLength", "(", "vector", ")", "\n", "return", "geom", ".", "Coord", "{", "vector", "[", "0", "]", "/", "vLen", ",", "vector", "[", "1", "]", "/", "vLen", ",", "vector", "[", "2", "]", "/", "vLen", "}", "\n", "}" ]
// VectorNormalize creates a coordinate that is the normalized vector from 0,0,0 to vector
[ "VectorNormalize", "creates", "a", "coordinate", "that", "is", "the", "normalized", "vector", "from", "0", "0", "0", "to", "vector" ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xyz/vector.go#L21-L24
151,732
twpayne/go-geom
xyz/vector.go
VectorLength
func VectorLength(vector geom.Coord) float64 { return math.Sqrt(vector[0]*vector[0] + vector[1]*vector[1] + vector[2]*vector[2]) }
go
func VectorLength(vector geom.Coord) float64 { return math.Sqrt(vector[0]*vector[0] + vector[1]*vector[1] + vector[2]*vector[2]) }
[ "func", "VectorLength", "(", "vector", "geom", ".", "Coord", ")", "float64", "{", "return", "math", ".", "Sqrt", "(", "vector", "[", "0", "]", "*", "vector", "[", "0", "]", "+", "vector", "[", "1", "]", "*", "vector", "[", "1", "]", "+", "vector", "[", "2", "]", "*", "vector", "[", "2", "]", ")", "\n", "}" ]
// VectorLength calculates the length of the vector from 0,0,0 to vector
[ "VectorLength", "calculates", "the", "length", "of", "the", "vector", "from", "0", "0", "0", "to", "vector" ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xyz/vector.go#L27-L29
151,733
twpayne/go-geom
encoding/kml/kml.go
Encode
func Encode(g geom.T) (kml.Element, error) { switch g := g.(type) { case *geom.Point: return EncodePoint(g), nil case *geom.LineString: return EncodeLineString(g), nil case *geom.LinearRing: return EncodeLinearRing(g), nil case *geom.MultiLineString: return EncodeMultiLineString(g), nil case *geom.MultiPoint: return EncodeMultiPoint(g), nil case *geom.MultiPolygon: return EncodeMultiPolygon(g), nil case *geom.Polygon: return EncodePolygon(g), nil case *geom.GeometryCollection: return EncodeGeometryCollection(g) default: return nil, geom.ErrUnsupportedType{Value: g} } }
go
func Encode(g geom.T) (kml.Element, error) { switch g := g.(type) { case *geom.Point: return EncodePoint(g), nil case *geom.LineString: return EncodeLineString(g), nil case *geom.LinearRing: return EncodeLinearRing(g), nil case *geom.MultiLineString: return EncodeMultiLineString(g), nil case *geom.MultiPoint: return EncodeMultiPoint(g), nil case *geom.MultiPolygon: return EncodeMultiPolygon(g), nil case *geom.Polygon: return EncodePolygon(g), nil case *geom.GeometryCollection: return EncodeGeometryCollection(g) default: return nil, geom.ErrUnsupportedType{Value: g} } }
[ "func", "Encode", "(", "g", "geom", ".", "T", ")", "(", "kml", ".", "Element", ",", "error", ")", "{", "switch", "g", ":=", "g", ".", "(", "type", ")", "{", "case", "*", "geom", ".", "Point", ":", "return", "EncodePoint", "(", "g", ")", ",", "nil", "\n", "case", "*", "geom", ".", "LineString", ":", "return", "EncodeLineString", "(", "g", ")", ",", "nil", "\n", "case", "*", "geom", ".", "LinearRing", ":", "return", "EncodeLinearRing", "(", "g", ")", ",", "nil", "\n", "case", "*", "geom", ".", "MultiLineString", ":", "return", "EncodeMultiLineString", "(", "g", ")", ",", "nil", "\n", "case", "*", "geom", ".", "MultiPoint", ":", "return", "EncodeMultiPoint", "(", "g", ")", ",", "nil", "\n", "case", "*", "geom", ".", "MultiPolygon", ":", "return", "EncodeMultiPolygon", "(", "g", ")", ",", "nil", "\n", "case", "*", "geom", ".", "Polygon", ":", "return", "EncodePolygon", "(", "g", ")", ",", "nil", "\n", "case", "*", "geom", ".", "GeometryCollection", ":", "return", "EncodeGeometryCollection", "(", "g", ")", "\n", "default", ":", "return", "nil", ",", "geom", ".", "ErrUnsupportedType", "{", "Value", ":", "g", "}", "\n", "}", "\n", "}" ]
// Encode encodes an arbitrary geometry.
[ "Encode", "encodes", "an", "arbitrary", "geometry", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/encoding/kml/kml.go#L10-L31
151,734
twpayne/go-geom
encoding/kml/kml.go
EncodeLineString
func EncodeLineString(ls *geom.LineString) kml.Element { flatCoords := ls.FlatCoords() return kml.LineString(kml.CoordinatesFlat(flatCoords, 0, len(flatCoords), ls.Stride(), dim(ls.Layout()))) }
go
func EncodeLineString(ls *geom.LineString) kml.Element { flatCoords := ls.FlatCoords() return kml.LineString(kml.CoordinatesFlat(flatCoords, 0, len(flatCoords), ls.Stride(), dim(ls.Layout()))) }
[ "func", "EncodeLineString", "(", "ls", "*", "geom", ".", "LineString", ")", "kml", ".", "Element", "{", "flatCoords", ":=", "ls", ".", "FlatCoords", "(", ")", "\n", "return", "kml", ".", "LineString", "(", "kml", ".", "CoordinatesFlat", "(", "flatCoords", ",", "0", ",", "len", "(", "flatCoords", ")", ",", "ls", ".", "Stride", "(", ")", ",", "dim", "(", "ls", ".", "Layout", "(", ")", ")", ")", ")", "\n", "}" ]
// EncodeLineString encodes a LineString.
[ "EncodeLineString", "encodes", "a", "LineString", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/encoding/kml/kml.go#L34-L37
151,735
twpayne/go-geom
encoding/kml/kml.go
EncodeLinearRing
func EncodeLinearRing(lr *geom.LinearRing) kml.Element { flatCoords := lr.FlatCoords() return kml.LinearRing(kml.CoordinatesFlat(flatCoords, 0, len(flatCoords), lr.Stride(), dim(lr.Layout()))) }
go
func EncodeLinearRing(lr *geom.LinearRing) kml.Element { flatCoords := lr.FlatCoords() return kml.LinearRing(kml.CoordinatesFlat(flatCoords, 0, len(flatCoords), lr.Stride(), dim(lr.Layout()))) }
[ "func", "EncodeLinearRing", "(", "lr", "*", "geom", ".", "LinearRing", ")", "kml", ".", "Element", "{", "flatCoords", ":=", "lr", ".", "FlatCoords", "(", ")", "\n", "return", "kml", ".", "LinearRing", "(", "kml", ".", "CoordinatesFlat", "(", "flatCoords", ",", "0", ",", "len", "(", "flatCoords", ")", ",", "lr", ".", "Stride", "(", ")", ",", "dim", "(", "lr", ".", "Layout", "(", ")", ")", ")", ")", "\n", "}" ]
// EncodeLinearRing encodes a LinearRing.
[ "EncodeLinearRing", "encodes", "a", "LinearRing", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/encoding/kml/kml.go#L40-L43
151,736
twpayne/go-geom
encoding/kml/kml.go
EncodeMultiLineString
func EncodeMultiLineString(mls *geom.MultiLineString) kml.Element { lineStrings := make([]kml.Element, mls.NumLineStrings()) flatCoords := mls.FlatCoords() ends := mls.Ends() stride := mls.Stride() d := dim(mls.Layout()) offset := 0 for i, end := range ends { lineStrings[i] = kml.LineString(kml.CoordinatesFlat(flatCoords, offset, end, stride, d)) offset = end } return kml.MultiGeometry(lineStrings...) }
go
func EncodeMultiLineString(mls *geom.MultiLineString) kml.Element { lineStrings := make([]kml.Element, mls.NumLineStrings()) flatCoords := mls.FlatCoords() ends := mls.Ends() stride := mls.Stride() d := dim(mls.Layout()) offset := 0 for i, end := range ends { lineStrings[i] = kml.LineString(kml.CoordinatesFlat(flatCoords, offset, end, stride, d)) offset = end } return kml.MultiGeometry(lineStrings...) }
[ "func", "EncodeMultiLineString", "(", "mls", "*", "geom", ".", "MultiLineString", ")", "kml", ".", "Element", "{", "lineStrings", ":=", "make", "(", "[", "]", "kml", ".", "Element", ",", "mls", ".", "NumLineStrings", "(", ")", ")", "\n", "flatCoords", ":=", "mls", ".", "FlatCoords", "(", ")", "\n", "ends", ":=", "mls", ".", "Ends", "(", ")", "\n", "stride", ":=", "mls", ".", "Stride", "(", ")", "\n", "d", ":=", "dim", "(", "mls", ".", "Layout", "(", ")", ")", "\n", "offset", ":=", "0", "\n", "for", "i", ",", "end", ":=", "range", "ends", "{", "lineStrings", "[", "i", "]", "=", "kml", ".", "LineString", "(", "kml", ".", "CoordinatesFlat", "(", "flatCoords", ",", "offset", ",", "end", ",", "stride", ",", "d", ")", ")", "\n", "offset", "=", "end", "\n", "}", "\n", "return", "kml", ".", "MultiGeometry", "(", "lineStrings", "...", ")", "\n", "}" ]
// EncodeMultiLineString encodes a MultiLineString.
[ "EncodeMultiLineString", "encodes", "a", "MultiLineString", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/encoding/kml/kml.go#L46-L58
151,737
twpayne/go-geom
encoding/kml/kml.go
EncodeMultiPoint
func EncodeMultiPoint(mp *geom.MultiPoint) kml.Element { points := make([]kml.Element, mp.NumPoints()) flatCoords := mp.FlatCoords() stride := mp.Stride() d := dim(mp.Layout()) for i, offset, end := 0, 0, len(flatCoords); offset < end; i++ { points[i] = kml.Point(kml.CoordinatesFlat(flatCoords, offset, offset+stride, stride, d)) offset += stride } return kml.MultiGeometry(points...) }
go
func EncodeMultiPoint(mp *geom.MultiPoint) kml.Element { points := make([]kml.Element, mp.NumPoints()) flatCoords := mp.FlatCoords() stride := mp.Stride() d := dim(mp.Layout()) for i, offset, end := 0, 0, len(flatCoords); offset < end; i++ { points[i] = kml.Point(kml.CoordinatesFlat(flatCoords, offset, offset+stride, stride, d)) offset += stride } return kml.MultiGeometry(points...) }
[ "func", "EncodeMultiPoint", "(", "mp", "*", "geom", ".", "MultiPoint", ")", "kml", ".", "Element", "{", "points", ":=", "make", "(", "[", "]", "kml", ".", "Element", ",", "mp", ".", "NumPoints", "(", ")", ")", "\n", "flatCoords", ":=", "mp", ".", "FlatCoords", "(", ")", "\n", "stride", ":=", "mp", ".", "Stride", "(", ")", "\n", "d", ":=", "dim", "(", "mp", ".", "Layout", "(", ")", ")", "\n", "for", "i", ",", "offset", ",", "end", ":=", "0", ",", "0", ",", "len", "(", "flatCoords", ")", ";", "offset", "<", "end", ";", "i", "++", "{", "points", "[", "i", "]", "=", "kml", ".", "Point", "(", "kml", ".", "CoordinatesFlat", "(", "flatCoords", ",", "offset", ",", "offset", "+", "stride", ",", "stride", ",", "d", ")", ")", "\n", "offset", "+=", "stride", "\n", "}", "\n", "return", "kml", ".", "MultiGeometry", "(", "points", "...", ")", "\n", "}" ]
// EncodeMultiPoint encodes a MultiPoint.
[ "EncodeMultiPoint", "encodes", "a", "MultiPoint", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/encoding/kml/kml.go#L61-L71
151,738
twpayne/go-geom
encoding/kml/kml.go
EncodeMultiPolygon
func EncodeMultiPolygon(mp *geom.MultiPolygon) kml.Element { polygons := make([]kml.Element, mp.NumPolygons()) flatCoords := mp.FlatCoords() endss := mp.Endss() stride := mp.Stride() d := dim(mp.Layout()) offset := 0 for i, ends := range endss { boundaries := make([]kml.Element, len(ends)) for j, end := range ends { linearRing := kml.LinearRing(kml.CoordinatesFlat(flatCoords, offset, end, stride, d)) if j == 0 { boundaries[j] = kml.OuterBoundaryIs(linearRing) } else { boundaries[j] = kml.InnerBoundaryIs(linearRing) } offset = end } polygons[i] = kml.Polygon(boundaries...) } return kml.MultiGeometry(polygons...) }
go
func EncodeMultiPolygon(mp *geom.MultiPolygon) kml.Element { polygons := make([]kml.Element, mp.NumPolygons()) flatCoords := mp.FlatCoords() endss := mp.Endss() stride := mp.Stride() d := dim(mp.Layout()) offset := 0 for i, ends := range endss { boundaries := make([]kml.Element, len(ends)) for j, end := range ends { linearRing := kml.LinearRing(kml.CoordinatesFlat(flatCoords, offset, end, stride, d)) if j == 0 { boundaries[j] = kml.OuterBoundaryIs(linearRing) } else { boundaries[j] = kml.InnerBoundaryIs(linearRing) } offset = end } polygons[i] = kml.Polygon(boundaries...) } return kml.MultiGeometry(polygons...) }
[ "func", "EncodeMultiPolygon", "(", "mp", "*", "geom", ".", "MultiPolygon", ")", "kml", ".", "Element", "{", "polygons", ":=", "make", "(", "[", "]", "kml", ".", "Element", ",", "mp", ".", "NumPolygons", "(", ")", ")", "\n", "flatCoords", ":=", "mp", ".", "FlatCoords", "(", ")", "\n", "endss", ":=", "mp", ".", "Endss", "(", ")", "\n", "stride", ":=", "mp", ".", "Stride", "(", ")", "\n", "d", ":=", "dim", "(", "mp", ".", "Layout", "(", ")", ")", "\n", "offset", ":=", "0", "\n", "for", "i", ",", "ends", ":=", "range", "endss", "{", "boundaries", ":=", "make", "(", "[", "]", "kml", ".", "Element", ",", "len", "(", "ends", ")", ")", "\n", "for", "j", ",", "end", ":=", "range", "ends", "{", "linearRing", ":=", "kml", ".", "LinearRing", "(", "kml", ".", "CoordinatesFlat", "(", "flatCoords", ",", "offset", ",", "end", ",", "stride", ",", "d", ")", ")", "\n", "if", "j", "==", "0", "{", "boundaries", "[", "j", "]", "=", "kml", ".", "OuterBoundaryIs", "(", "linearRing", ")", "\n", "}", "else", "{", "boundaries", "[", "j", "]", "=", "kml", ".", "InnerBoundaryIs", "(", "linearRing", ")", "\n", "}", "\n", "offset", "=", "end", "\n", "}", "\n", "polygons", "[", "i", "]", "=", "kml", ".", "Polygon", "(", "boundaries", "...", ")", "\n", "}", "\n", "return", "kml", ".", "MultiGeometry", "(", "polygons", "...", ")", "\n", "}" ]
// EncodeMultiPolygon encodes a MultiPolygon.
[ "EncodeMultiPolygon", "encodes", "a", "MultiPolygon", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/encoding/kml/kml.go#L74-L95
151,739
twpayne/go-geom
encoding/kml/kml.go
EncodePoint
func EncodePoint(p *geom.Point) kml.Element { flatCoords := p.FlatCoords() return kml.Point(kml.CoordinatesFlat(flatCoords, 0, len(flatCoords), p.Stride(), dim(p.Layout()))) }
go
func EncodePoint(p *geom.Point) kml.Element { flatCoords := p.FlatCoords() return kml.Point(kml.CoordinatesFlat(flatCoords, 0, len(flatCoords), p.Stride(), dim(p.Layout()))) }
[ "func", "EncodePoint", "(", "p", "*", "geom", ".", "Point", ")", "kml", ".", "Element", "{", "flatCoords", ":=", "p", ".", "FlatCoords", "(", ")", "\n", "return", "kml", ".", "Point", "(", "kml", ".", "CoordinatesFlat", "(", "flatCoords", ",", "0", ",", "len", "(", "flatCoords", ")", ",", "p", ".", "Stride", "(", ")", ",", "dim", "(", "p", ".", "Layout", "(", ")", ")", ")", ")", "\n", "}" ]
// EncodePoint encodes a Point.
[ "EncodePoint", "encodes", "a", "Point", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/encoding/kml/kml.go#L98-L101
151,740
twpayne/go-geom
encoding/kml/kml.go
EncodePolygon
func EncodePolygon(p *geom.Polygon) kml.Element { boundaries := make([]kml.Element, p.NumLinearRings()) stride := p.Stride() flatCoords := p.FlatCoords() d := dim(p.Layout()) offset := 0 for i, end := range p.Ends() { linearRing := kml.LinearRing(kml.CoordinatesFlat(flatCoords, offset, end, stride, d)) if i == 0 { boundaries[i] = kml.OuterBoundaryIs(linearRing) } else { boundaries[i] = kml.InnerBoundaryIs(linearRing) } offset = end } return kml.Polygon(boundaries...) }
go
func EncodePolygon(p *geom.Polygon) kml.Element { boundaries := make([]kml.Element, p.NumLinearRings()) stride := p.Stride() flatCoords := p.FlatCoords() d := dim(p.Layout()) offset := 0 for i, end := range p.Ends() { linearRing := kml.LinearRing(kml.CoordinatesFlat(flatCoords, offset, end, stride, d)) if i == 0 { boundaries[i] = kml.OuterBoundaryIs(linearRing) } else { boundaries[i] = kml.InnerBoundaryIs(linearRing) } offset = end } return kml.Polygon(boundaries...) }
[ "func", "EncodePolygon", "(", "p", "*", "geom", ".", "Polygon", ")", "kml", ".", "Element", "{", "boundaries", ":=", "make", "(", "[", "]", "kml", ".", "Element", ",", "p", ".", "NumLinearRings", "(", ")", ")", "\n", "stride", ":=", "p", ".", "Stride", "(", ")", "\n", "flatCoords", ":=", "p", ".", "FlatCoords", "(", ")", "\n", "d", ":=", "dim", "(", "p", ".", "Layout", "(", ")", ")", "\n", "offset", ":=", "0", "\n", "for", "i", ",", "end", ":=", "range", "p", ".", "Ends", "(", ")", "{", "linearRing", ":=", "kml", ".", "LinearRing", "(", "kml", ".", "CoordinatesFlat", "(", "flatCoords", ",", "offset", ",", "end", ",", "stride", ",", "d", ")", ")", "\n", "if", "i", "==", "0", "{", "boundaries", "[", "i", "]", "=", "kml", ".", "OuterBoundaryIs", "(", "linearRing", ")", "\n", "}", "else", "{", "boundaries", "[", "i", "]", "=", "kml", ".", "InnerBoundaryIs", "(", "linearRing", ")", "\n", "}", "\n", "offset", "=", "end", "\n", "}", "\n", "return", "kml", ".", "Polygon", "(", "boundaries", "...", ")", "\n", "}" ]
// EncodePolygon encodes a Polygon.
[ "EncodePolygon", "encodes", "a", "Polygon", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/encoding/kml/kml.go#L104-L120
151,741
twpayne/go-geom
encoding/kml/kml.go
EncodeGeometryCollection
func EncodeGeometryCollection(g *geom.GeometryCollection) (kml.Element, error) { geometries := make([]kml.Element, g.NumGeoms()) for i, g := range g.Geoms() { var err error geometries[i], err = Encode(g) if err != nil { return nil, err } } return kml.MultiGeometry(geometries...), nil }
go
func EncodeGeometryCollection(g *geom.GeometryCollection) (kml.Element, error) { geometries := make([]kml.Element, g.NumGeoms()) for i, g := range g.Geoms() { var err error geometries[i], err = Encode(g) if err != nil { return nil, err } } return kml.MultiGeometry(geometries...), nil }
[ "func", "EncodeGeometryCollection", "(", "g", "*", "geom", ".", "GeometryCollection", ")", "(", "kml", ".", "Element", ",", "error", ")", "{", "geometries", ":=", "make", "(", "[", "]", "kml", ".", "Element", ",", "g", ".", "NumGeoms", "(", ")", ")", "\n", "for", "i", ",", "g", ":=", "range", "g", ".", "Geoms", "(", ")", "{", "var", "err", "error", "\n", "geometries", "[", "i", "]", ",", "err", "=", "Encode", "(", "g", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "kml", ".", "MultiGeometry", "(", "geometries", "...", ")", ",", "nil", "\n", "}" ]
// EncodeGeometryCollection encodes a GeometryCollection.
[ "EncodeGeometryCollection", "encodes", "a", "GeometryCollection", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/encoding/kml/kml.go#L123-L133
151,742
twpayne/go-geom
multipoint.go
NewMultiPointFlat
func NewMultiPointFlat(layout Layout, flatCoords []float64) *MultiPoint { g := new(MultiPoint) g.layout = layout g.stride = layout.Stride() g.flatCoords = flatCoords return g }
go
func NewMultiPointFlat(layout Layout, flatCoords []float64) *MultiPoint { g := new(MultiPoint) g.layout = layout g.stride = layout.Stride() g.flatCoords = flatCoords return g }
[ "func", "NewMultiPointFlat", "(", "layout", "Layout", ",", "flatCoords", "[", "]", "float64", ")", "*", "MultiPoint", "{", "g", ":=", "new", "(", "MultiPoint", ")", "\n", "g", ".", "layout", "=", "layout", "\n", "g", ".", "stride", "=", "layout", ".", "Stride", "(", ")", "\n", "g", ".", "flatCoords", "=", "flatCoords", "\n", "return", "g", "\n", "}" ]
// NewMultiPointFlat returns a new MultiPoint with the given flat coordinates.
[ "NewMultiPointFlat", "returns", "a", "new", "MultiPoint", "with", "the", "given", "flat", "coordinates", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/multipoint.go#L14-L20
151,743
twpayne/go-geom
multipoint.go
Point
func (g *MultiPoint) Point(i int) *Point { return NewPointFlat(g.layout, g.Coord(i)) }
go
func (g *MultiPoint) Point(i int) *Point { return NewPointFlat(g.layout, g.Coord(i)) }
[ "func", "(", "g", "*", "MultiPoint", ")", "Point", "(", "i", "int", ")", "*", "Point", "{", "return", "NewPointFlat", "(", "g", ".", "layout", ",", "g", ".", "Coord", "(", "i", ")", ")", "\n", "}" ]
// Point returns the ith Point.
[ "Point", "returns", "the", "ith", "Point", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/multipoint.go#L68-L70
151,744
twpayne/go-geom
multipoint.go
Push
func (g *MultiPoint) Push(p *Point) error { if p.layout != g.layout { return ErrLayoutMismatch{Got: p.layout, Want: g.layout} } g.flatCoords = append(g.flatCoords, p.flatCoords...) return nil }
go
func (g *MultiPoint) Push(p *Point) error { if p.layout != g.layout { return ErrLayoutMismatch{Got: p.layout, Want: g.layout} } g.flatCoords = append(g.flatCoords, p.flatCoords...) return nil }
[ "func", "(", "g", "*", "MultiPoint", ")", "Push", "(", "p", "*", "Point", ")", "error", "{", "if", "p", ".", "layout", "!=", "g", ".", "layout", "{", "return", "ErrLayoutMismatch", "{", "Got", ":", "p", ".", "layout", ",", "Want", ":", "g", ".", "layout", "}", "\n", "}", "\n", "g", ".", "flatCoords", "=", "append", "(", "g", ".", "flatCoords", ",", "p", ".", "flatCoords", "...", ")", "\n", "return", "nil", "\n", "}" ]
// Push appends a point.
[ "Push", "appends", "a", "point", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/multipoint.go#L73-L79
151,745
twpayne/go-geom
xy/area_centroid.go
NewAreaCentroidCalculator
func NewAreaCentroidCalculator(layout geom.Layout) *AreaCentroidCalculator { return &AreaCentroidCalculator{ layout: layout, stride: layout.Stride(), centSum: geom.Coord(make([]float64, layout.Stride())), triangleCent3: geom.Coord(make([]float64, layout.Stride())), cg3: geom.Coord(make([]float64, layout.Stride())), } }
go
func NewAreaCentroidCalculator(layout geom.Layout) *AreaCentroidCalculator { return &AreaCentroidCalculator{ layout: layout, stride: layout.Stride(), centSum: geom.Coord(make([]float64, layout.Stride())), triangleCent3: geom.Coord(make([]float64, layout.Stride())), cg3: geom.Coord(make([]float64, layout.Stride())), } }
[ "func", "NewAreaCentroidCalculator", "(", "layout", "geom", ".", "Layout", ")", "*", "AreaCentroidCalculator", "{", "return", "&", "AreaCentroidCalculator", "{", "layout", ":", "layout", ",", "stride", ":", "layout", ".", "Stride", "(", ")", ",", "centSum", ":", "geom", ".", "Coord", "(", "make", "(", "[", "]", "float64", ",", "layout", ".", "Stride", "(", ")", ")", ")", ",", "triangleCent3", ":", "geom", ".", "Coord", "(", "make", "(", "[", "]", "float64", ",", "layout", ".", "Stride", "(", ")", ")", ")", ",", "cg3", ":", "geom", ".", "Coord", "(", "make", "(", "[", "]", "float64", ",", "layout", ".", "Stride", "(", ")", ")", ")", ",", "}", "\n", "}" ]
// NewAreaCentroidCalculator creates a new instance of the calculator. // Once a calculator is created polygons can be added to it and the // GetCentroid method can be used at any point to get the current centroid // the centroid will naturally change each time a polygon is added
[ "NewAreaCentroidCalculator", "creates", "a", "new", "instance", "of", "the", "calculator", ".", "Once", "a", "calculator", "is", "created", "polygons", "can", "be", "added", "to", "it", "and", "the", "GetCentroid", "method", "can", "be", "used", "at", "any", "point", "to", "get", "the", "current", "centroid", "the", "centroid", "will", "naturally", "change", "each", "time", "a", "polygon", "is", "added" ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/area_centroid.go#L72-L80
151,746
twpayne/go-geom
xy/area_centroid.go
AddPolygon
func (calc *AreaCentroidCalculator) AddPolygon(polygon *geom.Polygon) { calc.setBasePoint(polygon.Coord(0)) calc.addShell(polygon.LinearRing(0).FlatCoords()) for i := 1; i < polygon.NumLinearRings(); i++ { calc.addHole(polygon.LinearRing(i).FlatCoords()) } }
go
func (calc *AreaCentroidCalculator) AddPolygon(polygon *geom.Polygon) { calc.setBasePoint(polygon.Coord(0)) calc.addShell(polygon.LinearRing(0).FlatCoords()) for i := 1; i < polygon.NumLinearRings(); i++ { calc.addHole(polygon.LinearRing(i).FlatCoords()) } }
[ "func", "(", "calc", "*", "AreaCentroidCalculator", ")", "AddPolygon", "(", "polygon", "*", "geom", ".", "Polygon", ")", "{", "calc", ".", "setBasePoint", "(", "polygon", ".", "Coord", "(", "0", ")", ")", "\n\n", "calc", ".", "addShell", "(", "polygon", ".", "LinearRing", "(", "0", ")", ".", "FlatCoords", "(", ")", ")", "\n", "for", "i", ":=", "1", ";", "i", "<", "polygon", ".", "NumLinearRings", "(", ")", ";", "i", "++", "{", "calc", ".", "addHole", "(", "polygon", ".", "LinearRing", "(", "i", ")", ".", "FlatCoords", "(", ")", ")", "\n", "}", "\n", "}" ]
// AddPolygon adds a polygon to the calculation.
[ "AddPolygon", "adds", "a", "polygon", "to", "the", "calculation", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/area_centroid.go#L102-L109
151,747
twpayne/go-geom
xy/area_centroid.go
centroid3
func centroid3(p1, p2, p3, c geom.Coord) { c[0] = p1[0] + p2[0] + p3[0] c[1] = p1[1] + p2[1] + p3[1] }
go
func centroid3(p1, p2, p3, c geom.Coord) { c[0] = p1[0] + p2[0] + p3[0] c[1] = p1[1] + p2[1] + p3[1] }
[ "func", "centroid3", "(", "p1", ",", "p2", ",", "p3", ",", "c", "geom", ".", "Coord", ")", "{", "c", "[", "0", "]", "=", "p1", "[", "0", "]", "+", "p2", "[", "0", "]", "+", "p3", "[", "0", "]", "\n", "c", "[", "1", "]", "=", "p1", "[", "1", "]", "+", "p2", "[", "1", "]", "+", "p3", "[", "1", "]", "\n", "}" ]
// Returns three times the centroid of the triangle p1-p2-p3. // The factor of 3 is left in to permit division to be avoided until later.
[ "Returns", "three", "times", "the", "centroid", "of", "the", "triangle", "p1", "-", "p2", "-", "p3", ".", "The", "factor", "of", "3", "is", "left", "in", "to", "permit", "division", "to", "be", "avoided", "until", "later", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/area_centroid.go#L165-L168
151,748
twpayne/go-geom
xy/area_centroid.go
area2
func area2(p1, p2, p3 geom.Coord) float64 { return (p2[0]-p1[0])*(p3[1]-p1[1]) - (p3[0]-p1[0])*(p2[1]-p1[1]) }
go
func area2(p1, p2, p3 geom.Coord) float64 { return (p2[0]-p1[0])*(p3[1]-p1[1]) - (p3[0]-p1[0])*(p2[1]-p1[1]) }
[ "func", "area2", "(", "p1", ",", "p2", ",", "p3", "geom", ".", "Coord", ")", "float64", "{", "return", "(", "p2", "[", "0", "]", "-", "p1", "[", "0", "]", ")", "*", "(", "p3", "[", "1", "]", "-", "p1", "[", "1", "]", ")", "-", "(", "p3", "[", "0", "]", "-", "p1", "[", "0", "]", ")", "*", "(", "p2", "[", "1", "]", "-", "p1", "[", "1", "]", ")", "\n", "}" ]
// Returns twice the signed area of the triangle p1-p2-p3, // positive if a,b,c are oriented ccw, and negative if cw.
[ "Returns", "twice", "the", "signed", "area", "of", "the", "triangle", "p1", "-", "p2", "-", "p3", "positive", "if", "a", "b", "c", "are", "oriented", "ccw", "and", "negative", "if", "cw", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/area_centroid.go#L172-L174
151,749
twpayne/go-geom
xy/radial_comparator.go
NewRadialSorting
func NewRadialSorting(layout geom.Layout, coordData []float64, focalPoint geom.Coord) sort.Interface { isLess := func(v1, v2 []float64) bool { orient := bigxy.OrientationIndex(focalPoint, v1, v2) if orient == orientation.CounterClockwise { return false } if orient == orientation.Clockwise { return true } dxp := v1[0] - focalPoint[0] dyp := v1[1] - focalPoint[1] dxq := v2[0] - focalPoint[0] dyq := v2[1] - focalPoint[1] // points are collinear - check distance op := dxp*dxp + dyp*dyp oq := dxq*dxq + dyq*dyq return op < oq } return sorting.NewFlatCoordSorting(layout, coordData, isLess) }
go
func NewRadialSorting(layout geom.Layout, coordData []float64, focalPoint geom.Coord) sort.Interface { isLess := func(v1, v2 []float64) bool { orient := bigxy.OrientationIndex(focalPoint, v1, v2) if orient == orientation.CounterClockwise { return false } if orient == orientation.Clockwise { return true } dxp := v1[0] - focalPoint[0] dyp := v1[1] - focalPoint[1] dxq := v2[0] - focalPoint[0] dyq := v2[1] - focalPoint[1] // points are collinear - check distance op := dxp*dxp + dyp*dyp oq := dxq*dxq + dyq*dyq return op < oq } return sorting.NewFlatCoordSorting(layout, coordData, isLess) }
[ "func", "NewRadialSorting", "(", "layout", "geom", ".", "Layout", ",", "coordData", "[", "]", "float64", ",", "focalPoint", "geom", ".", "Coord", ")", "sort", ".", "Interface", "{", "isLess", ":=", "func", "(", "v1", ",", "v2", "[", "]", "float64", ")", "bool", "{", "orient", ":=", "bigxy", ".", "OrientationIndex", "(", "focalPoint", ",", "v1", ",", "v2", ")", "\n\n", "if", "orient", "==", "orientation", ".", "CounterClockwise", "{", "return", "false", "\n", "}", "\n", "if", "orient", "==", "orientation", ".", "Clockwise", "{", "return", "true", "\n", "}", "\n\n", "dxp", ":=", "v1", "[", "0", "]", "-", "focalPoint", "[", "0", "]", "\n", "dyp", ":=", "v1", "[", "1", "]", "-", "focalPoint", "[", "1", "]", "\n", "dxq", ":=", "v2", "[", "0", "]", "-", "focalPoint", "[", "0", "]", "\n", "dyq", ":=", "v2", "[", "1", "]", "-", "focalPoint", "[", "1", "]", "\n\n", "// points are collinear - check distance", "op", ":=", "dxp", "*", "dxp", "+", "dyp", "*", "dyp", "\n", "oq", ":=", "dxq", "*", "dxq", "+", "dyq", "*", "dyq", "\n", "return", "op", "<", "oq", "\n", "}", "\n", "return", "sorting", ".", "NewFlatCoordSorting", "(", "layout", ",", "coordData", ",", "isLess", ")", "\n", "}" ]
// NewRadialSorting creates an implementation sort.Interface which will sort the wrapped coordinate array // radially around the focal point. The comparison is based on the angle and distance // from the focal point. // First the angle is checked. // Counter clockwise indicates a greater value and clockwise indicates a lesser value // If co-linear then the coordinate nearer to the focalPoint is considered less.
[ "NewRadialSorting", "creates", "an", "implementation", "sort", ".", "Interface", "which", "will", "sort", "the", "wrapped", "coordinate", "array", "radially", "around", "the", "focal", "point", ".", "The", "comparison", "is", "based", "on", "the", "angle", "and", "distance", "from", "the", "focal", "point", ".", "First", "the", "angle", "is", "checked", ".", "Counter", "clockwise", "indicates", "a", "greater", "value", "and", "clockwise", "indicates", "a", "lesser", "value", "If", "co", "-", "linear", "then", "the", "coordinate", "nearer", "to", "the", "focalPoint", "is", "considered", "less", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/radial_comparator.go#L18-L40
151,750
twpayne/go-geom
encoding/wkbcommon/binary.go
ReadUInt32
func ReadUInt32(r io.Reader, byteOrder binary.ByteOrder) (uint32, error) { var buf [4]byte if _, err := io.ReadFull(r, buf[:]); err != nil { return 0, err } return byteOrder.Uint32(buf[:]), nil }
go
func ReadUInt32(r io.Reader, byteOrder binary.ByteOrder) (uint32, error) { var buf [4]byte if _, err := io.ReadFull(r, buf[:]); err != nil { return 0, err } return byteOrder.Uint32(buf[:]), nil }
[ "func", "ReadUInt32", "(", "r", "io", ".", "Reader", ",", "byteOrder", "binary", ".", "ByteOrder", ")", "(", "uint32", ",", "error", ")", "{", "var", "buf", "[", "4", "]", "byte", "\n", "if", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "r", ",", "buf", "[", ":", "]", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "byteOrder", ".", "Uint32", "(", "buf", "[", ":", "]", ")", ",", "nil", "\n", "}" ]
// ReadUInt32 reads a uint32 from r.
[ "ReadUInt32", "reads", "a", "uint32", "from", "r", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/encoding/wkbcommon/binary.go#L16-L22
151,751
twpayne/go-geom
encoding/wkbcommon/binary.go
ReadByte
func ReadByte(r io.Reader) (byte, error) { var buf [1]byte if _, err := r.Read(buf[:]); err != nil { return 0, err } return buf[0], nil }
go
func ReadByte(r io.Reader) (byte, error) { var buf [1]byte if _, err := r.Read(buf[:]); err != nil { return 0, err } return buf[0], nil }
[ "func", "ReadByte", "(", "r", "io", ".", "Reader", ")", "(", "byte", ",", "error", ")", "{", "var", "buf", "[", "1", "]", "byte", "\n", "if", "_", ",", "err", ":=", "r", ".", "Read", "(", "buf", "[", ":", "]", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "buf", "[", "0", "]", ",", "nil", "\n", "}" ]
// ReadByte reads a byte from r.
[ "ReadByte", "reads", "a", "byte", "from", "r", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/encoding/wkbcommon/binary.go#L38-L44
151,752
twpayne/go-geom
encoding/wkbcommon/binary.go
WriteUInt32
func WriteUInt32(w io.Writer, byteOrder binary.ByteOrder, value uint32) error { var buf [4]byte byteOrder.PutUint32(buf[:], value) _, err := w.Write(buf[:]) return err }
go
func WriteUInt32(w io.Writer, byteOrder binary.ByteOrder, value uint32) error { var buf [4]byte byteOrder.PutUint32(buf[:], value) _, err := w.Write(buf[:]) return err }
[ "func", "WriteUInt32", "(", "w", "io", ".", "Writer", ",", "byteOrder", "binary", ".", "ByteOrder", ",", "value", "uint32", ")", "error", "{", "var", "buf", "[", "4", "]", "byte", "\n", "byteOrder", ".", "PutUint32", "(", "buf", "[", ":", "]", ",", "value", ")", "\n", "_", ",", "err", ":=", "w", ".", "Write", "(", "buf", "[", ":", "]", ")", "\n", "return", "err", "\n", "}" ]
// WriteUInt32 writes a uint32 to w.
[ "WriteUInt32", "writes", "a", "uint32", "to", "w", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/encoding/wkbcommon/binary.go#L62-L67
151,753
twpayne/go-geom
encoding/wkbcommon/binary.go
WriteByte
func WriteByte(w io.Writer, value byte) error { var buf [1]byte buf[0] = value _, err := w.Write(buf[:]) return err }
go
func WriteByte(w io.Writer, value byte) error { var buf [1]byte buf[0] = value _, err := w.Write(buf[:]) return err }
[ "func", "WriteByte", "(", "w", "io", ".", "Writer", ",", "value", "byte", ")", "error", "{", "var", "buf", "[", "1", "]", "byte", "\n", "buf", "[", "0", "]", "=", "value", "\n", "_", ",", "err", ":=", "w", ".", "Write", "(", "buf", "[", ":", "]", ")", "\n", "return", "err", "\n", "}" ]
// WriteByte wrties a byte to w.
[ "WriteByte", "wrties", "a", "byte", "to", "w", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/encoding/wkbcommon/binary.go#L70-L75
151,754
pquerna/ffjson
fflib/v1/buffer_pool.go
poolNum
func poolNum(i int) int { // TODO(pquerna): convert to log2 w/ bsr asm instruction: // <https://groups.google.com/forum/#!topic/golang-nuts/uAb5J1_y7ns> if i <= 64 { return 0 } else if i <= 128 { return 1 } else if i <= 256 { return 2 } else if i <= 512 { return 3 } else if i <= 1024 { return 4 } else if i <= 2048 { return 5 } else if i <= 4096 { return 6 } else if i <= 8192 { return 7 } else if i <= 16384 { return 8 } else if i <= 32768 { return 9 } else if i <= 65536 { return 10 } else if i <= 131072 { return 11 } else if i <= 262144 { return 12 } else if i <= 524288 { return 13 } else { return -1 } }
go
func poolNum(i int) int { // TODO(pquerna): convert to log2 w/ bsr asm instruction: // <https://groups.google.com/forum/#!topic/golang-nuts/uAb5J1_y7ns> if i <= 64 { return 0 } else if i <= 128 { return 1 } else if i <= 256 { return 2 } else if i <= 512 { return 3 } else if i <= 1024 { return 4 } else if i <= 2048 { return 5 } else if i <= 4096 { return 6 } else if i <= 8192 { return 7 } else if i <= 16384 { return 8 } else if i <= 32768 { return 9 } else if i <= 65536 { return 10 } else if i <= 131072 { return 11 } else if i <= 262144 { return 12 } else if i <= 524288 { return 13 } else { return -1 } }
[ "func", "poolNum", "(", "i", "int", ")", "int", "{", "// TODO(pquerna): convert to log2 w/ bsr asm instruction:", "// \t<https://groups.google.com/forum/#!topic/golang-nuts/uAb5J1_y7ns>", "if", "i", "<=", "64", "{", "return", "0", "\n", "}", "else", "if", "i", "<=", "128", "{", "return", "1", "\n", "}", "else", "if", "i", "<=", "256", "{", "return", "2", "\n", "}", "else", "if", "i", "<=", "512", "{", "return", "3", "\n", "}", "else", "if", "i", "<=", "1024", "{", "return", "4", "\n", "}", "else", "if", "i", "<=", "2048", "{", "return", "5", "\n", "}", "else", "if", "i", "<=", "4096", "{", "return", "6", "\n", "}", "else", "if", "i", "<=", "8192", "{", "return", "7", "\n", "}", "else", "if", "i", "<=", "16384", "{", "return", "8", "\n", "}", "else", "if", "i", "<=", "32768", "{", "return", "9", "\n", "}", "else", "if", "i", "<=", "65536", "{", "return", "10", "\n", "}", "else", "if", "i", "<=", "131072", "{", "return", "11", "\n", "}", "else", "if", "i", "<=", "262144", "{", "return", "12", "\n", "}", "else", "if", "i", "<=", "524288", "{", "return", "13", "\n", "}", "else", "{", "return", "-", "1", "\n", "}", "\n", "}" ]
// This returns the pool number that will give a buffer of // at least 'i' bytes.
[ "This", "returns", "the", "pool", "number", "that", "will", "give", "a", "buffer", "of", "at", "least", "i", "bytes", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/fflib/v1/buffer_pool.go#L28-L62
151,755
pquerna/ffjson
fflib/v1/buffer_pool.go
Pool
func Pool(b []byte) { if b == nil { return } c := cap(b) // Our smallest buffer is 64 bytes, so we discard smaller buffers. if c < 64 { return } // We need to put the incoming buffer into the NEXT buffer, // since a buffer guarantees AT LEAST the number of bytes available // that is the top of this buffer. // That is the reason for dividing the cap by 2, so it gets into the NEXT bucket. // We add 2 to avoid rounding down if size is exactly power of 2. pn := poolNum((c + 2) >> 1) if pn != -1 { pools[pn].Put(b[0:0]) } // if we didn't have a slot for this []byte, we just drop it and let the GC // take care of it. }
go
func Pool(b []byte) { if b == nil { return } c := cap(b) // Our smallest buffer is 64 bytes, so we discard smaller buffers. if c < 64 { return } // We need to put the incoming buffer into the NEXT buffer, // since a buffer guarantees AT LEAST the number of bytes available // that is the top of this buffer. // That is the reason for dividing the cap by 2, so it gets into the NEXT bucket. // We add 2 to avoid rounding down if size is exactly power of 2. pn := poolNum((c + 2) >> 1) if pn != -1 { pools[pn].Put(b[0:0]) } // if we didn't have a slot for this []byte, we just drop it and let the GC // take care of it. }
[ "func", "Pool", "(", "b", "[", "]", "byte", ")", "{", "if", "b", "==", "nil", "{", "return", "\n", "}", "\n", "c", ":=", "cap", "(", "b", ")", "\n\n", "// Our smallest buffer is 64 bytes, so we discard smaller buffers.", "if", "c", "<", "64", "{", "return", "\n", "}", "\n\n", "// We need to put the incoming buffer into the NEXT buffer,", "// since a buffer guarantees AT LEAST the number of bytes available", "// that is the top of this buffer.", "// That is the reason for dividing the cap by 2, so it gets into the NEXT bucket.", "// We add 2 to avoid rounding down if size is exactly power of 2.", "pn", ":=", "poolNum", "(", "(", "c", "+", "2", ")", ">>", "1", ")", "\n", "if", "pn", "!=", "-", "1", "{", "pools", "[", "pn", "]", ".", "Put", "(", "b", "[", "0", ":", "0", "]", ")", "\n", "}", "\n", "// if we didn't have a slot for this []byte, we just drop it and let the GC", "// take care of it.", "}" ]
// Send a buffer to the Pool to reuse for other instances. // You may no longer utilize the content of the buffer, since it may be used // by other goroutines.
[ "Send", "a", "buffer", "to", "the", "Pool", "to", "reuse", "for", "other", "instances", ".", "You", "may", "no", "longer", "utilize", "the", "content", "of", "the", "buffer", "since", "it", "may", "be", "used", "by", "other", "goroutines", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/fflib/v1/buffer_pool.go#L67-L89
151,756
pquerna/ffjson
ffjson/marshal.go
Marshal
func Marshal(v interface{}) ([]byte, error) { f, ok := v.(marshalerFaster) if ok { buf := fflib.Buffer{} err := f.MarshalJSONBuf(&buf) b := buf.Bytes() if err != nil { if len(b) > 0 { Pool(b) } return nil, err } return b, nil } j, ok := v.(json.Marshaler) if ok { return j.MarshalJSON() } return json.Marshal(v) }
go
func Marshal(v interface{}) ([]byte, error) { f, ok := v.(marshalerFaster) if ok { buf := fflib.Buffer{} err := f.MarshalJSONBuf(&buf) b := buf.Bytes() if err != nil { if len(b) > 0 { Pool(b) } return nil, err } return b, nil } j, ok := v.(json.Marshaler) if ok { return j.MarshalJSON() } return json.Marshal(v) }
[ "func", "Marshal", "(", "v", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "f", ",", "ok", ":=", "v", ".", "(", "marshalerFaster", ")", "\n", "if", "ok", "{", "buf", ":=", "fflib", ".", "Buffer", "{", "}", "\n", "err", ":=", "f", ".", "MarshalJSONBuf", "(", "&", "buf", ")", "\n", "b", ":=", "buf", ".", "Bytes", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "len", "(", "b", ")", ">", "0", "{", "Pool", "(", "b", ")", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "b", ",", "nil", "\n", "}", "\n\n", "j", ",", "ok", ":=", "v", ".", "(", "json", ".", "Marshaler", ")", "\n", "if", "ok", "{", "return", "j", ".", "MarshalJSON", "(", ")", "\n", "}", "\n", "return", "json", ".", "Marshal", "(", "v", ")", "\n", "}" ]
// Marshal will act the same way as json.Marshal, except // it will choose the ffjson marshal function before falling // back to using json.Marshal. // Using this function will bypass the internal copying and parsing // the json library normally does, which greatly speeds up encoding time. // It is ok to call this function even if no ffjson code has been // generated for the data type you pass in the interface.
[ "Marshal", "will", "act", "the", "same", "way", "as", "json", ".", "Marshal", "except", "it", "will", "choose", "the", "ffjson", "marshal", "function", "before", "falling", "back", "to", "using", "json", ".", "Marshal", ".", "Using", "this", "function", "will", "bypass", "the", "internal", "copying", "and", "parsing", "the", "json", "library", "normally", "does", "which", "greatly", "speeds", "up", "encoding", "time", ".", "It", "is", "ok", "to", "call", "this", "function", "even", "if", "no", "ffjson", "code", "has", "been", "generated", "for", "the", "data", "type", "you", "pass", "in", "the", "interface", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/ffjson/marshal.go#L42-L62
151,757
pquerna/ffjson
ffjson/marshal.go
Unmarshal
func Unmarshal(data []byte, v interface{}) error { f, ok := v.(unmarshalFaster) if ok { fs := fflib.NewFFLexer(data) return f.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) } j, ok := v.(json.Unmarshaler) if ok { return j.UnmarshalJSON(data) } return json.Unmarshal(data, v) }
go
func Unmarshal(data []byte, v interface{}) error { f, ok := v.(unmarshalFaster) if ok { fs := fflib.NewFFLexer(data) return f.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) } j, ok := v.(json.Unmarshaler) if ok { return j.UnmarshalJSON(data) } return json.Unmarshal(data, v) }
[ "func", "Unmarshal", "(", "data", "[", "]", "byte", ",", "v", "interface", "{", "}", ")", "error", "{", "f", ",", "ok", ":=", "v", ".", "(", "unmarshalFaster", ")", "\n", "if", "ok", "{", "fs", ":=", "fflib", ".", "NewFFLexer", "(", "data", ")", "\n", "return", "f", ".", "UnmarshalJSONFFLexer", "(", "fs", ",", "fflib", ".", "FFParse_map_start", ")", "\n", "}", "\n\n", "j", ",", "ok", ":=", "v", ".", "(", "json", ".", "Unmarshaler", ")", "\n", "if", "ok", "{", "return", "j", ".", "UnmarshalJSON", "(", "data", ")", "\n", "}", "\n", "return", "json", ".", "Unmarshal", "(", "data", ",", "v", ")", "\n", "}" ]
// Unmarshal will act the same way as json.Unmarshal, except // it will choose the ffjson unmarshal function before falling // back to using json.Unmarshal. // The overhead of unmarshal is lower than on Marshal, // however this should still provide a speedup for your encoding. // It is ok to call this function even if no ffjson code has been // generated for the data type you pass in the interface.
[ "Unmarshal", "will", "act", "the", "same", "way", "as", "json", ".", "Unmarshal", "except", "it", "will", "choose", "the", "ffjson", "unmarshal", "function", "before", "falling", "back", "to", "using", "json", ".", "Unmarshal", ".", "The", "overhead", "of", "unmarshal", "is", "lower", "than", "on", "Marshal", "however", "this", "should", "still", "provide", "a", "speedup", "for", "your", "encoding", ".", "It", "is", "ok", "to", "call", "this", "function", "even", "if", "no", "ffjson", "code", "has", "been", "generated", "for", "the", "data", "type", "you", "pass", "in", "the", "interface", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/ffjson/marshal.go#L84-L96
151,758
pquerna/ffjson
fflib/v1/iota.go
FormatBits2
func FormatBits2(dst FormatBitsWriter, u uint64, base int, neg bool) { if base < 2 || base > len(digits) { panic("strconv: illegal AppendInt/FormatInt base") } // fast path for small common numbers if u <= 10 { if neg { dst.WriteByte('-') } dst.Write(smallNumbers[u]) return } // 2 <= base && base <= len(digits) var a = makeSlice(65) // var a [64 + 1]byte // +1 for sign of 64bit value in base 2 i := len(a) if neg { u = -u } // convert bits if base == 10 { // common case: use constants for / and % because // the compiler can optimize it into a multiply+shift, // and unroll loop for u >= 100 { i -= 2 q := u / 100 j := uintptr(u - q*100) a[i+1] = digits01[j] a[i+0] = digits10[j] u = q } if u >= 10 { i-- q := u / 10 a[i] = digits[uintptr(u-q*10)] u = q } } else if s := shifts[base]; s > 0 { // base is power of 2: use shifts and masks instead of / and % b := uint64(base) m := uintptr(b) - 1 // == 1<<s - 1 for u >= b { i-- a[i] = digits[uintptr(u)&m] u >>= s } } else { // general case b := uint64(base) for u >= b { i-- a[i] = digits[uintptr(u%b)] u /= b } } // u < base i-- a[i] = digits[uintptr(u)] // add sign, if any if neg { i-- a[i] = '-' } dst.Write(a[i:]) Pool(a) return }
go
func FormatBits2(dst FormatBitsWriter, u uint64, base int, neg bool) { if base < 2 || base > len(digits) { panic("strconv: illegal AppendInt/FormatInt base") } // fast path for small common numbers if u <= 10 { if neg { dst.WriteByte('-') } dst.Write(smallNumbers[u]) return } // 2 <= base && base <= len(digits) var a = makeSlice(65) // var a [64 + 1]byte // +1 for sign of 64bit value in base 2 i := len(a) if neg { u = -u } // convert bits if base == 10 { // common case: use constants for / and % because // the compiler can optimize it into a multiply+shift, // and unroll loop for u >= 100 { i -= 2 q := u / 100 j := uintptr(u - q*100) a[i+1] = digits01[j] a[i+0] = digits10[j] u = q } if u >= 10 { i-- q := u / 10 a[i] = digits[uintptr(u-q*10)] u = q } } else if s := shifts[base]; s > 0 { // base is power of 2: use shifts and masks instead of / and % b := uint64(base) m := uintptr(b) - 1 // == 1<<s - 1 for u >= b { i-- a[i] = digits[uintptr(u)&m] u >>= s } } else { // general case b := uint64(base) for u >= b { i-- a[i] = digits[uintptr(u%b)] u /= b } } // u < base i-- a[i] = digits[uintptr(u)] // add sign, if any if neg { i-- a[i] = '-' } dst.Write(a[i:]) Pool(a) return }
[ "func", "FormatBits2", "(", "dst", "FormatBitsWriter", ",", "u", "uint64", ",", "base", "int", ",", "neg", "bool", ")", "{", "if", "base", "<", "2", "||", "base", ">", "len", "(", "digits", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "// fast path for small common numbers", "if", "u", "<=", "10", "{", "if", "neg", "{", "dst", ".", "WriteByte", "(", "'-'", ")", "\n", "}", "\n", "dst", ".", "Write", "(", "smallNumbers", "[", "u", "]", ")", "\n", "return", "\n", "}", "\n\n", "// 2 <= base && base <= len(digits)", "var", "a", "=", "makeSlice", "(", "65", ")", "\n", "//\tvar a [64 + 1]byte // +1 for sign of 64bit value in base 2", "i", ":=", "len", "(", "a", ")", "\n\n", "if", "neg", "{", "u", "=", "-", "u", "\n", "}", "\n\n", "// convert bits", "if", "base", "==", "10", "{", "// common case: use constants for / and % because", "// the compiler can optimize it into a multiply+shift,", "// and unroll loop", "for", "u", ">=", "100", "{", "i", "-=", "2", "\n", "q", ":=", "u", "/", "100", "\n", "j", ":=", "uintptr", "(", "u", "-", "q", "*", "100", ")", "\n", "a", "[", "i", "+", "1", "]", "=", "digits01", "[", "j", "]", "\n", "a", "[", "i", "+", "0", "]", "=", "digits10", "[", "j", "]", "\n", "u", "=", "q", "\n", "}", "\n", "if", "u", ">=", "10", "{", "i", "--", "\n", "q", ":=", "u", "/", "10", "\n", "a", "[", "i", "]", "=", "digits", "[", "uintptr", "(", "u", "-", "q", "*", "10", ")", "]", "\n", "u", "=", "q", "\n", "}", "\n\n", "}", "else", "if", "s", ":=", "shifts", "[", "base", "]", ";", "s", ">", "0", "{", "// base is power of 2: use shifts and masks instead of / and %", "b", ":=", "uint64", "(", "base", ")", "\n", "m", ":=", "uintptr", "(", "b", ")", "-", "1", "// == 1<<s - 1", "\n", "for", "u", ">=", "b", "{", "i", "--", "\n", "a", "[", "i", "]", "=", "digits", "[", "uintptr", "(", "u", ")", "&", "m", "]", "\n", "u", ">>=", "s", "\n", "}", "\n\n", "}", "else", "{", "// general case", "b", ":=", "uint64", "(", "base", ")", "\n", "for", "u", ">=", "b", "{", "i", "--", "\n", "a", "[", "i", "]", "=", "digits", "[", "uintptr", "(", "u", "%", "b", ")", "]", "\n", "u", "/=", "b", "\n", "}", "\n", "}", "\n\n", "// u < base", "i", "--", "\n", "a", "[", "i", "]", "=", "digits", "[", "uintptr", "(", "u", ")", "]", "\n\n", "// add sign, if any", "if", "neg", "{", "i", "--", "\n", "a", "[", "i", "]", "=", "'-'", "\n", "}", "\n\n", "dst", ".", "Write", "(", "a", "[", "i", ":", "]", ")", "\n\n", "Pool", "(", "a", ")", "\n\n", "return", "\n", "}" ]
// FormatBits2 computes the string representation of u in the given base. // If neg is set, u is treated as negative int64 value. If append_ is // set, the string is appended to dst and the resulting byte slice is // returned as the first result value; otherwise the string is returned // as the second result value. //
[ "FormatBits2", "computes", "the", "string", "representation", "of", "u", "in", "the", "given", "base", ".", "If", "neg", "is", "set", "u", "is", "treated", "as", "negative", "int64", "value", ".", "If", "append_", "is", "set", "the", "string", "is", "appended", "to", "dst", "and", "the", "resulting", "byte", "slice", "is", "returned", "as", "the", "first", "result", "value", ";", "otherwise", "the", "string", "is", "returned", "as", "the", "second", "result", "value", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/fflib/v1/iota.go#L83-L161
151,759
pquerna/ffjson
fflib/v1/reader.go
Reset
func (r *ffReader) Reset(d []byte) { r.s = d r.i = 0 r.l = len(d) }
go
func (r *ffReader) Reset(d []byte) { r.s = d r.i = 0 r.l = len(d) }
[ "func", "(", "r", "*", "ffReader", ")", "Reset", "(", "d", "[", "]", "byte", ")", "{", "r", ".", "s", "=", "d", "\n", "r", ".", "i", "=", "0", "\n", "r", ".", "l", "=", "len", "(", "d", ")", "\n", "}" ]
// Reset the reader, and add new input.
[ "Reset", "the", "reader", "and", "add", "new", "input", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/fflib/v1/reader.go#L52-L56
151,760
pquerna/ffjson
fflib/v1/reader.go
PosWithLine
func (r *ffReader) PosWithLine() (int, int) { currentLine := 1 currentChar := 0 for i := 0; i < r.i; i++ { c := r.s[i] currentChar++ if c == '\n' { currentLine++ currentChar = 0 } } return currentLine, currentChar }
go
func (r *ffReader) PosWithLine() (int, int) { currentLine := 1 currentChar := 0 for i := 0; i < r.i; i++ { c := r.s[i] currentChar++ if c == '\n' { currentLine++ currentChar = 0 } } return currentLine, currentChar }
[ "func", "(", "r", "*", "ffReader", ")", "PosWithLine", "(", ")", "(", "int", ",", "int", ")", "{", "currentLine", ":=", "1", "\n", "currentChar", ":=", "0", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "r", ".", "i", ";", "i", "++", "{", "c", ":=", "r", ".", "s", "[", "i", "]", "\n", "currentChar", "++", "\n", "if", "c", "==", "'\\n'", "{", "currentLine", "++", "\n", "currentChar", "=", "0", "\n", "}", "\n", "}", "\n\n", "return", "currentLine", ",", "currentChar", "\n", "}" ]
// Calcuates the Position with line and line offset, // because this isn't counted for performance reasons, // it will iterate the buffer from the beginning, and should // only be used in error-paths.
[ "Calcuates", "the", "Position", "with", "line", "and", "line", "offset", "because", "this", "isn", "t", "counted", "for", "performance", "reasons", "it", "will", "iterate", "the", "buffer", "from", "the", "beginning", "and", "should", "only", "be", "used", "in", "error", "-", "paths", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/fflib/v1/reader.go#L62-L76
151,761
pquerna/ffjson
fflib/v1/ftoa.go
formatBits
func formatBits(dst EncodingBuffer, u uint64, base int, neg bool) { if base < 2 || base > len(digits) { panic("strconv: illegal AppendInt/FormatInt base") } // 2 <= base && base <= len(digits) var a [64 + 1]byte // +1 for sign of 64bit value in base 2 i := len(a) if neg { u = -u } // convert bits if base == 10 { // common case: use constants for / because // the compiler can optimize it into a multiply+shift if ^uintptr(0)>>32 == 0 { for u > uint64(^uintptr(0)) { q := u / 1e9 us := uintptr(u - q*1e9) // us % 1e9 fits into a uintptr for j := 9; j > 0; j-- { i-- qs := us / 10 a[i] = byte(us - qs*10 + '0') us = qs } u = q } } // u guaranteed to fit into a uintptr us := uintptr(u) for us >= 10 { i-- q := us / 10 a[i] = byte(us - q*10 + '0') us = q } // u < 10 i-- a[i] = byte(us + '0') } else if s := shifts[base]; s > 0 { // base is power of 2: use shifts and masks instead of / and % b := uint64(base) m := uintptr(b) - 1 // == 1<<s - 1 for u >= b { i-- a[i] = digits[uintptr(u)&m] u >>= s } // u < base i-- a[i] = digits[uintptr(u)] } else { // general case b := uint64(base) for u >= b { i-- q := u / b a[i] = digits[uintptr(u-q*b)] u = q } // u < base i-- a[i] = digits[uintptr(u)] } // add sign, if any if neg { i-- a[i] = '-' } dst.Write(a[i:]) }
go
func formatBits(dst EncodingBuffer, u uint64, base int, neg bool) { if base < 2 || base > len(digits) { panic("strconv: illegal AppendInt/FormatInt base") } // 2 <= base && base <= len(digits) var a [64 + 1]byte // +1 for sign of 64bit value in base 2 i := len(a) if neg { u = -u } // convert bits if base == 10 { // common case: use constants for / because // the compiler can optimize it into a multiply+shift if ^uintptr(0)>>32 == 0 { for u > uint64(^uintptr(0)) { q := u / 1e9 us := uintptr(u - q*1e9) // us % 1e9 fits into a uintptr for j := 9; j > 0; j-- { i-- qs := us / 10 a[i] = byte(us - qs*10 + '0') us = qs } u = q } } // u guaranteed to fit into a uintptr us := uintptr(u) for us >= 10 { i-- q := us / 10 a[i] = byte(us - q*10 + '0') us = q } // u < 10 i-- a[i] = byte(us + '0') } else if s := shifts[base]; s > 0 { // base is power of 2: use shifts and masks instead of / and % b := uint64(base) m := uintptr(b) - 1 // == 1<<s - 1 for u >= b { i-- a[i] = digits[uintptr(u)&m] u >>= s } // u < base i-- a[i] = digits[uintptr(u)] } else { // general case b := uint64(base) for u >= b { i-- q := u / b a[i] = digits[uintptr(u-q*b)] u = q } // u < base i-- a[i] = digits[uintptr(u)] } // add sign, if any if neg { i-- a[i] = '-' } dst.Write(a[i:]) }
[ "func", "formatBits", "(", "dst", "EncodingBuffer", ",", "u", "uint64", ",", "base", "int", ",", "neg", "bool", ")", "{", "if", "base", "<", "2", "||", "base", ">", "len", "(", "digits", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "// 2 <= base && base <= len(digits)", "var", "a", "[", "64", "+", "1", "]", "byte", "// +1 for sign of 64bit value in base 2", "\n", "i", ":=", "len", "(", "a", ")", "\n\n", "if", "neg", "{", "u", "=", "-", "u", "\n", "}", "\n\n", "// convert bits", "if", "base", "==", "10", "{", "// common case: use constants for / because", "// the compiler can optimize it into a multiply+shift", "if", "^", "uintptr", "(", "0", ")", ">>", "32", "==", "0", "{", "for", "u", ">", "uint64", "(", "^", "uintptr", "(", "0", ")", ")", "{", "q", ":=", "u", "/", "1e9", "\n", "us", ":=", "uintptr", "(", "u", "-", "q", "*", "1e9", ")", "// us % 1e9 fits into a uintptr", "\n", "for", "j", ":=", "9", ";", "j", ">", "0", ";", "j", "--", "{", "i", "--", "\n", "qs", ":=", "us", "/", "10", "\n", "a", "[", "i", "]", "=", "byte", "(", "us", "-", "qs", "*", "10", "+", "'0'", ")", "\n", "us", "=", "qs", "\n", "}", "\n", "u", "=", "q", "\n", "}", "\n", "}", "\n\n", "// u guaranteed to fit into a uintptr", "us", ":=", "uintptr", "(", "u", ")", "\n", "for", "us", ">=", "10", "{", "i", "--", "\n", "q", ":=", "us", "/", "10", "\n", "a", "[", "i", "]", "=", "byte", "(", "us", "-", "q", "*", "10", "+", "'0'", ")", "\n", "us", "=", "q", "\n", "}", "\n", "// u < 10", "i", "--", "\n", "a", "[", "i", "]", "=", "byte", "(", "us", "+", "'0'", ")", "\n\n", "}", "else", "if", "s", ":=", "shifts", "[", "base", "]", ";", "s", ">", "0", "{", "// base is power of 2: use shifts and masks instead of / and %", "b", ":=", "uint64", "(", "base", ")", "\n", "m", ":=", "uintptr", "(", "b", ")", "-", "1", "// == 1<<s - 1", "\n", "for", "u", ">=", "b", "{", "i", "--", "\n", "a", "[", "i", "]", "=", "digits", "[", "uintptr", "(", "u", ")", "&", "m", "]", "\n", "u", ">>=", "s", "\n", "}", "\n", "// u < base", "i", "--", "\n", "a", "[", "i", "]", "=", "digits", "[", "uintptr", "(", "u", ")", "]", "\n\n", "}", "else", "{", "// general case", "b", ":=", "uint64", "(", "base", ")", "\n", "for", "u", ">=", "b", "{", "i", "--", "\n", "q", ":=", "u", "/", "b", "\n", "a", "[", "i", "]", "=", "digits", "[", "uintptr", "(", "u", "-", "q", "*", "b", ")", "]", "\n", "u", "=", "q", "\n", "}", "\n", "// u < base", "i", "--", "\n", "a", "[", "i", "]", "=", "digits", "[", "uintptr", "(", "u", ")", "]", "\n", "}", "\n\n", "// add sign, if any", "if", "neg", "{", "i", "--", "\n", "a", "[", "i", "]", "=", "'-'", "\n", "}", "\n\n", "dst", ".", "Write", "(", "a", "[", "i", ":", "]", ")", "\n", "}" ]
// formatBits computes the string representation of u in the given base. // If neg is set, u is treated as negative int64 value.
[ "formatBits", "computes", "the", "string", "representation", "of", "u", "in", "the", "given", "base", ".", "If", "neg", "is", "set", "u", "is", "treated", "as", "negative", "int64", "value", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/fflib/v1/ftoa.go#L464-L542
151,762
pquerna/ffjson
inception/encoder.go
lastConditional
func lastConditional(fields []*StructField) bool { if len(fields) > 0 { f := fields[len(fields)-1] return f.OmitEmpty } return false }
go
func lastConditional(fields []*StructField) bool { if len(fields) > 0 { f := fields[len(fields)-1] return f.OmitEmpty } return false }
[ "func", "lastConditional", "(", "fields", "[", "]", "*", "StructField", ")", "bool", "{", "if", "len", "(", "fields", ")", ">", "0", "{", "f", ":=", "fields", "[", "len", "(", "fields", ")", "-", "1", "]", "\n", "return", "f", ".", "OmitEmpty", "\n", "}", "\n", "return", "false", "\n", "}" ]
// We check if the last field is conditional.
[ "We", "check", "if", "the", "last", "field", "is", "conditional", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/inception/encoder.go#L475-L481
151,763
pquerna/ffjson
fflib/v1/extfloat.go
Normalize
func (f *extFloat) Normalize() (shift uint) { mant, exp := f.mant, f.exp if mant == 0 { return 0 } if mant>>(64-32) == 0 { mant <<= 32 exp -= 32 } if mant>>(64-16) == 0 { mant <<= 16 exp -= 16 } if mant>>(64-8) == 0 { mant <<= 8 exp -= 8 } if mant>>(64-4) == 0 { mant <<= 4 exp -= 4 } if mant>>(64-2) == 0 { mant <<= 2 exp -= 2 } if mant>>(64-1) == 0 { mant <<= 1 exp -= 1 } shift = uint(f.exp - exp) f.mant, f.exp = mant, exp return }
go
func (f *extFloat) Normalize() (shift uint) { mant, exp := f.mant, f.exp if mant == 0 { return 0 } if mant>>(64-32) == 0 { mant <<= 32 exp -= 32 } if mant>>(64-16) == 0 { mant <<= 16 exp -= 16 } if mant>>(64-8) == 0 { mant <<= 8 exp -= 8 } if mant>>(64-4) == 0 { mant <<= 4 exp -= 4 } if mant>>(64-2) == 0 { mant <<= 2 exp -= 2 } if mant>>(64-1) == 0 { mant <<= 1 exp -= 1 } shift = uint(f.exp - exp) f.mant, f.exp = mant, exp return }
[ "func", "(", "f", "*", "extFloat", ")", "Normalize", "(", ")", "(", "shift", "uint", ")", "{", "mant", ",", "exp", ":=", "f", ".", "mant", ",", "f", ".", "exp", "\n", "if", "mant", "==", "0", "{", "return", "0", "\n", "}", "\n", "if", "mant", ">>", "(", "64", "-", "32", ")", "==", "0", "{", "mant", "<<=", "32", "\n", "exp", "-=", "32", "\n", "}", "\n", "if", "mant", ">>", "(", "64", "-", "16", ")", "==", "0", "{", "mant", "<<=", "16", "\n", "exp", "-=", "16", "\n", "}", "\n", "if", "mant", ">>", "(", "64", "-", "8", ")", "==", "0", "{", "mant", "<<=", "8", "\n", "exp", "-=", "8", "\n", "}", "\n", "if", "mant", ">>", "(", "64", "-", "4", ")", "==", "0", "{", "mant", "<<=", "4", "\n", "exp", "-=", "4", "\n", "}", "\n", "if", "mant", ">>", "(", "64", "-", "2", ")", "==", "0", "{", "mant", "<<=", "2", "\n", "exp", "-=", "2", "\n", "}", "\n", "if", "mant", ">>", "(", "64", "-", "1", ")", "==", "0", "{", "mant", "<<=", "1", "\n", "exp", "-=", "1", "\n", "}", "\n", "shift", "=", "uint", "(", "f", ".", "exp", "-", "exp", ")", "\n", "f", ".", "mant", ",", "f", ".", "exp", "=", "mant", ",", "exp", "\n", "return", "\n", "}" ]
// Normalize normalizes f so that the highest bit of the mantissa is // set, and returns the number by which the mantissa was left-shifted.
[ "Normalize", "normalizes", "f", "so", "that", "the", "highest", "bit", "of", "the", "mantissa", "is", "set", "and", "returns", "the", "number", "by", "which", "the", "mantissa", "was", "left", "-", "shifted", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/fflib/v1/extfloat.go#L199-L231
151,764
pquerna/ffjson
fflib/v1/extfloat.go
frexp10Many
func frexp10Many(a, b, c *extFloat) (exp10 int) { exp10, i := c.frexp10() a.Multiply(powersOfTen[i]) b.Multiply(powersOfTen[i]) return }
go
func frexp10Many(a, b, c *extFloat) (exp10 int) { exp10, i := c.frexp10() a.Multiply(powersOfTen[i]) b.Multiply(powersOfTen[i]) return }
[ "func", "frexp10Many", "(", "a", ",", "b", ",", "c", "*", "extFloat", ")", "(", "exp10", "int", ")", "{", "exp10", ",", "i", ":=", "c", ".", "frexp10", "(", ")", "\n", "a", ".", "Multiply", "(", "powersOfTen", "[", "i", "]", ")", "\n", "b", ".", "Multiply", "(", "powersOfTen", "[", "i", "]", ")", "\n", "return", "\n", "}" ]
// frexp10Many applies a common shift by a power of ten to a, b, c.
[ "frexp10Many", "applies", "a", "common", "shift", "by", "a", "power", "of", "ten", "to", "a", "b", "c", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/fflib/v1/extfloat.go#L368-L373
151,765
pquerna/ffjson
fflib/v1/extfloat.go
FixedDecimal
func (f *extFloat) FixedDecimal(d *decimalSlice, n int) bool { if f.mant == 0 { d.nd = 0 d.dp = 0 d.neg = f.neg return true } if n == 0 { panic("strconv: internal error: extFloat.FixedDecimal called with n == 0") } // Multiply by an appropriate power of ten to have a reasonable // number to process. f.Normalize() exp10, _ := f.frexp10() shift := uint(-f.exp) integer := uint32(f.mant >> shift) fraction := f.mant - (uint64(integer) << shift) ε := uint64(1) // ε is the uncertainty we have on the mantissa of f. // Write exactly n digits to d. needed := n // how many digits are left to write. integerDigits := 0 // the number of decimal digits of integer. pow10 := uint64(1) // the power of ten by which f was scaled. for i, pow := 0, uint64(1); i < 20; i++ { if pow > uint64(integer) { integerDigits = i break } pow *= 10 } rest := integer if integerDigits > needed { // the integral part is already large, trim the last digits. pow10 = uint64pow10[integerDigits-needed] integer /= uint32(pow10) rest -= integer * uint32(pow10) } else { rest = 0 } // Write the digits of integer: the digits of rest are omitted. var buf [32]byte pos := len(buf) for v := integer; v > 0; { v1 := v / 10 v -= 10 * v1 pos-- buf[pos] = byte(v + '0') v = v1 } for i := pos; i < len(buf); i++ { d.d[i-pos] = buf[i] } nd := len(buf) - pos d.nd = nd d.dp = integerDigits + exp10 needed -= nd if needed > 0 { if rest != 0 || pow10 != 1 { panic("strconv: internal error, rest != 0 but needed > 0") } // Emit digits for the fractional part. Each time, 10*fraction // fits in a uint64 without overflow. for needed > 0 { fraction *= 10 ε *= 10 // the uncertainty scales as we multiply by ten. if 2*ε > 1<<shift { // the error is so large it could modify which digit to write, abort. return false } digit := fraction >> shift d.d[nd] = byte(digit + '0') fraction -= digit << shift nd++ needed-- } d.nd = nd } // We have written a truncation of f (a numerator / 10^d.dp). The remaining part // can be interpreted as a small number (< 1) to be added to the last digit of the // numerator. // // If rest > 0, the amount is: // (rest<<shift | fraction) / (pow10 << shift) // fraction being known with a ±ε uncertainty. // The fact that n > 0 guarantees that pow10 << shift does not overflow a uint64. // // If rest = 0, pow10 == 1 and the amount is // fraction / (1 << shift) // fraction being known with a ±ε uncertainty. // // We pass this information to the rounding routine for adjustment. ok := adjustLastDigitFixed(d, uint64(rest)<<shift|fraction, pow10, shift, ε) if !ok { return false } // Trim trailing zeros. for i := d.nd - 1; i >= 0; i-- { if d.d[i] != '0' { d.nd = i + 1 break } } return true }
go
func (f *extFloat) FixedDecimal(d *decimalSlice, n int) bool { if f.mant == 0 { d.nd = 0 d.dp = 0 d.neg = f.neg return true } if n == 0 { panic("strconv: internal error: extFloat.FixedDecimal called with n == 0") } // Multiply by an appropriate power of ten to have a reasonable // number to process. f.Normalize() exp10, _ := f.frexp10() shift := uint(-f.exp) integer := uint32(f.mant >> shift) fraction := f.mant - (uint64(integer) << shift) ε := uint64(1) // ε is the uncertainty we have on the mantissa of f. // Write exactly n digits to d. needed := n // how many digits are left to write. integerDigits := 0 // the number of decimal digits of integer. pow10 := uint64(1) // the power of ten by which f was scaled. for i, pow := 0, uint64(1); i < 20; i++ { if pow > uint64(integer) { integerDigits = i break } pow *= 10 } rest := integer if integerDigits > needed { // the integral part is already large, trim the last digits. pow10 = uint64pow10[integerDigits-needed] integer /= uint32(pow10) rest -= integer * uint32(pow10) } else { rest = 0 } // Write the digits of integer: the digits of rest are omitted. var buf [32]byte pos := len(buf) for v := integer; v > 0; { v1 := v / 10 v -= 10 * v1 pos-- buf[pos] = byte(v + '0') v = v1 } for i := pos; i < len(buf); i++ { d.d[i-pos] = buf[i] } nd := len(buf) - pos d.nd = nd d.dp = integerDigits + exp10 needed -= nd if needed > 0 { if rest != 0 || pow10 != 1 { panic("strconv: internal error, rest != 0 but needed > 0") } // Emit digits for the fractional part. Each time, 10*fraction // fits in a uint64 without overflow. for needed > 0 { fraction *= 10 ε *= 10 // the uncertainty scales as we multiply by ten. if 2*ε > 1<<shift { // the error is so large it could modify which digit to write, abort. return false } digit := fraction >> shift d.d[nd] = byte(digit + '0') fraction -= digit << shift nd++ needed-- } d.nd = nd } // We have written a truncation of f (a numerator / 10^d.dp). The remaining part // can be interpreted as a small number (< 1) to be added to the last digit of the // numerator. // // If rest > 0, the amount is: // (rest<<shift | fraction) / (pow10 << shift) // fraction being known with a ±ε uncertainty. // The fact that n > 0 guarantees that pow10 << shift does not overflow a uint64. // // If rest = 0, pow10 == 1 and the amount is // fraction / (1 << shift) // fraction being known with a ±ε uncertainty. // // We pass this information to the rounding routine for adjustment. ok := adjustLastDigitFixed(d, uint64(rest)<<shift|fraction, pow10, shift, ε) if !ok { return false } // Trim trailing zeros. for i := d.nd - 1; i >= 0; i-- { if d.d[i] != '0' { d.nd = i + 1 break } } return true }
[ "func", "(", "f", "*", "extFloat", ")", "FixedDecimal", "(", "d", "*", "decimalSlice", ",", "n", "int", ")", "bool", "{", "if", "f", ".", "mant", "==", "0", "{", "d", ".", "nd", "=", "0", "\n", "d", ".", "dp", "=", "0", "\n", "d", ".", "neg", "=", "f", ".", "neg", "\n", "return", "true", "\n", "}", "\n", "if", "n", "==", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "// Multiply by an appropriate power of ten to have a reasonable", "// number to process.", "f", ".", "Normalize", "(", ")", "\n", "exp10", ",", "_", ":=", "f", ".", "frexp10", "(", ")", "\n\n", "shift", ":=", "uint", "(", "-", "f", ".", "exp", ")", "\n", "integer", ":=", "uint32", "(", "f", ".", "mant", ">>", "shift", ")", "\n", "fraction", ":=", "f", ".", "mant", "-", "(", "uint64", "(", "integer", ")", "<<", "shift", ")", "\n", "ε ", "= ", "int64(", "1", ")", " ", "/ ε is the uncertainty we have on the mantissa of f.", "\n\n", "// Write exactly n digits to d.", "needed", ":=", "n", "// how many digits are left to write.", "\n", "integerDigits", ":=", "0", "// the number of decimal digits of integer.", "\n", "pow10", ":=", "uint64", "(", "1", ")", "// the power of ten by which f was scaled.", "\n", "for", "i", ",", "pow", ":=", "0", ",", "uint64", "(", "1", ")", ";", "i", "<", "20", ";", "i", "++", "{", "if", "pow", ">", "uint64", "(", "integer", ")", "{", "integerDigits", "=", "i", "\n", "break", "\n", "}", "\n", "pow", "*=", "10", "\n", "}", "\n", "rest", ":=", "integer", "\n", "if", "integerDigits", ">", "needed", "{", "// the integral part is already large, trim the last digits.", "pow10", "=", "uint64pow10", "[", "integerDigits", "-", "needed", "]", "\n", "integer", "/=", "uint32", "(", "pow10", ")", "\n", "rest", "-=", "integer", "*", "uint32", "(", "pow10", ")", "\n", "}", "else", "{", "rest", "=", "0", "\n", "}", "\n\n", "// Write the digits of integer: the digits of rest are omitted.", "var", "buf", "[", "32", "]", "byte", "\n", "pos", ":=", "len", "(", "buf", ")", "\n", "for", "v", ":=", "integer", ";", "v", ">", "0", ";", "{", "v1", ":=", "v", "/", "10", "\n", "v", "-=", "10", "*", "v1", "\n", "pos", "--", "\n", "buf", "[", "pos", "]", "=", "byte", "(", "v", "+", "'0'", ")", "\n", "v", "=", "v1", "\n", "}", "\n", "for", "i", ":=", "pos", ";", "i", "<", "len", "(", "buf", ")", ";", "i", "++", "{", "d", ".", "d", "[", "i", "-", "pos", "]", "=", "buf", "[", "i", "]", "\n", "}", "\n", "nd", ":=", "len", "(", "buf", ")", "-", "pos", "\n", "d", ".", "nd", "=", "nd", "\n", "d", ".", "dp", "=", "integerDigits", "+", "exp10", "\n", "needed", "-=", "nd", "\n\n", "if", "needed", ">", "0", "{", "if", "rest", "!=", "0", "||", "pow10", "!=", "1", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "// Emit digits for the fractional part. Each time, 10*fraction", "// fits in a uint64 without overflow.", "for", "needed", ">", "0", "{", "fraction", "*=", "10", "\n", "ε ", "= ", "0 ", "/ the uncertainty scales as we multiply by ten.", "\n", "if", "2", "*", "ε ", " ", "<", "<s", "hift ", "", "// the error is so large it could modify which digit to write, abort.", "return", "false", "\n", "}", "\n", "digit", ":=", "fraction", ">>", "shift", "\n", "d", ".", "d", "[", "nd", "]", "=", "byte", "(", "digit", "+", "'0'", ")", "\n", "fraction", "-=", "digit", "<<", "shift", "\n", "nd", "++", "\n", "needed", "--", "\n", "}", "\n", "d", ".", "nd", "=", "nd", "\n", "}", "\n\n", "// We have written a truncation of f (a numerator / 10^d.dp). The remaining part", "// can be interpreted as a small number (< 1) to be added to the last digit of the", "// numerator.", "//", "// If rest > 0, the amount is:", "// (rest<<shift | fraction) / (pow10 << shift)", "// fraction being known with a ±ε uncertainty.", "// The fact that n > 0 guarantees that pow10 << shift does not overflow a uint64.", "//", "// If rest = 0, pow10 == 1 and the amount is", "// fraction / (1 << shift)", "// fraction being known with a ±ε uncertainty.", "//", "// We pass this information to the rounding routine for adjustment.", "ok", ":=", "adjustLastDigitFixed", "(", "d", ",", "uint64", "(", "rest", ")", "<<", "shift", "|", "fraction", ",", "pow10", ",", "shift", ",", "ε)", "", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "// Trim trailing zeros.", "for", "i", ":=", "d", ".", "nd", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "if", "d", ".", "d", "[", "i", "]", "!=", "'0'", "{", "d", ".", "nd", "=", "i", "+", "1", "\n", "break", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// FixedDecimal stores in d the first n significant digits // of the decimal representation of f. It returns false // if it cannot be sure of the answer.
[ "FixedDecimal", "stores", "in", "d", "the", "first", "n", "significant", "digits", "of", "the", "decimal", "representation", "of", "f", ".", "It", "returns", "false", "if", "it", "cannot", "be", "sure", "of", "the", "answer", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/fflib/v1/extfloat.go#L378-L486
151,766
pquerna/ffjson
fflib/v1/lexer.go
Reset
func (ffl *FFLexer) Reset(input []byte) { ffl.Token = FFTok_init ffl.Error = FFErr_e_ok ffl.BigError = nil ffl.reader.Reset(input) ffl.lastCurrentChar = 0 ffl.Output.Reset() }
go
func (ffl *FFLexer) Reset(input []byte) { ffl.Token = FFTok_init ffl.Error = FFErr_e_ok ffl.BigError = nil ffl.reader.Reset(input) ffl.lastCurrentChar = 0 ffl.Output.Reset() }
[ "func", "(", "ffl", "*", "FFLexer", ")", "Reset", "(", "input", "[", "]", "byte", ")", "{", "ffl", ".", "Token", "=", "FFTok_init", "\n", "ffl", ".", "Error", "=", "FFErr_e_ok", "\n", "ffl", ".", "BigError", "=", "nil", "\n", "ffl", ".", "reader", ".", "Reset", "(", "input", ")", "\n", "ffl", ".", "lastCurrentChar", "=", "0", "\n", "ffl", ".", "Output", ".", "Reset", "(", ")", "\n", "}" ]
// Reset the Lexer and add new input.
[ "Reset", "the", "Lexer", "and", "add", "new", "input", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/fflib/v1/lexer.go#L130-L137
151,767
pquerna/ffjson
fflib/v1/decimal.go
Assign
func (a *decimal) Assign(v uint64) { var buf [24]byte // Write reversed decimal in buf. n := 0 for v > 0 { v1 := v / 10 v -= 10 * v1 buf[n] = byte(v + '0') n++ v = v1 } // Reverse again to produce forward decimal in a.d. a.nd = 0 for n--; n >= 0; n-- { a.d[a.nd] = buf[n] a.nd++ } a.dp = a.nd trim(a) }
go
func (a *decimal) Assign(v uint64) { var buf [24]byte // Write reversed decimal in buf. n := 0 for v > 0 { v1 := v / 10 v -= 10 * v1 buf[n] = byte(v + '0') n++ v = v1 } // Reverse again to produce forward decimal in a.d. a.nd = 0 for n--; n >= 0; n-- { a.d[a.nd] = buf[n] a.nd++ } a.dp = a.nd trim(a) }
[ "func", "(", "a", "*", "decimal", ")", "Assign", "(", "v", "uint64", ")", "{", "var", "buf", "[", "24", "]", "byte", "\n\n", "// Write reversed decimal in buf.", "n", ":=", "0", "\n", "for", "v", ">", "0", "{", "v1", ":=", "v", "/", "10", "\n", "v", "-=", "10", "*", "v1", "\n", "buf", "[", "n", "]", "=", "byte", "(", "v", "+", "'0'", ")", "\n", "n", "++", "\n", "v", "=", "v1", "\n", "}", "\n\n", "// Reverse again to produce forward decimal in a.d.", "a", ".", "nd", "=", "0", "\n", "for", "n", "--", ";", "n", ">=", "0", ";", "n", "--", "{", "a", ".", "d", "[", "a", ".", "nd", "]", "=", "buf", "[", "n", "]", "\n", "a", ".", "nd", "++", "\n", "}", "\n", "a", ".", "dp", "=", "a", ".", "nd", "\n", "trim", "(", "a", ")", "\n", "}" ]
// Assign v to a.
[ "Assign", "v", "to", "a", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/fflib/v1/decimal.go#L81-L102
151,768
pquerna/ffjson
fflib/v1/decimal.go
prefixIsLessThan
func prefixIsLessThan(b []byte, s string) bool { for i := 0; i < len(s); i++ { if i >= len(b) { return true } if b[i] != s[i] { return b[i] < s[i] } } return false }
go
func prefixIsLessThan(b []byte, s string) bool { for i := 0; i < len(s); i++ { if i >= len(b) { return true } if b[i] != s[i] { return b[i] < s[i] } } return false }
[ "func", "prefixIsLessThan", "(", "b", "[", "]", "byte", ",", "s", "string", ")", "bool", "{", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "s", ")", ";", "i", "++", "{", "if", "i", ">=", "len", "(", "b", ")", "{", "return", "true", "\n", "}", "\n", "if", "b", "[", "i", "]", "!=", "s", "[", "i", "]", "{", "return", "b", "[", "i", "]", "<", "s", "[", "i", "]", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Is the leading prefix of b lexicographically less than s?
[ "Is", "the", "leading", "prefix", "of", "b", "lexicographically", "less", "than", "s?" ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/fflib/v1/decimal.go#L219-L229
151,769
pquerna/ffjson
fflib/v1/decimal.go
shouldRoundUp
func shouldRoundUp(a *decimal, nd int) bool { if nd < 0 || nd >= a.nd { return false } if a.d[nd] == '5' && nd+1 == a.nd { // exactly halfway - round to even // if we truncated, a little higher than what's recorded - always round up if a.trunc { return true } return nd > 0 && (a.d[nd-1]-'0')%2 != 0 } // not halfway - digit tells all return a.d[nd] >= '5' }
go
func shouldRoundUp(a *decimal, nd int) bool { if nd < 0 || nd >= a.nd { return false } if a.d[nd] == '5' && nd+1 == a.nd { // exactly halfway - round to even // if we truncated, a little higher than what's recorded - always round up if a.trunc { return true } return nd > 0 && (a.d[nd-1]-'0')%2 != 0 } // not halfway - digit tells all return a.d[nd] >= '5' }
[ "func", "shouldRoundUp", "(", "a", "*", "decimal", ",", "nd", "int", ")", "bool", "{", "if", "nd", "<", "0", "||", "nd", ">=", "a", ".", "nd", "{", "return", "false", "\n", "}", "\n", "if", "a", ".", "d", "[", "nd", "]", "==", "'5'", "&&", "nd", "+", "1", "==", "a", ".", "nd", "{", "// exactly halfway - round to even", "// if we truncated, a little higher than what's recorded - always round up", "if", "a", ".", "trunc", "{", "return", "true", "\n", "}", "\n", "return", "nd", ">", "0", "&&", "(", "a", ".", "d", "[", "nd", "-", "1", "]", "-", "'0'", ")", "%", "2", "!=", "0", "\n", "}", "\n", "// not halfway - digit tells all", "return", "a", ".", "d", "[", "nd", "]", ">=", "'5'", "\n", "}" ]
// If we chop a at nd digits, should we round up?
[ "If", "we", "chop", "a", "at", "nd", "digits", "should", "we", "round", "up?" ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/fflib/v1/decimal.go#L298-L311
151,770
pquerna/ffjson
fflib/v1/decimal.go
RoundedInteger
func (a *decimal) RoundedInteger() uint64 { if a.dp > 20 { return 0xFFFFFFFFFFFFFFFF } var i int n := uint64(0) for i = 0; i < a.dp && i < a.nd; i++ { n = n*10 + uint64(a.d[i]-'0') } for ; i < a.dp; i++ { n *= 10 } if shouldRoundUp(a, a.dp) { n++ } return n }
go
func (a *decimal) RoundedInteger() uint64 { if a.dp > 20 { return 0xFFFFFFFFFFFFFFFF } var i int n := uint64(0) for i = 0; i < a.dp && i < a.nd; i++ { n = n*10 + uint64(a.d[i]-'0') } for ; i < a.dp; i++ { n *= 10 } if shouldRoundUp(a, a.dp) { n++ } return n }
[ "func", "(", "a", "*", "decimal", ")", "RoundedInteger", "(", ")", "uint64", "{", "if", "a", ".", "dp", ">", "20", "{", "return", "0xFFFFFFFFFFFFFFFF", "\n", "}", "\n", "var", "i", "int", "\n", "n", ":=", "uint64", "(", "0", ")", "\n", "for", "i", "=", "0", ";", "i", "<", "a", ".", "dp", "&&", "i", "<", "a", ".", "nd", ";", "i", "++", "{", "n", "=", "n", "*", "10", "+", "uint64", "(", "a", ".", "d", "[", "i", "]", "-", "'0'", ")", "\n", "}", "\n", "for", ";", "i", "<", "a", ".", "dp", ";", "i", "++", "{", "n", "*=", "10", "\n", "}", "\n", "if", "shouldRoundUp", "(", "a", ",", "a", ".", "dp", ")", "{", "n", "++", "\n", "}", "\n", "return", "n", "\n", "}" ]
// Extract integer part, rounded appropriately. // No guarantees about overflow.
[ "Extract", "integer", "part", "rounded", "appropriately", ".", "No", "guarantees", "about", "overflow", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/fflib/v1/decimal.go#L362-L378
151,771
pquerna/ffjson
inception/writerstack.go
Write
func (w *ConditionalWrite) Write(s string) { w.Queued = append(w.Queued, s) }
go
func (w *ConditionalWrite) Write(s string) { w.Queued = append(w.Queued, s) }
[ "func", "(", "w", "*", "ConditionalWrite", ")", "Write", "(", "s", "string", ")", "{", "w", ".", "Queued", "=", "append", "(", "w", ".", "Queued", ",", "s", ")", "\n", "}" ]
// Write will add a string to be written
[ "Write", "will", "add", "a", "string", "to", "be", "written" ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/inception/writerstack.go#L11-L13
151,772
pquerna/ffjson
inception/writerstack.go
DeleteLast
func (w *ConditionalWrite) DeleteLast() { if len(w.Queued) == 0 { return } w.Queued = w.Queued[:len(w.Queued)-1] }
go
func (w *ConditionalWrite) DeleteLast() { if len(w.Queued) == 0 { return } w.Queued = w.Queued[:len(w.Queued)-1] }
[ "func", "(", "w", "*", "ConditionalWrite", ")", "DeleteLast", "(", ")", "{", "if", "len", "(", "w", ".", "Queued", ")", "==", "0", "{", "return", "\n", "}", "\n", "w", ".", "Queued", "=", "w", ".", "Queued", "[", ":", "len", "(", "w", ".", "Queued", ")", "-", "1", "]", "\n", "}" ]
// DeleteLast will delete the last added write
[ "DeleteLast", "will", "delete", "the", "last", "added", "write" ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/inception/writerstack.go#L16-L21
151,773
pquerna/ffjson
inception/writerstack.go
Last
func (w *ConditionalWrite) Last() string { if len(w.Queued) == 0 { return "" } return w.Queued[len(w.Queued)-1] }
go
func (w *ConditionalWrite) Last() string { if len(w.Queued) == 0 { return "" } return w.Queued[len(w.Queued)-1] }
[ "func", "(", "w", "*", "ConditionalWrite", ")", "Last", "(", ")", "string", "{", "if", "len", "(", "w", ".", "Queued", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "w", ".", "Queued", "[", "len", "(", "w", ".", "Queued", ")", "-", "1", "]", "\n", "}" ]
// Last will return the last added write
[ "Last", "will", "return", "the", "last", "added", "write" ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/inception/writerstack.go#L24-L29
151,774
pquerna/ffjson
inception/writerstack.go
WriteFlush
func (w *ConditionalWrite) WriteFlush(s string) string { w.Write(s) return w.Flush() }
go
func (w *ConditionalWrite) WriteFlush(s string) string { w.Write(s) return w.Flush() }
[ "func", "(", "w", "*", "ConditionalWrite", ")", "WriteFlush", "(", "s", "string", ")", "string", "{", "w", ".", "Write", "(", "s", ")", "\n", "return", "w", ".", "Flush", "(", ")", "\n", "}" ]
// WriteFlush will add a string and return the Flush result for the queue
[ "WriteFlush", "will", "add", "a", "string", "and", "return", "the", "Flush", "result", "for", "the", "queue" ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/inception/writerstack.go#L54-L57
151,775
pquerna/ffjson
inception/writerstack.go
GetQueued
func (w *ConditionalWrite) GetQueued() string { t := w.Queued s := w.Flush() w.Queued = t return s }
go
func (w *ConditionalWrite) GetQueued() string { t := w.Queued s := w.Flush() w.Queued = t return s }
[ "func", "(", "w", "*", "ConditionalWrite", ")", "GetQueued", "(", ")", "string", "{", "t", ":=", "w", ".", "Queued", "\n", "s", ":=", "w", ".", "Flush", "(", ")", "\n", "w", ".", "Queued", "=", "t", "\n", "return", "s", "\n", "}" ]
// GetQueued will return the current queued content without flushing.
[ "GetQueued", "will", "return", "the", "current", "queued", "content", "without", "flushing", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/inception/writerstack.go#L60-L65
151,776
pquerna/ffjson
ffjson/decoder.go
Decode
func (d *Decoder) Decode(data []byte, v interface{}) error { f, ok := v.(unmarshalFaster) if ok { if d.fs == nil { d.fs = fflib.NewFFLexer(data) } else { d.fs.Reset(data) } return f.UnmarshalJSONFFLexer(d.fs, fflib.FFParse_map_start) } um, ok := v.(json.Unmarshaler) if ok { return um.UnmarshalJSON(data) } return json.Unmarshal(data, v) }
go
func (d *Decoder) Decode(data []byte, v interface{}) error { f, ok := v.(unmarshalFaster) if ok { if d.fs == nil { d.fs = fflib.NewFFLexer(data) } else { d.fs.Reset(data) } return f.UnmarshalJSONFFLexer(d.fs, fflib.FFParse_map_start) } um, ok := v.(json.Unmarshaler) if ok { return um.UnmarshalJSON(data) } return json.Unmarshal(data, v) }
[ "func", "(", "d", "*", "Decoder", ")", "Decode", "(", "data", "[", "]", "byte", ",", "v", "interface", "{", "}", ")", "error", "{", "f", ",", "ok", ":=", "v", ".", "(", "unmarshalFaster", ")", "\n", "if", "ok", "{", "if", "d", ".", "fs", "==", "nil", "{", "d", ".", "fs", "=", "fflib", ".", "NewFFLexer", "(", "data", ")", "\n", "}", "else", "{", "d", ".", "fs", ".", "Reset", "(", "data", ")", "\n", "}", "\n", "return", "f", ".", "UnmarshalJSONFFLexer", "(", "d", ".", "fs", ",", "fflib", ".", "FFParse_map_start", ")", "\n", "}", "\n\n", "um", ",", "ok", ":=", "v", ".", "(", "json", ".", "Unmarshaler", ")", "\n", "if", "ok", "{", "return", "um", ".", "UnmarshalJSON", "(", "data", ")", "\n", "}", "\n", "return", "json", ".", "Unmarshal", "(", "data", ",", "v", ")", "\n", "}" ]
// Decode the data in the supplied data slice.
[ "Decode", "the", "data", "in", "the", "supplied", "data", "slice", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/ffjson/decoder.go#L41-L57
151,777
pquerna/ffjson
ffjson/decoder.go
DecodeReader
func (d *Decoder) DecodeReader(r io.Reader, v interface{}) error { _, ok := v.(unmarshalFaster) _, ok2 := v.(json.Unmarshaler) if ok || ok2 { data, err := ioutil.ReadAll(r) if err != nil { return err } defer fflib.Pool(data) return d.Decode(data, v) } dec := json.NewDecoder(r) return dec.Decode(v) }
go
func (d *Decoder) DecodeReader(r io.Reader, v interface{}) error { _, ok := v.(unmarshalFaster) _, ok2 := v.(json.Unmarshaler) if ok || ok2 { data, err := ioutil.ReadAll(r) if err != nil { return err } defer fflib.Pool(data) return d.Decode(data, v) } dec := json.NewDecoder(r) return dec.Decode(v) }
[ "func", "(", "d", "*", "Decoder", ")", "DecodeReader", "(", "r", "io", ".", "Reader", ",", "v", "interface", "{", "}", ")", "error", "{", "_", ",", "ok", ":=", "v", ".", "(", "unmarshalFaster", ")", "\n", "_", ",", "ok2", ":=", "v", ".", "(", "json", ".", "Unmarshaler", ")", "\n", "if", "ok", "||", "ok2", "{", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "fflib", ".", "Pool", "(", "data", ")", "\n", "return", "d", ".", "Decode", "(", "data", ",", "v", ")", "\n", "}", "\n", "dec", ":=", "json", ".", "NewDecoder", "(", "r", ")", "\n", "return", "dec", ".", "Decode", "(", "v", ")", "\n", "}" ]
// Decode the data from the supplied reader. // You should expect that data is read into memory before it is decoded.
[ "Decode", "the", "data", "from", "the", "supplied", "reader", ".", "You", "should", "expect", "that", "data", "is", "read", "into", "memory", "before", "it", "is", "decoded", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/ffjson/decoder.go#L61-L74
151,778
pquerna/ffjson
fflib/v1/internal/atof.go
readFloat
func readFloat(s []byte) (mantissa uint64, exp int, neg, trunc, ok bool) { const uint64digits = 19 i := 0 // optional sign if i >= len(s) { return } switch { case s[i] == '+': i++ case s[i] == '-': neg = true i++ } // digits sawdot := false sawdigits := false nd := 0 ndMant := 0 dp := 0 for ; i < len(s); i++ { switch c := s[i]; true { case c == '.': if sawdot { return } sawdot = true dp = nd continue case '0' <= c && c <= '9': sawdigits = true if c == '0' && nd == 0 { // ignore leading zeros dp-- continue } nd++ if ndMant < uint64digits { mantissa *= 10 mantissa += uint64(c - '0') ndMant++ } else if s[i] != '0' { trunc = true } continue } break } if !sawdigits { return } if !sawdot { dp = nd } // optional exponent moves decimal point. // if we read a very large, very long number, // just be sure to move the decimal point by // a lot (say, 100000). it doesn't matter if it's // not the exact number. if i < len(s) && (s[i] == 'e' || s[i] == 'E') { i++ if i >= len(s) { return } esign := 1 if s[i] == '+' { i++ } else if s[i] == '-' { i++ esign = -1 } if i >= len(s) || s[i] < '0' || s[i] > '9' { return } e := 0 for ; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ { if e < 10000 { e = e*10 + int(s[i]) - '0' } } dp += e * esign } if i != len(s) { return } exp = dp - ndMant ok = true return }
go
func readFloat(s []byte) (mantissa uint64, exp int, neg, trunc, ok bool) { const uint64digits = 19 i := 0 // optional sign if i >= len(s) { return } switch { case s[i] == '+': i++ case s[i] == '-': neg = true i++ } // digits sawdot := false sawdigits := false nd := 0 ndMant := 0 dp := 0 for ; i < len(s); i++ { switch c := s[i]; true { case c == '.': if sawdot { return } sawdot = true dp = nd continue case '0' <= c && c <= '9': sawdigits = true if c == '0' && nd == 0 { // ignore leading zeros dp-- continue } nd++ if ndMant < uint64digits { mantissa *= 10 mantissa += uint64(c - '0') ndMant++ } else if s[i] != '0' { trunc = true } continue } break } if !sawdigits { return } if !sawdot { dp = nd } // optional exponent moves decimal point. // if we read a very large, very long number, // just be sure to move the decimal point by // a lot (say, 100000). it doesn't matter if it's // not the exact number. if i < len(s) && (s[i] == 'e' || s[i] == 'E') { i++ if i >= len(s) { return } esign := 1 if s[i] == '+' { i++ } else if s[i] == '-' { i++ esign = -1 } if i >= len(s) || s[i] < '0' || s[i] > '9' { return } e := 0 for ; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ { if e < 10000 { e = e*10 + int(s[i]) - '0' } } dp += e * esign } if i != len(s) { return } exp = dp - ndMant ok = true return }
[ "func", "readFloat", "(", "s", "[", "]", "byte", ")", "(", "mantissa", "uint64", ",", "exp", "int", ",", "neg", ",", "trunc", ",", "ok", "bool", ")", "{", "const", "uint64digits", "=", "19", "\n", "i", ":=", "0", "\n\n", "// optional sign", "if", "i", ">=", "len", "(", "s", ")", "{", "return", "\n", "}", "\n", "switch", "{", "case", "s", "[", "i", "]", "==", "'+'", ":", "i", "++", "\n", "case", "s", "[", "i", "]", "==", "'-'", ":", "neg", "=", "true", "\n", "i", "++", "\n", "}", "\n\n", "// digits", "sawdot", ":=", "false", "\n", "sawdigits", ":=", "false", "\n", "nd", ":=", "0", "\n", "ndMant", ":=", "0", "\n", "dp", ":=", "0", "\n", "for", ";", "i", "<", "len", "(", "s", ")", ";", "i", "++", "{", "switch", "c", ":=", "s", "[", "i", "]", ";", "true", "{", "case", "c", "==", "'.'", ":", "if", "sawdot", "{", "return", "\n", "}", "\n", "sawdot", "=", "true", "\n", "dp", "=", "nd", "\n", "continue", "\n\n", "case", "'0'", "<=", "c", "&&", "c", "<=", "'9'", ":", "sawdigits", "=", "true", "\n", "if", "c", "==", "'0'", "&&", "nd", "==", "0", "{", "// ignore leading zeros", "dp", "--", "\n", "continue", "\n", "}", "\n", "nd", "++", "\n", "if", "ndMant", "<", "uint64digits", "{", "mantissa", "*=", "10", "\n", "mantissa", "+=", "uint64", "(", "c", "-", "'0'", ")", "\n", "ndMant", "++", "\n", "}", "else", "if", "s", "[", "i", "]", "!=", "'0'", "{", "trunc", "=", "true", "\n", "}", "\n", "continue", "\n", "}", "\n", "break", "\n", "}", "\n", "if", "!", "sawdigits", "{", "return", "\n", "}", "\n", "if", "!", "sawdot", "{", "dp", "=", "nd", "\n", "}", "\n\n", "// optional exponent moves decimal point.", "// if we read a very large, very long number,", "// just be sure to move the decimal point by", "// a lot (say, 100000). it doesn't matter if it's", "// not the exact number.", "if", "i", "<", "len", "(", "s", ")", "&&", "(", "s", "[", "i", "]", "==", "'e'", "||", "s", "[", "i", "]", "==", "'E'", ")", "{", "i", "++", "\n", "if", "i", ">=", "len", "(", "s", ")", "{", "return", "\n", "}", "\n", "esign", ":=", "1", "\n", "if", "s", "[", "i", "]", "==", "'+'", "{", "i", "++", "\n", "}", "else", "if", "s", "[", "i", "]", "==", "'-'", "{", "i", "++", "\n", "esign", "=", "-", "1", "\n", "}", "\n", "if", "i", ">=", "len", "(", "s", ")", "||", "s", "[", "i", "]", "<", "'0'", "||", "s", "[", "i", "]", ">", "'9'", "{", "return", "\n", "}", "\n", "e", ":=", "0", "\n", "for", ";", "i", "<", "len", "(", "s", ")", "&&", "'0'", "<=", "s", "[", "i", "]", "&&", "s", "[", "i", "]", "<=", "'9'", ";", "i", "++", "{", "if", "e", "<", "10000", "{", "e", "=", "e", "*", "10", "+", "int", "(", "s", "[", "i", "]", ")", "-", "'0'", "\n", "}", "\n", "}", "\n", "dp", "+=", "e", "*", "esign", "\n", "}", "\n\n", "if", "i", "!=", "len", "(", "s", ")", "{", "return", "\n", "}", "\n\n", "exp", "=", "dp", "-", "ndMant", "\n", "ok", "=", "true", "\n", "return", "\n\n", "}" ]
// readFloat reads a decimal mantissa and exponent from a float // string representation. It sets ok to false if the number could // not fit return types or is invalid.
[ "readFloat", "reads", "a", "decimal", "mantissa", "and", "exponent", "from", "a", "float", "string", "representation", ".", "It", "sets", "ok", "to", "false", "if", "the", "number", "could", "not", "fit", "return", "types", "or", "is", "invalid", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/fflib/v1/internal/atof.go#L176-L270
151,779
pquerna/ffjson
fflib/v1/internal/ftoa.go
appendFloat
func appendFloat(dst []byte, f float64, fmt byte, prec int, bitSize int) []byte { return genericFtoa(dst, f, fmt, prec, bitSize) }
go
func appendFloat(dst []byte, f float64, fmt byte, prec int, bitSize int) []byte { return genericFtoa(dst, f, fmt, prec, bitSize) }
[ "func", "appendFloat", "(", "dst", "[", "]", "byte", ",", "f", "float64", ",", "fmt", "byte", ",", "prec", "int", ",", "bitSize", "int", ")", "[", "]", "byte", "{", "return", "genericFtoa", "(", "dst", ",", "f", ",", "fmt", ",", "prec", ",", "bitSize", ")", "\n", "}" ]
// AppendFloat appends the string form of the floating-point number f, // as generated by FormatFloat, to dst and returns the extended buffer.
[ "AppendFloat", "appends", "the", "string", "form", "of", "the", "floating", "-", "point", "number", "f", "as", "generated", "by", "FormatFloat", "to", "dst", "and", "returns", "the", "extended", "buffer", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/fflib/v1/internal/ftoa.go#L50-L52
151,780
pquerna/ffjson
ffjson/encoder.go
NewEncoder
func NewEncoder(w io.Writer) *Encoder { return &Encoder{w: w, enc: json.NewEncoder(w)} }
go
func NewEncoder(w io.Writer) *Encoder { return &Encoder{w: w, enc: json.NewEncoder(w)} }
[ "func", "NewEncoder", "(", "w", "io", ".", "Writer", ")", "*", "Encoder", "{", "return", "&", "Encoder", "{", "w", ":", "w", ",", "enc", ":", "json", ".", "NewEncoder", "(", "w", ")", "}", "\n", "}" ]
// NewEncoder returns a reusable Encoder. // Output will be written to the supplied writer.
[ "NewEncoder", "returns", "a", "reusable", "Encoder", ".", "Output", "will", "be", "written", "to", "the", "supplied", "writer", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/ffjson/encoder.go#L50-L52
151,781
pquerna/ffjson
ffjson/encoder.go
Encode
func (e *Encoder) Encode(v interface{}) error { f, ok := v.(marshalerFaster) if ok { e.buf.Reset() err := f.MarshalJSONBuf(&e.buf) if err != nil { return err } _, err = io.Copy(e.w, &e.buf) return err } return e.enc.Encode(v) }
go
func (e *Encoder) Encode(v interface{}) error { f, ok := v.(marshalerFaster) if ok { e.buf.Reset() err := f.MarshalJSONBuf(&e.buf) if err != nil { return err } _, err = io.Copy(e.w, &e.buf) return err } return e.enc.Encode(v) }
[ "func", "(", "e", "*", "Encoder", ")", "Encode", "(", "v", "interface", "{", "}", ")", "error", "{", "f", ",", "ok", ":=", "v", ".", "(", "marshalerFaster", ")", "\n", "if", "ok", "{", "e", ".", "buf", ".", "Reset", "(", ")", "\n", "err", ":=", "f", ".", "MarshalJSONBuf", "(", "&", "e", ".", "buf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "e", ".", "w", ",", "&", "e", ".", "buf", ")", "\n", "return", "err", "\n", "}", "\n\n", "return", "e", ".", "enc", ".", "Encode", "(", "v", ")", "\n", "}" ]
// Encode the data in the supplied value to the stream // given on creation. // When the function returns the output has been // written to the stream.
[ "Encode", "the", "data", "in", "the", "supplied", "value", "to", "the", "stream", "given", "on", "creation", ".", "When", "the", "function", "returns", "the", "output", "has", "been", "written", "to", "the", "stream", "." ]
e517b90714f7c0eabe6d2e570a5886ae077d6db6
https://github.com/pquerna/ffjson/blob/e517b90714f7c0eabe6d2e570a5886ae077d6db6/ffjson/encoder.go#L58-L72
151,782
araddon/dateparse
parseany.go
MustParse
func MustParse(datestr string) time.Time { p, err := parseTime(datestr, nil) if err != nil { panic(err.Error()) } t, err := p.parse() if err != nil { panic(err.Error()) } return t }
go
func MustParse(datestr string) time.Time { p, err := parseTime(datestr, nil) if err != nil { panic(err.Error()) } t, err := p.parse() if err != nil { panic(err.Error()) } return t }
[ "func", "MustParse", "(", "datestr", "string", ")", "time", ".", "Time", "{", "p", ",", "err", ":=", "parseTime", "(", "datestr", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "t", ",", "err", ":=", "p", ".", "parse", "(", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "t", "\n", "}" ]
// MustParse parse a date, and panic if it can't be parsed. Used for testing. // Not recommended for most use-cases.
[ "MustParse", "parse", "a", "date", "and", "panic", "if", "it", "can", "t", "be", "parsed", ".", "Used", "for", "testing", ".", "Not", "recommended", "for", "most", "use", "-", "cases", "." ]
0d74ffceef83c568c4c47a6e74de8ee5c5955048
https://github.com/araddon/dateparse/blob/0d74ffceef83c568c4c47a6e74de8ee5c5955048/parseany.go#L169-L179
151,783
ulule/limiter
limiter.go
New
func New(store Store, rate Rate, options ...Option) *Limiter { opt := Options{ IPv4Mask: DefaultIPv4Mask, IPv6Mask: DefaultIPv6Mask, TrustForwardHeader: false, } for _, o := range options { o(&opt) } return &Limiter{ Store: store, Rate: rate, Options: opt, } }
go
func New(store Store, rate Rate, options ...Option) *Limiter { opt := Options{ IPv4Mask: DefaultIPv4Mask, IPv6Mask: DefaultIPv6Mask, TrustForwardHeader: false, } for _, o := range options { o(&opt) } return &Limiter{ Store: store, Rate: rate, Options: opt, } }
[ "func", "New", "(", "store", "Store", ",", "rate", "Rate", ",", "options", "...", "Option", ")", "*", "Limiter", "{", "opt", ":=", "Options", "{", "IPv4Mask", ":", "DefaultIPv4Mask", ",", "IPv6Mask", ":", "DefaultIPv6Mask", ",", "TrustForwardHeader", ":", "false", ",", "}", "\n", "for", "_", ",", "o", ":=", "range", "options", "{", "o", "(", "&", "opt", ")", "\n", "}", "\n", "return", "&", "Limiter", "{", "Store", ":", "store", ",", "Rate", ":", "rate", ",", "Options", ":", "opt", ",", "}", "\n", "}" ]
// New returns an instance of Limiter.
[ "New", "returns", "an", "instance", "of", "Limiter", "." ]
d1a9972e76c234debd9f4cf39c847ea174f0faa4
https://github.com/ulule/limiter/blob/d1a9972e76c234debd9f4cf39c847ea174f0faa4/limiter.go#L31-L45
151,784
ulule/limiter
limiter.go
Peek
func (limiter *Limiter) Peek(ctx context.Context, key string) (Context, error) { return limiter.Store.Peek(ctx, key, limiter.Rate) }
go
func (limiter *Limiter) Peek(ctx context.Context, key string) (Context, error) { return limiter.Store.Peek(ctx, key, limiter.Rate) }
[ "func", "(", "limiter", "*", "Limiter", ")", "Peek", "(", "ctx", "context", ".", "Context", ",", "key", "string", ")", "(", "Context", ",", "error", ")", "{", "return", "limiter", ".", "Store", ".", "Peek", "(", "ctx", ",", "key", ",", "limiter", ".", "Rate", ")", "\n", "}" ]
// Peek returns the limit for given identifier, without modification on current values.
[ "Peek", "returns", "the", "limit", "for", "given", "identifier", "without", "modification", "on", "current", "values", "." ]
d1a9972e76c234debd9f4cf39c847ea174f0faa4
https://github.com/ulule/limiter/blob/d1a9972e76c234debd9f4cf39c847ea174f0faa4/limiter.go#L53-L55
151,785
ulule/limiter
drivers/middleware/stdlib/middleware.go
Handler
func (middleware *Middleware) Handler(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { context, err := middleware.Limiter.Get(r.Context(), middleware.Limiter.GetIPKey(r)) if err != nil { middleware.OnError(w, r, err) return } w.Header().Add("X-RateLimit-Limit", strconv.FormatInt(context.Limit, 10)) w.Header().Add("X-RateLimit-Remaining", strconv.FormatInt(context.Remaining, 10)) w.Header().Add("X-RateLimit-Reset", strconv.FormatInt(context.Reset, 10)) if context.Reached { middleware.OnLimitReached(w, r) return } h.ServeHTTP(w, r) }) }
go
func (middleware *Middleware) Handler(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { context, err := middleware.Limiter.Get(r.Context(), middleware.Limiter.GetIPKey(r)) if err != nil { middleware.OnError(w, r, err) return } w.Header().Add("X-RateLimit-Limit", strconv.FormatInt(context.Limit, 10)) w.Header().Add("X-RateLimit-Remaining", strconv.FormatInt(context.Remaining, 10)) w.Header().Add("X-RateLimit-Reset", strconv.FormatInt(context.Reset, 10)) if context.Reached { middleware.OnLimitReached(w, r) return } h.ServeHTTP(w, r) }) }
[ "func", "(", "middleware", "*", "Middleware", ")", "Handler", "(", "h", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "context", ",", "err", ":=", "middleware", ".", "Limiter", ".", "Get", "(", "r", ".", "Context", "(", ")", ",", "middleware", ".", "Limiter", ".", "GetIPKey", "(", "r", ")", ")", "\n", "if", "err", "!=", "nil", "{", "middleware", ".", "OnError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "w", ".", "Header", "(", ")", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "context", ".", "Limit", ",", "10", ")", ")", "\n", "w", ".", "Header", "(", ")", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "context", ".", "Remaining", ",", "10", ")", ")", "\n", "w", ".", "Header", "(", ")", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "context", ".", "Reset", ",", "10", ")", ")", "\n\n", "if", "context", ".", "Reached", "{", "middleware", ".", "OnLimitReached", "(", "w", ",", "r", ")", "\n", "return", "\n", "}", "\n\n", "h", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", ")", "\n", "}" ]
// Handler the middleware handler.
[ "Handler", "the", "middleware", "handler", "." ]
d1a9972e76c234debd9f4cf39c847ea174f0faa4
https://github.com/ulule/limiter/blob/d1a9972e76c234debd9f4cf39c847ea174f0faa4/drivers/middleware/stdlib/middleware.go#L34-L53
151,786
ulule/limiter
drivers/store/common/context.go
GetContextFromState
func GetContextFromState(now time.Time, rate limiter.Rate, expiration time.Time, count int64) limiter.Context { limit := rate.Limit remaining := int64(0) reached := true if count <= limit { remaining = limit - count reached = false } reset := expiration.Unix() return limiter.Context{ Limit: limit, Remaining: remaining, Reset: reset, Reached: reached, } }
go
func GetContextFromState(now time.Time, rate limiter.Rate, expiration time.Time, count int64) limiter.Context { limit := rate.Limit remaining := int64(0) reached := true if count <= limit { remaining = limit - count reached = false } reset := expiration.Unix() return limiter.Context{ Limit: limit, Remaining: remaining, Reset: reset, Reached: reached, } }
[ "func", "GetContextFromState", "(", "now", "time", ".", "Time", ",", "rate", "limiter", ".", "Rate", ",", "expiration", "time", ".", "Time", ",", "count", "int64", ")", "limiter", ".", "Context", "{", "limit", ":=", "rate", ".", "Limit", "\n", "remaining", ":=", "int64", "(", "0", ")", "\n", "reached", ":=", "true", "\n\n", "if", "count", "<=", "limit", "{", "remaining", "=", "limit", "-", "count", "\n", "reached", "=", "false", "\n", "}", "\n\n", "reset", ":=", "expiration", ".", "Unix", "(", ")", "\n\n", "return", "limiter", ".", "Context", "{", "Limit", ":", "limit", ",", "Remaining", ":", "remaining", ",", "Reset", ":", "reset", ",", "Reached", ":", "reached", ",", "}", "\n", "}" ]
// GetContextFromState generate a new limiter.Context from given state.
[ "GetContextFromState", "generate", "a", "new", "limiter", ".", "Context", "from", "given", "state", "." ]
d1a9972e76c234debd9f4cf39c847ea174f0faa4
https://github.com/ulule/limiter/blob/d1a9972e76c234debd9f4cf39c847ea174f0faa4/drivers/store/common/context.go#L10-L28
151,787
ulule/limiter
drivers/store/memory/cache.go
Run
func (cleaner *cleaner) Run(cache *Cache) { ticker := time.NewTicker(cleaner.interval) for { select { case <-ticker.C: cache.Clean() case <-cleaner.stop: ticker.Stop() return } } }
go
func (cleaner *cleaner) Run(cache *Cache) { ticker := time.NewTicker(cleaner.interval) for { select { case <-ticker.C: cache.Clean() case <-cleaner.stop: ticker.Stop() return } } }
[ "func", "(", "cleaner", "*", "cleaner", ")", "Run", "(", "cache", "*", "Cache", ")", "{", "ticker", ":=", "time", ".", "NewTicker", "(", "cleaner", ".", "interval", ")", "\n", "for", "{", "select", "{", "case", "<-", "ticker", ".", "C", ":", "cache", ".", "Clean", "(", ")", "\n", "case", "<-", "cleaner", ".", "stop", ":", "ticker", ".", "Stop", "(", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// Run will periodically delete expired keys from given cache until GC notify that it should stop.
[ "Run", "will", "periodically", "delete", "expired", "keys", "from", "given", "cache", "until", "GC", "notify", "that", "it", "should", "stop", "." ]
d1a9972e76c234debd9f4cf39c847ea174f0faa4
https://github.com/ulule/limiter/blob/d1a9972e76c234debd9f4cf39c847ea174f0faa4/drivers/store/memory/cache.go#L24-L35
151,788
ulule/limiter
drivers/store/memory/cache.go
startCleaner
func startCleaner(cache *Cache, interval time.Duration) { cleaner := &cleaner{ interval: interval, stop: make(chan bool), } cache.cleaner = cleaner go cleaner.Run(cache) }
go
func startCleaner(cache *Cache, interval time.Duration) { cleaner := &cleaner{ interval: interval, stop: make(chan bool), } cache.cleaner = cleaner go cleaner.Run(cache) }
[ "func", "startCleaner", "(", "cache", "*", "Cache", ",", "interval", "time", ".", "Duration", ")", "{", "cleaner", ":=", "&", "cleaner", "{", "interval", ":", "interval", ",", "stop", ":", "make", "(", "chan", "bool", ")", ",", "}", "\n\n", "cache", ".", "cleaner", "=", "cleaner", "\n", "go", "cleaner", ".", "Run", "(", "cache", ")", "\n", "}" ]
// startCleaner will start a cleaner goroutine for given cache.
[ "startCleaner", "will", "start", "a", "cleaner", "goroutine", "for", "given", "cache", "." ]
d1a9972e76c234debd9f4cf39c847ea174f0faa4
https://github.com/ulule/limiter/blob/d1a9972e76c234debd9f4cf39c847ea174f0faa4/drivers/store/memory/cache.go#L43-L51
151,789
ulule/limiter
drivers/store/memory/cache.go
Expired
func (counter Counter) Expired() bool { if counter.Expiration == 0 { return false } return time.Now().UnixNano() > counter.Expiration }
go
func (counter Counter) Expired() bool { if counter.Expiration == 0 { return false } return time.Now().UnixNano() > counter.Expiration }
[ "func", "(", "counter", "Counter", ")", "Expired", "(", ")", "bool", "{", "if", "counter", ".", "Expiration", "==", "0", "{", "return", "false", "\n", "}", "\n", "return", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ">", "counter", ".", "Expiration", "\n", "}" ]
// Expired returns true if the counter has expired.
[ "Expired", "returns", "true", "if", "the", "counter", "has", "expired", "." ]
d1a9972e76c234debd9f4cf39c847ea174f0faa4
https://github.com/ulule/limiter/blob/d1a9972e76c234debd9f4cf39c847ea174f0faa4/drivers/store/memory/cache.go#L60-L65
151,790
ulule/limiter
drivers/store/memory/cache.go
NewCache
func NewCache(cleanInterval time.Duration) *CacheWrapper { cache := &Cache{ counters: map[string]Counter{}, } wrapper := &CacheWrapper{Cache: cache} if cleanInterval > 0 { startCleaner(cache, cleanInterval) runtime.SetFinalizer(wrapper, stopCleaner) } return wrapper }
go
func NewCache(cleanInterval time.Duration) *CacheWrapper { cache := &Cache{ counters: map[string]Counter{}, } wrapper := &CacheWrapper{Cache: cache} if cleanInterval > 0 { startCleaner(cache, cleanInterval) runtime.SetFinalizer(wrapper, stopCleaner) } return wrapper }
[ "func", "NewCache", "(", "cleanInterval", "time", ".", "Duration", ")", "*", "CacheWrapper", "{", "cache", ":=", "&", "Cache", "{", "counters", ":", "map", "[", "string", "]", "Counter", "{", "}", ",", "}", "\n\n", "wrapper", ":=", "&", "CacheWrapper", "{", "Cache", ":", "cache", "}", "\n\n", "if", "cleanInterval", ">", "0", "{", "startCleaner", "(", "cache", ",", "cleanInterval", ")", "\n", "runtime", ".", "SetFinalizer", "(", "wrapper", ",", "stopCleaner", ")", "\n", "}", "\n\n", "return", "wrapper", "\n", "}" ]
// NewCache returns a new cache.
[ "NewCache", "returns", "a", "new", "cache", "." ]
d1a9972e76c234debd9f4cf39c847ea174f0faa4
https://github.com/ulule/limiter/blob/d1a9972e76c234debd9f4cf39c847ea174f0faa4/drivers/store/memory/cache.go#L75-L89
151,791
ulule/limiter
drivers/store/memory/cache.go
Increment
func (cache *Cache) Increment(key string, value int64, duration time.Duration) (int64, time.Time) { cache.mutex.Lock() counter, ok := cache.counters[key] if !ok || counter.Expired() { expiration := time.Now().Add(duration).UnixNano() counter = Counter{ Value: value, Expiration: expiration, } cache.counters[key] = counter cache.mutex.Unlock() return value, time.Unix(0, expiration) } value = counter.Value + value counter.Value = value expiration := counter.Expiration cache.counters[key] = counter cache.mutex.Unlock() return value, time.Unix(0, expiration) }
go
func (cache *Cache) Increment(key string, value int64, duration time.Duration) (int64, time.Time) { cache.mutex.Lock() counter, ok := cache.counters[key] if !ok || counter.Expired() { expiration := time.Now().Add(duration).UnixNano() counter = Counter{ Value: value, Expiration: expiration, } cache.counters[key] = counter cache.mutex.Unlock() return value, time.Unix(0, expiration) } value = counter.Value + value counter.Value = value expiration := counter.Expiration cache.counters[key] = counter cache.mutex.Unlock() return value, time.Unix(0, expiration) }
[ "func", "(", "cache", "*", "Cache", ")", "Increment", "(", "key", "string", ",", "value", "int64", ",", "duration", "time", ".", "Duration", ")", "(", "int64", ",", "time", ".", "Time", ")", "{", "cache", ".", "mutex", ".", "Lock", "(", ")", "\n\n", "counter", ",", "ok", ":=", "cache", ".", "counters", "[", "key", "]", "\n", "if", "!", "ok", "||", "counter", ".", "Expired", "(", ")", "{", "expiration", ":=", "time", ".", "Now", "(", ")", ".", "Add", "(", "duration", ")", ".", "UnixNano", "(", ")", "\n", "counter", "=", "Counter", "{", "Value", ":", "value", ",", "Expiration", ":", "expiration", ",", "}", "\n\n", "cache", ".", "counters", "[", "key", "]", "=", "counter", "\n", "cache", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "return", "value", ",", "time", ".", "Unix", "(", "0", ",", "expiration", ")", "\n", "}", "\n\n", "value", "=", "counter", ".", "Value", "+", "value", "\n", "counter", ".", "Value", "=", "value", "\n", "expiration", ":=", "counter", ".", "Expiration", "\n\n", "cache", ".", "counters", "[", "key", "]", "=", "counter", "\n", "cache", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "return", "value", ",", "time", ".", "Unix", "(", "0", ",", "expiration", ")", "\n", "}" ]
// Increment increments given value on key. // If key is undefined or expired, it will create it.
[ "Increment", "increments", "given", "value", "on", "key", ".", "If", "key", "is", "undefined", "or", "expired", "it", "will", "create", "it", "." ]
d1a9972e76c234debd9f4cf39c847ea174f0faa4
https://github.com/ulule/limiter/blob/d1a9972e76c234debd9f4cf39c847ea174f0faa4/drivers/store/memory/cache.go#L93-L118
151,792
ulule/limiter
drivers/store/memory/cache.go
Get
func (cache *Cache) Get(key string, duration time.Duration) (int64, time.Time) { cache.mutex.RLock() counter, ok := cache.counters[key] if !ok || counter.Expired() { expiration := time.Now().Add(duration).UnixNano() cache.mutex.RUnlock() return 0, time.Unix(0, expiration) } value := counter.Value expiration := counter.Expiration cache.mutex.RUnlock() return value, time.Unix(0, expiration) }
go
func (cache *Cache) Get(key string, duration time.Duration) (int64, time.Time) { cache.mutex.RLock() counter, ok := cache.counters[key] if !ok || counter.Expired() { expiration := time.Now().Add(duration).UnixNano() cache.mutex.RUnlock() return 0, time.Unix(0, expiration) } value := counter.Value expiration := counter.Expiration cache.mutex.RUnlock() return value, time.Unix(0, expiration) }
[ "func", "(", "cache", "*", "Cache", ")", "Get", "(", "key", "string", ",", "duration", "time", ".", "Duration", ")", "(", "int64", ",", "time", ".", "Time", ")", "{", "cache", ".", "mutex", ".", "RLock", "(", ")", "\n\n", "counter", ",", "ok", ":=", "cache", ".", "counters", "[", "key", "]", "\n", "if", "!", "ok", "||", "counter", ".", "Expired", "(", ")", "{", "expiration", ":=", "time", ".", "Now", "(", ")", ".", "Add", "(", "duration", ")", ".", "UnixNano", "(", ")", "\n", "cache", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "0", ",", "time", ".", "Unix", "(", "0", ",", "expiration", ")", "\n", "}", "\n\n", "value", ":=", "counter", ".", "Value", "\n", "expiration", ":=", "counter", ".", "Expiration", "\n", "cache", ".", "mutex", ".", "RUnlock", "(", ")", "\n\n", "return", "value", ",", "time", ".", "Unix", "(", "0", ",", "expiration", ")", "\n", "}" ]
// Get returns key's value and expiration.
[ "Get", "returns", "key", "s", "value", "and", "expiration", "." ]
d1a9972e76c234debd9f4cf39c847ea174f0faa4
https://github.com/ulule/limiter/blob/d1a9972e76c234debd9f4cf39c847ea174f0faa4/drivers/store/memory/cache.go#L121-L136
151,793
ulule/limiter
drivers/store/memory/cache.go
Clean
func (cache *Cache) Clean() { now := time.Now().UnixNano() cache.mutex.Lock() for key, counter := range cache.counters { if now > counter.Expiration { delete(cache.counters, key) } } cache.mutex.Unlock() }
go
func (cache *Cache) Clean() { now := time.Now().UnixNano() cache.mutex.Lock() for key, counter := range cache.counters { if now > counter.Expiration { delete(cache.counters, key) } } cache.mutex.Unlock() }
[ "func", "(", "cache", "*", "Cache", ")", "Clean", "(", ")", "{", "now", ":=", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "\n\n", "cache", ".", "mutex", ".", "Lock", "(", ")", "\n", "for", "key", ",", "counter", ":=", "range", "cache", ".", "counters", "{", "if", "now", ">", "counter", ".", "Expiration", "{", "delete", "(", "cache", ".", "counters", ",", "key", ")", "\n", "}", "\n", "}", "\n", "cache", ".", "mutex", ".", "Unlock", "(", ")", "\n", "}" ]
// Clean will deleted any expired keys.
[ "Clean", "will", "deleted", "any", "expired", "keys", "." ]
d1a9972e76c234debd9f4cf39c847ea174f0faa4
https://github.com/ulule/limiter/blob/d1a9972e76c234debd9f4cf39c847ea174f0faa4/drivers/store/memory/cache.go#L139-L149
151,794
ulule/limiter
drivers/middleware/gin/middleware.go
Handle
func (middleware *Middleware) Handle(c *gin.Context) { key := middleware.KeyGetter(c) context, err := middleware.Limiter.Get(c, key) if err != nil { middleware.OnError(c, err) c.Abort() return } c.Header("X-RateLimit-Limit", strconv.FormatInt(context.Limit, 10)) c.Header("X-RateLimit-Remaining", strconv.FormatInt(context.Remaining, 10)) c.Header("X-RateLimit-Reset", strconv.FormatInt(context.Reset, 10)) if context.Reached { middleware.OnLimitReached(c) c.Abort() return } c.Next() }
go
func (middleware *Middleware) Handle(c *gin.Context) { key := middleware.KeyGetter(c) context, err := middleware.Limiter.Get(c, key) if err != nil { middleware.OnError(c, err) c.Abort() return } c.Header("X-RateLimit-Limit", strconv.FormatInt(context.Limit, 10)) c.Header("X-RateLimit-Remaining", strconv.FormatInt(context.Remaining, 10)) c.Header("X-RateLimit-Reset", strconv.FormatInt(context.Reset, 10)) if context.Reached { middleware.OnLimitReached(c) c.Abort() return } c.Next() }
[ "func", "(", "middleware", "*", "Middleware", ")", "Handle", "(", "c", "*", "gin", ".", "Context", ")", "{", "key", ":=", "middleware", ".", "KeyGetter", "(", "c", ")", "\n", "context", ",", "err", ":=", "middleware", ".", "Limiter", ".", "Get", "(", "c", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "middleware", ".", "OnError", "(", "c", ",", "err", ")", "\n", "c", ".", "Abort", "(", ")", "\n", "return", "\n", "}", "\n\n", "c", ".", "Header", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "context", ".", "Limit", ",", "10", ")", ")", "\n", "c", ".", "Header", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "context", ".", "Remaining", ",", "10", ")", ")", "\n", "c", ".", "Header", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "context", ".", "Reset", ",", "10", ")", ")", "\n\n", "if", "context", ".", "Reached", "{", "middleware", ".", "OnLimitReached", "(", "c", ")", "\n", "c", ".", "Abort", "(", ")", "\n", "return", "\n", "}", "\n\n", "c", ".", "Next", "(", ")", "\n", "}" ]
// Handle gin request.
[ "Handle", "gin", "request", "." ]
d1a9972e76c234debd9f4cf39c847ea174f0faa4
https://github.com/ulule/limiter/blob/d1a9972e76c234debd9f4cf39c847ea174f0faa4/drivers/middleware/gin/middleware.go#L38-L58
151,795
ulule/limiter
drivers/middleware/gin/options.go
WithErrorHandler
func WithErrorHandler(handler ErrorHandler) Option { return option(func(middleware *Middleware) { middleware.OnError = handler }) }
go
func WithErrorHandler(handler ErrorHandler) Option { return option(func(middleware *Middleware) { middleware.OnError = handler }) }
[ "func", "WithErrorHandler", "(", "handler", "ErrorHandler", ")", "Option", "{", "return", "option", "(", "func", "(", "middleware", "*", "Middleware", ")", "{", "middleware", ".", "OnError", "=", "handler", "\n", "}", ")", "\n", "}" ]
// WithErrorHandler will configure the Middleware to use the given ErrorHandler.
[ "WithErrorHandler", "will", "configure", "the", "Middleware", "to", "use", "the", "given", "ErrorHandler", "." ]
d1a9972e76c234debd9f4cf39c847ea174f0faa4
https://github.com/ulule/limiter/blob/d1a9972e76c234debd9f4cf39c847ea174f0faa4/drivers/middleware/gin/options.go#L24-L28
151,796
ulule/limiter
drivers/middleware/gin/options.go
WithLimitReachedHandler
func WithLimitReachedHandler(handler LimitReachedHandler) Option { return option(func(middleware *Middleware) { middleware.OnLimitReached = handler }) }
go
func WithLimitReachedHandler(handler LimitReachedHandler) Option { return option(func(middleware *Middleware) { middleware.OnLimitReached = handler }) }
[ "func", "WithLimitReachedHandler", "(", "handler", "LimitReachedHandler", ")", "Option", "{", "return", "option", "(", "func", "(", "middleware", "*", "Middleware", ")", "{", "middleware", ".", "OnLimitReached", "=", "handler", "\n", "}", ")", "\n", "}" ]
// WithLimitReachedHandler will configure the Middleware to use the given LimitReachedHandler.
[ "WithLimitReachedHandler", "will", "configure", "the", "Middleware", "to", "use", "the", "given", "LimitReachedHandler", "." ]
d1a9972e76c234debd9f4cf39c847ea174f0faa4
https://github.com/ulule/limiter/blob/d1a9972e76c234debd9f4cf39c847ea174f0faa4/drivers/middleware/gin/options.go#L39-L43
151,797
ulule/limiter
drivers/middleware/gin/options.go
WithKeyGetter
func WithKeyGetter(KeyGetter KeyGetter) Option { return option(func(middleware *Middleware) { middleware.KeyGetter = KeyGetter }) }
go
func WithKeyGetter(KeyGetter KeyGetter) Option { return option(func(middleware *Middleware) { middleware.KeyGetter = KeyGetter }) }
[ "func", "WithKeyGetter", "(", "KeyGetter", "KeyGetter", ")", "Option", "{", "return", "option", "(", "func", "(", "middleware", "*", "Middleware", ")", "{", "middleware", ".", "KeyGetter", "=", "KeyGetter", "\n", "}", ")", "\n", "}" ]
// WithKeyGetter will configure the Middleware to use the given KeyGetter
[ "WithKeyGetter", "will", "configure", "the", "Middleware", "to", "use", "the", "given", "KeyGetter" ]
d1a9972e76c234debd9f4cf39c847ea174f0faa4
https://github.com/ulule/limiter/blob/d1a9972e76c234debd9f4cf39c847ea174f0faa4/drivers/middleware/gin/options.go#L54-L58
151,798
ulule/limiter
rate.go
NewRateFromFormatted
func NewRateFromFormatted(formatted string) (Rate, error) { rate := Rate{} values := strings.Split(formatted, "-") if len(values) != 2 { return rate, errors.Errorf("incorrect format '%s'", formatted) } periods := map[string]time.Duration{ "S": time.Second, // Second "M": time.Minute, // Minute "H": time.Hour, // Hour } limit, period := values[0], strings.ToUpper(values[1]) duration, ok := periods[period] if !ok { return rate, errors.Errorf("incorrect period '%s'", period) } p := 1 * duration l, err := strconv.ParseInt(limit, 10, 64) if err != nil { return rate, errors.Errorf("incorrect limit '%s'", limit) } rate = Rate{ Formatted: formatted, Period: p, Limit: l, } return rate, nil }
go
func NewRateFromFormatted(formatted string) (Rate, error) { rate := Rate{} values := strings.Split(formatted, "-") if len(values) != 2 { return rate, errors.Errorf("incorrect format '%s'", formatted) } periods := map[string]time.Duration{ "S": time.Second, // Second "M": time.Minute, // Minute "H": time.Hour, // Hour } limit, period := values[0], strings.ToUpper(values[1]) duration, ok := periods[period] if !ok { return rate, errors.Errorf("incorrect period '%s'", period) } p := 1 * duration l, err := strconv.ParseInt(limit, 10, 64) if err != nil { return rate, errors.Errorf("incorrect limit '%s'", limit) } rate = Rate{ Formatted: formatted, Period: p, Limit: l, } return rate, nil }
[ "func", "NewRateFromFormatted", "(", "formatted", "string", ")", "(", "Rate", ",", "error", ")", "{", "rate", ":=", "Rate", "{", "}", "\n\n", "values", ":=", "strings", ".", "Split", "(", "formatted", ",", "\"", "\"", ")", "\n", "if", "len", "(", "values", ")", "!=", "2", "{", "return", "rate", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "formatted", ")", "\n", "}", "\n\n", "periods", ":=", "map", "[", "string", "]", "time", ".", "Duration", "{", "\"", "\"", ":", "time", ".", "Second", ",", "// Second", "\"", "\"", ":", "time", ".", "Minute", ",", "// Minute", "\"", "\"", ":", "time", ".", "Hour", ",", "// Hour", "}", "\n\n", "limit", ",", "period", ":=", "values", "[", "0", "]", ",", "strings", ".", "ToUpper", "(", "values", "[", "1", "]", ")", "\n\n", "duration", ",", "ok", ":=", "periods", "[", "period", "]", "\n", "if", "!", "ok", "{", "return", "rate", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "period", ")", "\n", "}", "\n\n", "p", ":=", "1", "*", "duration", "\n", "l", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "limit", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "rate", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "limit", ")", "\n", "}", "\n\n", "rate", "=", "Rate", "{", "Formatted", ":", "formatted", ",", "Period", ":", "p", ",", "Limit", ":", "l", ",", "}", "\n\n", "return", "rate", ",", "nil", "\n", "}" ]
// NewRateFromFormatted returns the rate from the formatted version.
[ "NewRateFromFormatted", "returns", "the", "rate", "from", "the", "formatted", "version", "." ]
d1a9972e76c234debd9f4cf39c847ea174f0faa4
https://github.com/ulule/limiter/blob/d1a9972e76c234debd9f4cf39c847ea174f0faa4/rate.go#L19-L53
151,799
ulule/limiter
options.go
WithIPv4Mask
func WithIPv4Mask(mask net.IPMask) Option { return func(o *Options) { o.IPv4Mask = mask } }
go
func WithIPv4Mask(mask net.IPMask) Option { return func(o *Options) { o.IPv4Mask = mask } }
[ "func", "WithIPv4Mask", "(", "mask", "net", ".", "IPMask", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "{", "o", ".", "IPv4Mask", "=", "mask", "\n", "}", "\n", "}" ]
// WithIPv4Mask will configure the limiter to use given mask for IPv4 address.
[ "WithIPv4Mask", "will", "configure", "the", "limiter", "to", "use", "given", "mask", "for", "IPv4", "address", "." ]
d1a9972e76c234debd9f4cf39c847ea174f0faa4
https://github.com/ulule/limiter/blob/d1a9972e76c234debd9f4cf39c847ea174f0faa4/options.go#L21-L25