-
Notifications
You must be signed in to change notification settings - Fork 0
/
encode.go
95 lines (80 loc) · 1.99 KB
/
encode.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
84
85
86
87
88
89
90
91
92
93
94
95
package go_inthex
import (
"encoding/binary"
"strings"
)
func Encode(stream *Stream) (hex []byte, err error) {
var entries []string
emitRecord := func(r Record) {
entries = append(entries, r.String())
}
emitAddress := func(addr uint32) error {
if addr <= 0x000FFFF0 && (addr&(^RecordExtendedSegmentAddressMask)) == 0 {
emitRecord(Record{
Code: RecordExtendedSegmentAddress,
Address: uint16(addr / 16),
Data: nil,
})
return nil
} else {
emitRecord(Record{
Code: RecordExtendedLinearAddress,
Address: uint16(addr >> 16),
Data: nil,
})
return nil
}
}
const recordSize = 16
const sectionSize = 1 << 16
for _, r := range stream.Regions {
if err = emitAddress(r.Address); err != nil {
return nil, err
}
// Add extra entries as needed
for _, e := range r.Extra {
entries = append(entries, e)
}
endAddress := r.Address + uint32(len(r.Data))
for addr := r.Address; addr < endAddress; addr += sectionSize {
if addr != r.Address {
if err = emitAddress(addr); err != nil {
return nil, err
}
}
for subAddr := addr; subAddr < (addr+sectionSize) && subAddr < endAddress; subAddr += recordSize {
writeSize := min(recordSize, endAddress-subAddr+1)
dataOffset := subAddr - r.Address
emitRecord(Record{
Code: RecordData,
Address: uint16(subAddr & 0xFFFF),
Data: r.Data[dataOffset : dataOffset+writeSize],
})
}
}
}
if stream.StartLinearAddress != 0 {
var buf [4]byte
binary.BigEndian.PutUint32(buf[:], stream.StartLinearAddress)
emitRecord(Record{
Code: RecordStartLinearAddress,
Address: 0,
Data: buf[:],
})
}
if stream.StartSegmentAddress != 0 {
var buf [4]byte
binary.BigEndian.PutUint32(buf[:], stream.StartSegmentAddress)
emitRecord(Record{
Code: RecordStartSegmentAddress,
Address: 0,
Data: buf[:],
})
}
emitRecord(Record{
Code: RecordEOF,
Address: 0,
Data: nil,
})
return []byte(strings.Join(entries, "\r\n")), nil
}