-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode.go
83 lines (73 loc) · 1.96 KB
/
decode.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
83
package go_inthex
import (
"encoding/binary"
"errors"
"strings"
)
func Decode(data []byte) (stream *Stream, err error) {
stream = &Stream{}
var currentRegion Region
var baseAddress uint32
emitRegion := func() {
if len(currentRegion.Data) > 0 || len(currentRegion.Extra) > 0 {
stream.Regions = append(stream.Regions, currentRegion)
}
currentRegion = Region{}
}
for _, d := range strings.Split(string(data), "\n") {
if len(d) == 0 {
continue
}
if d[0] != ':' {
extra := strings.Trim(d, "\r\n")
if len(extra) > 0 {
currentRegion.Extra = append(currentRegion.Extra, extra)
}
continue
}
r, err := RecordFromString(d)
if err != nil {
return nil, err
}
switch r.Code {
case RecordData:
address := baseAddress + uint32(r.Address)
if !currentRegion.IsContiguousAddress(address) {
emitRegion()
baseAddress = baseAddress + uint32(r.Address)
currentRegion.Address = baseAddress
}
currentRegion.Append(r.Data)
case RecordEOF:
emitRegion()
return stream, nil
case RecordExtendedSegmentAddress:
if len(r.Data) != 2 {
return nil, errors.New("invalid ExtendedSegmentAddress length")
}
baseAddress = uint32(binary.BigEndian.Uint16(r.Data)) * 16
if len(currentRegion.Data) == 0 {
currentRegion.Address = baseAddress
}
case RecordStartSegmentAddress:
if len(r.Data) != 4 {
return nil, errors.New("invalid StartSegmentAddress length")
}
stream.StartLinearAddress = binary.BigEndian.Uint32(r.Data)
case RecordExtendedLinearAddress:
if len(r.Data) != 2 {
return nil, errors.New("invalid ExtendedLinearAddress length")
}
baseAddress = uint32(binary.BigEndian.Uint16(r.Data)) << 16
if len(currentRegion.Data) == 0 {
currentRegion.Address = baseAddress
}
case RecordStartLinearAddress:
if len(r.Data) != 4 {
return nil, errors.New("invalid RecordStartLinearAddress length")
}
stream.StartLinearAddress = binary.BigEndian.Uint32(r.Data)
}
}
return
}