-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockmap.go
74 lines (56 loc) · 1.46 KB
/
blockmap.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
package gc
import (
"bytes"
"encoding/binary"
"errors"
"github.com/bodgit/gc/internal/hash"
)
var errBadBlockMapChecksum = errors.New("bad block map checksum")
type blockMap struct {
Checksum [checksums][hash.Size]byte
UpdateCounter uint16
FreeBlocks uint16
LastAllocatedBlock uint16
Blocks [0x0ffb]uint16
}
func (m *blockMap) MarshalBinary() ([]byte, error) {
buf := new(bytes.Buffer)
buf.Grow(binary.Size(m))
_ = binary.Write(buf, binary.BigEndian, m)
return buf.Bytes(), nil
}
func (m *blockMap) generateChecksums() ([]byte, []byte, error) {
b, err := m.MarshalBinary()
if err != nil {
return nil, nil, err
}
normal, inverted := checksum(b[checksums*hash.Size:])
return normal, inverted, nil
}
func (m *blockMap) checksum() error {
normal, inverted, err := m.generateChecksums()
if err != nil {
return err
}
copy(m.Checksum[checksumNormal][:], normal)
copy(m.Checksum[checksumInverted][:], inverted)
return nil
}
func (m *blockMap) isValid() error {
normal, inverted, err := m.generateChecksums()
if err != nil {
return err
}
c1, c2 := m.Checksum[checksumNormal][:], m.Checksum[checksumInverted][:]
if !bytes.Equal(c1, normal) || !bytes.Equal(c2, inverted) {
return errBadBlockMapChecksum
}
return nil
}
func newBlockMap(updateCounter, freeBlocks uint16) blockMap {
return blockMap{
UpdateCounter: updateCounter,
FreeBlocks: freeBlocks,
LastAllocatedBlock: reservedBlocks - 1,
}
}