-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary.go
More file actions
55 lines (42 loc) · 963 Bytes
/
binary.go
File metadata and controls
55 lines (42 loc) · 963 Bytes
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
// Copyright (c) 2021 Andrej Giesbrecht
package store
import (
"bytes"
"encoding/gob"
"os"
)
// ReadBinary loads the file into v and returns an error, if any.
func ReadBinary(file string, v interface{}) error {
lock.Lock()
defer lock.Unlock()
var buf bytes.Buffer
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
_, err = buf.ReadFrom(f)
if err != nil {
return err
}
dec := gob.NewDecoder(&buf)
return dec.Decode(v)
}
// WriteBinary saves a representation of v to the file at path.
// It returns the number of bytes written and an error, if any.
func WriteBinary(file string, v interface{}) (int64, error) {
lock.Lock()
defer lock.Unlock()
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(v)
if err != nil {
return 0, err
}
f, err := os.Create(file)
if err != nil {
return 0, err
}
defer f.Close()
return buf.WriteTo(f)
}