forked from fiam/max7456tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoder.go
73 lines (67 loc) · 1.27 KB
/
encoder.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
package main
import (
"fmt"
"io"
"strconv"
)
const (
mcmCharNum = 256
mcmExtendedCharNum = 512
)
type Encoder struct {
Chars map[int]*MCMChar
Fill bool
}
func (e *Encoder) isExtended() bool {
for k := range e.Chars {
if k >= mcmCharNum {
return true
}
}
return false
}
func (e *Encoder) charNum() int {
if e.isExtended() {
return mcmExtendedCharNum
}
return mcmCharNum
}
func (e *Encoder) Encode(w io.Writer) error {
charNum := e.charNum()
for k := range e.Chars {
if k >= charNum {
return fmt.Errorf("invalid character number %d, max is %d", k, mcmCharNum-1)
}
}
if _, err := io.WriteString(w, max7456Hdr); err != nil {
return err
}
for ii := 0; ii < charNum; ii++ {
c := e.Chars[ii]
if c == nil {
if !e.Fill {
return fmt.Errorf("missing character %d", ii)
}
c = blankCharacter
}
data := c.Data()
if len(data) != charBytes {
return fmt.Errorf("invalid character length %d (!= %d)", len(data), charBytes)
}
for jj, b := range data {
if ii > 0 || jj > 0 {
if _, err := io.WriteString(w, "\r\n"); err != nil {
return err
}
}
s := strconv.FormatUint(uint64(b), 2)
for len(s) < 8 {
s = "0" + s
}
if _, err := io.WriteString(w, s); err != nil {
return err
}
}
}
return nil
}