-
Notifications
You must be signed in to change notification settings - Fork 3
/
letter-file.go
82 lines (65 loc) · 1.73 KB
/
letter-file.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package jess
import (
"errors"
"github.com/safing/structures/container"
"github.com/safing/structures/dsd"
)
/*
### File Format Version 1
- File Format Version: varint
- Header: Letter without Data as byte block
- Data: byte block
*/
// ErrIncompatibleFileFormatVersion is returned when an incompatible wire format is encountered.
var ErrIncompatibleFileFormatVersion = errors.New("incompatible file format version")
// ToFileFormat serializes the letter for storing it as a file.
func (letter *Letter) ToFileFormat() (*container.Container, error) {
c := container.New()
// File Format Version: varint
c.AppendNumber(1)
// split header and data
letterData := letter.Data
letter.Data = nil
// Header: Letter without Data as byte block
headerData, err := dsd.DumpIndent(letter, dsd.JSON, "\t")
if err != nil {
return nil, err
}
// add newline for better raw viewability
headerData = append(headerData, byte('\n'))
// add header
c.AppendAsBlock(headerData)
// Data: byte block
c.AppendAsBlock(letterData)
// put back together
letter.Data = letterData
return c, nil
}
// LetterFromFileFormat parses a letter stored as a file.
func LetterFromFileFormat(c *container.Container) (*Letter, error) {
letter := &Letter{}
// File Format Version: varint
fileFormatVersion, err := c.GetNextN8()
if err != nil {
return nil, err
}
if fileFormatVersion != 1 {
return nil, ErrIncompatibleFileFormatVersion
}
// Header: Letter without Data as byte block
data, err := c.GetNextBlock()
if err != nil {
return nil, err
}
_, err = dsd.Load(data, letter)
if err != nil {
return nil, err
}
// Data: byte block
letterData, err := c.GetNextBlock()
if err != nil {
return nil, err
}
letter.Data = letterData
return letter, nil
}