-
Notifications
You must be signed in to change notification settings - Fork 0
/
slip.js
71 lines (63 loc) · 1.78 KB
/
slip.js
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
/*
This module has core functions for SLIP protocol:
https://tools.ietf.org/html/rfc1055
Author: Dmitry Myadzelets
Assumptions:
1. The beginning and the end of the data are unknown.Both encode and decode
functions operate on chunks of data. The upper level should add END
character at the end (and the beginning) of the data.
2. Two bytes escape sequences are always in the same chunk during decoding.
Encode and decode functions do not modify data. For such the `slice` and `add`
functions should be provided.
*/
const END = 192
const ESC = 219
const ESC_END = 220
const ESC_ESC = 221
const buf = {
end: new Uint8Array([END]),
esc: new Uint8Array([ESC]),
escend: new Uint8Array([ESC, ESC_END]),
escesc: new Uint8Array([ESC, ESC_ESC])
}
function encode (chunk, slice, add) {
let start, end
for (start = 0, end = 0; end < chunk.length; end += 1) {
switch (chunk[end]) {
case ESC:
(end > start) && slice(chunk, start, end)
add(buf.escesc)
start = end + 1
break
case END:
(end > start) && slice(chunk, start, end)
add(buf.escend)
start = end + 1
break
}
}
(end > start) && slice(chunk, start, end)
}
function decode (chunk, slice, add, eof) {
let start, end
let esc = false
for (start = 0, end = 0; end < chunk.length; end += 1) {
switch (chunk[end]) {
case ESC_END:
esc && (start = end + 1) && add(buf.end)
break
case ESC_ESC:
esc && (start = end + 1) && add(buf.esc)
break
case END:
(end > start) && slice(chunk, start, end)
start = end + 1
eof()
break
}
esc = chunk[end] === ESC
}
(end > start) && slice(chunk, start, end)
}
module.exports = { encode, decode }
module.exports.END = buf.end