-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparseLengthPrefixed4.js
More file actions
52 lines (48 loc) · 1.53 KB
/
parseLengthPrefixed4.js
File metadata and controls
52 lines (48 loc) · 1.53 KB
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
import { Buffer } from 'buffer';
const digits = [...'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'].map(c => c.charCodeAt(0))
export const parseLengthPrefixed4 = (str1, {
open = '['.charCodeAt(0),
close = ']'.charCodeAt(0),
} = {}) => {
const parents = []
let parent = {subvalues: []}, buffer = [], affix = []
const str = Buffer.from(str1, 'utf8')
let i = 0
for (; i < str.length; ++i) {
const c = str[i]
if (digits.includes(c)) buffer.push(c)
else if (c === open) {
if (buffer.length > 0) {
const length = Number.parseInt(String.fromCharCode(...buffer), 36)
buffer = []
++i
affix = str.slice(i, i + length)
i += length - 1
}
const value = {subvalues: []}
parent.subvalues.push({prefix: affix, value})
parents.push(parent)
parent = value
} else if (c === close) {
if (buffer.length > 0) {
const length = Number.parseInt(String.fromCharCode(...buffer), 36)
buffer = []
++i
affix = str.slice(i, i + length)
i += length - 1
}
if (parents.length === 0) {
if (i !== str.length - 1) throw Error('Unexpected end!')
else break
}
parent.suffix = affix
if (parents.length < 1) throw Error('Unexpected close!')
parent = parents.pop()
} else throw Error(`unexpected byte ${c}`)
}
if (buffer.length > 0 || parents.length > 0) throw Error('Unexpected end!')
parent.suffix = affix
parent.open = open
parent.close = close
return parent
}