-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.go
More file actions
62 lines (56 loc) · 1.09 KB
/
db.go
File metadata and controls
62 lines (56 loc) · 1.09 KB
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
package main
import (
"bytes"
"compress/zlib"
"io"
"os"
"github.com/vmihailenco/msgpack"
)
func encodeTicks(object interface{}, bCompress bool) ([]byte, error) {
b, err := msgpack.Marshal(object)
if err != nil {
return nil, err
}
if bCompress {
var zb bytes.Buffer
zw := zlib.NewWriter(&zb)
zw.Write(b)
zw.Close()
return zb.Bytes(), nil
}
return b, nil
}
func decodeTicks(b io.Reader, object interface{}, bCompress bool) error {
var out bytes.Buffer
if bCompress {
reader, err := zlib.NewReader(b)
if err != nil {
return err
}
io.Copy(&out, reader)
reader.Close()
} else {
io.Copy(&out, b)
}
return msgpack.Unmarshal(out.Bytes(), object)
}
func writeMsgpackFile(filePath string, object interface{}) error {
file, err := os.Create(filePath)
if err == nil {
b, err := encodeTicks(object, true)
if err == nil {
file.Write(b)
}
file.Close()
}
return err
}
func readMsgpackFile(filePath string, object interface{}) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
err = decodeTicks(file, object, true)
file.Close()
return err
}