-
Notifications
You must be signed in to change notification settings - Fork 1
/
helpers.go
65 lines (51 loc) · 1.46 KB
/
helpers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Package vector_tile provides the go code needed to read and write
// Mapbox vector tiles (https://github.com/mapbox/vector-tile-spec).
// Most of the code is autogenerated, but there are a few helpers
// the make encoded and decoded the tiles a little easier.
package vector_tile
//go:generate protoc --go_out=. vector_tile.proto
import (
"bytes"
"io/ioutil"
"compress/gzip"
"github.com/golang/protobuf/proto"
)
// Encode protobuf encodes the tile into a byte buffer.
func Encode(tile *Tile) ([]byte, error) {
return proto.Marshal(tile)
}
// EncodeGzipped gzips the data after encoding the tile via protocol buffers.
func EncodeGzipped(tile *Tile) ([]byte, error) {
data, err := Encode(tile)
if err != nil {
return nil, err
}
buf := bytes.NewBuffer(nil)
gzWriter := gzip.NewWriter(buf)
defer gzWriter.Close()
_, err = gzWriter.Write(data)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// Decode has the protobuf library decode the data into a tile.
func Decode(data []byte) (*Tile, error) {
tile := &Tile{}
err := proto.Unmarshal(data, tile)
return tile, err
}
// DecodeGzipped first ungzips the data before having the
// protobuf library decode the data into a tile.
func DecodeGzipped(data []byte) (*Tile, error) {
gzReader, err := gzip.NewReader(bytes.NewBuffer(data))
if err != nil {
return nil, err
}
defer gzReader.Close()
ungzipped, err := ioutil.ReadAll(gzReader)
if err != nil {
return nil, err
}
return Decode(ungzipped)
}