-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheader.go
76 lines (57 loc) · 1.35 KB
/
header.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
package psx
import (
"bytes"
"encoding/binary"
"errors"
"io"
"github.com/bodgit/psx/internal/xor"
)
var (
headerSignature = [2]byte{'M', 'C'} //nolint:gochecknoglobals
errBadHeaderChecksum = errors.New("bad header frame checksum")
errBadHeaderSignature = errors.New("bad header frame signature")
)
type headerFrame struct {
Signature [2]byte
_ [125]byte
Checksum [1]byte
}
func (hf *headerFrame) unmarshalBinary(r io.Reader) error {
h := xor.New()
if err := binary.Read(checksumReader(r, h, binary.Size(hf)), binary.LittleEndian, hf); err != nil {
return err
}
if !bytes.Equal(hf.Signature[:], headerSignature[:]) {
return errBadHeaderSignature
}
if !bytes.Equal(hf.Checksum[:], h.Sum(nil)) {
return errBadHeaderChecksum
}
return nil
}
func (hf *headerFrame) MarshalBinary() ([]byte, error) {
buf := new(bytes.Buffer)
buf.Grow(binary.Size(hf))
_ = binary.Write(buf, binary.LittleEndian, hf)
return buf.Bytes(), nil
}
func (hf *headerFrame) generateChecksum() ([]byte, error) {
b, err := hf.MarshalBinary()
if err != nil {
return nil, err
}
return checksum(b[:frameSize-1]), nil
}
func (hf *headerFrame) checksum() error {
xor, err := hf.generateChecksum()
if err != nil {
return err
}
copy(hf.Checksum[:], xor)
return nil
}
func newHeaderFrame() headerFrame {
return headerFrame{
Signature: headerSignature,
}
}