-
Notifications
You must be signed in to change notification settings - Fork 3
/
slip.go
51 lines (44 loc) · 805 Bytes
/
slip.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
package main
import (
"fmt"
)
const slipEnd = 0xC0
const slipEsc = 0xDB
const slipEscEnd = 0xDC
const slipEscEsc = 0xDD
func decodeSLIP(data []byte, handle func(packet []byte)) (rest []byte, err error) {
var packet []byte
escaped := false
var index, lastEndIndex int
var b byte
for index, b = range data {
switch b {
case slipEnd:
lastEndIndex = index + 1
if len(packet) > 0 {
handle(packet)
packet = nil
}
continue
case slipEsc:
escaped = true
continue
case slipEscEnd:
if escaped {
b = slipEnd
escaped = false
}
case slipEscEsc:
if escaped {
b = slipEsc
escaped = false
}
default:
if escaped {
return data, fmt.Errorf("SLIP protocol error")
}
}
packet = append(packet, b)
}
return data[lastEndIndex:], nil
}