-
Notifications
You must be signed in to change notification settings - Fork 0
/
cobs.go
56 lines (49 loc) · 969 Bytes
/
cobs.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
package core
func CobsEncode(buf []byte) []byte {
// Size our destination buffer -- we need an extra byte for each length of up to 255
lengths := len(buf) / 255
if len(buf)%255 != 0 {
lengths++
}
dest := make([]byte, 0, len(buf)+lengths)
dest = append(dest, 0)
codePtr := 0
var code byte = 0x01
finish := func(inclLast bool) {
dest[codePtr] = code
codePtr = len(dest)
if inclLast {
dest = append(dest, 0x00)
}
code = 0x01
}
for i := 0; i < len(buf); i++ {
if buf[i] == 0 {
finish(true)
} else {
dest = append(dest, buf[i])
code += 1
if code == 0xff {
finish(true)
}
}
}
finish(false)
return dest
}
func CobsDecode(buf []byte) []byte {
dest := make([]byte, 0, len(buf))
for i := 0; i < len(buf); {
code := buf[i]
i++
var j byte
for j = 1; j < code && i < len(buf); j++ {
dest = append(dest, buf[i])
i++
}
if code < 0xff && i < len(buf) {
dest = append(dest, 0x00)
}
}
return dest
}