-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathencoder.go
115 lines (98 loc) · 2.49 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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package hdlc
import (
"bufio"
"encoding/binary"
"io"
"github.com/sigurn/crc16"
)
// An Encoder writes HDLC frames to an output stream.
type Encoder struct {
w io.Writer
bufW *bufio.Writer
accm asyncControlCharacterMap
}
// NewEncoder returns a new encoder that writes to w.
func NewEncoder(w io.Writer) *Encoder {
return &Encoder{
w: w,
bufW: bufio.NewWriter(w),
}
}
// WriteFrame writes the frame f on the output stream, encoding it's content.
func (e *Encoder) WriteFrame(f *Frame) (int, error) {
var err error
var n, nn int
if err = e.bufW.WriteByte(flagSym); err != nil {
return 0, err
}
n++
if f.HasAddressCtrlPrefix {
if nn, err = e.writeEscapedData(addressCtrlSeq, e.bufW); err != nil {
return n + nn, err
}
n += nn
}
if nn, err = e.writeEscapedData(f.Payload, e.bufW); err != nil {
return n + nn, err
}
n += nn
if nn, err = e.writeEscapedData(f.FCS, e.bufW); err != nil {
return n + nn, err
}
n += nn
if err = e.bufW.WriteByte(flagSym); err != nil {
return n + 1, err
}
n++
if err = e.bufW.Flush(); err != nil {
return n, err
}
return n, nil
}
// SetACCM sets the encoder's Async-Control-Character-Map (ACCM). The default
// ACCM value is 0, meaning that the encoder does not escape any control
// characters.
//
// Note that this implementation does not negotiate the ACCM with the peer.
func (e *Encoder) SetACCM(chars ControlChar) *Encoder {
e.accm = asyncControlCharacterMap(chars)
return e
}
func (e *Encoder) writeEscapedData(p []byte, out *bufio.Writer) (int, error) {
var err error
written := 0
for i, b := range p {
if e.accm.contains(b) || ((b)&0x7f) == 0x7d || ((b)&0x7f) == 0x7e {
if err = out.WriteByte(escapeSym); err != nil {
return written, err
}
if err = out.WriteByte(b ^ 0x20); err != nil {
return written, err
}
} else {
if err = out.WriteByte(b); err != nil {
return written, err
}
}
written = i
}
return written + 1, nil
}
// Encapsulate takes a payload p and some configuration and creates a frame that
// can be written with an Encoder.
func Encapsulate(p []byte, hasAddressCtrlPrefix bool) *Frame {
crc := crc16.Init(crcTable)
if hasAddressCtrlPrefix {
crc = crc16.Update(crc, addressCtrlSeq, crcTable)
}
crc = crc16.Update(crc, p, crcTable)
crc = crc16.Complete(crc, crcTable)
crc ^= 0xffff
crcBytes := []byte{0, 0}
binary.LittleEndian.PutUint16(crcBytes, crc)
return &Frame{
Payload: p,
FCS: crcBytes,
HasAddressCtrlPrefix: hasAddressCtrlPrefix,
}
}