-
Notifications
You must be signed in to change notification settings - Fork 72
/
file_serializer.go
47 lines (40 loc) · 1.03 KB
/
file_serializer.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
package serial
import (
"encoding/json"
"io"
)
//go:generate counterfeiter -o ../fakes/overwriteable_file.go --fake-name OverwriteableFile . OverwriteableFile
type OverwriteableFile interface {
io.Reader
io.Writer
io.Seeker
Truncate(size int64) error
}
//go:generate counterfeiter -o ../fakes/serializer.go --fake-name Serializer . Serializer
type Serializer interface {
DecodeAll(file io.ReadSeeker, outData interface{}) error
EncodeAndOverwrite(file OverwriteableFile, outData interface{}) error
}
type Serial struct{}
func (s *Serial) DecodeAll(file io.ReadSeeker, outData interface{}) error {
_, err := file.Seek(0, io.SeekStart)
if err != nil {
return err
}
err = json.NewDecoder(file).Decode(outData)
if err != nil && err != io.EOF {
return err
}
return nil
}
func (s *Serial) EncodeAndOverwrite(file OverwriteableFile, outData interface{}) error {
_, err := file.Seek(0, io.SeekStart)
if err != nil {
return err
}
err = file.Truncate(0)
if err != nil {
return err
}
return json.NewEncoder(file).Encode(outData)
}