-
Notifications
You must be signed in to change notification settings - Fork 10
/
data_encoder.go
99 lines (74 loc) · 1.74 KB
/
data_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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package pdf417
type Encoder interface {
GetName() string
CanEncode(char string) bool
GetSwitchCode(data string) int
Encode(data string, addSwitchCode bool) []int
}
type DataEncoder struct {
Encoders []Encoder
DefaultEncoder Encoder
}
type Chain struct {
Data string
Encoder Encoder
}
func CreateDataEncoder() DataEncoder {
numberEncoder := CreateNumberEncoder()
textEncoder := CreateTextEncoder()
encoder := DataEncoder{
[]Encoder{numberEncoder, textEncoder},
textEncoder,
}
return encoder
}
func (dataEncoder DataEncoder) Encode(data string) []int {
chains := dataEncoder.SplitToChains(data)
if len(chains) == 0 {
panic("hmmm")
}
firstEncoder := chains[0].Encoder
addSwitchCode := firstEncoder.GetName() != dataEncoder.DefaultEncoder.GetName()
cws := []int{}
for _, chainWithEncoder := range chains {
encoded := chainWithEncoder.Encoder.Encode(
chainWithEncoder.Data,
addSwitchCode,
)
cws = append(cws, encoded...)
addSwitchCode = true
}
return cws
}
func (dataEncoder DataEncoder) SplitToChains(data string) []Chain {
chains := []Chain{}
chainData := ""
encoder := dataEncoder.DefaultEncoder
for i := 0; i < len(data); i++ {
char := string(data[i])
newEncoder := getEncoder(
dataEncoder.Encoders,
char,
)
if newEncoder != encoder {
if len(chainData) > 0 {
chains = append(chains, Chain{chainData, encoder})
chainData = ""
}
encoder = newEncoder
}
chainData = chainData + char
}
if len(chainData) > 0 {
chains = append(chains, Chain{chainData, encoder})
}
return chains
}
func getEncoder(encoders []Encoder, char string) Encoder {
for _, encoder := range encoders {
if encoder.CanEncode(char) {
return encoder
}
}
panic("Cannot encode character " + char)
}