forked from alexdovzhanyn/bert-elixir
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
407 lines (305 loc) · 9.92 KB
/
index.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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
const BERT_START = String.fromCharCode(131)
const SMALL_ATOM = String.fromCharCode(115)
const SMALL_ATOM_UTF8 = String.fromCharCode(119)
const ATOM = String.fromCharCode(100)
const ATOM_UTF8 = String.fromCharCode(118)
const SMALL_INTEGER = String.fromCharCode(97)
const MAP = String.fromCharCode(116)
const INTEGER = String.fromCharCode(98)
const SMALL_BIG = String.fromCharCode(110)
const LARGE_BIG = String.fromCharCode(111)
const FLOAT = String.fromCharCode(99)
const CHARLIST = String.fromCharCode(107)
const STRING = String.fromCharCode(109)
const LIST = String.fromCharCode(108)
const SMALL_TUPLE = String.fromCharCode(104)
const LARGE_TUPLE = String.fromCharCode(105)
const NIL = String.fromCharCode(106)
const ZERO = String.fromCharCode(0)
const ZERO_CHAR = String.fromCharCode(48)
const atom = value => ({ type: 'Atom', value, toString: () => value })
const charlist = value => ({ type: 'Charlist', value, toString: () => value })
const encode = obj => BERT_START + encodeInner(obj)
const encodeCharlist = ({ value }) => CHARLIST + intToBytes(value.length, 2) + value
const encodeString = obj => STRING + intToBytes(obj.length, 4) + obj
const encodeBoolean = obj => encodeInner(atom(obj ? 'true' : 'false'))
const encodeAtom = ({ value }) => ATOM + intToBytes(value.length, 2) + value
const decodeSmallInteger = s => ({ value: s.charCodeAt(0), rest: s.substring(1) })
const decodeInteger = (s, count) => ({ value: bytesToInt(s, count), rest: s.substring(count) })
const encodeAssociativeArray = obj => encodeArray(Object.keys(obj).map(k => tuple(atom(k), obj[k])))
const tuple = (...arr) => {
let res = { type: 'Tuple', length: arr.length, value: arr, toString: () => `{${arr.join(", ")}}`, items: [] }
for (var i = 0; i < arr.length; i++) {
res.items.push(arr[i])
}
return res
}
const encodeInner = obj => {
if (obj === undefined) throw new Error('Cannot encode undefined values.')
switch(typeof(obj)) {
case 'string': return encodeString(obj)
case 'boolean': return encodeBoolean(obj)
case 'atom': return encodeAtom(obj)
case 'number': return encodeNumber(obj)
case 'float': return encodeFloat(obj)
case 'object': return encodeObject(obj)
case 'tuple': return encodeTuple(obj)
case 'array': return encodeArray(obj)
default: return
}
}
const decode = s => {
if (s[0] !== BERT_START) throw ('Not a valid BERT.')
const obj = decodeInner(s.substring(1))
if (obj.rest !== '') throw ('Invalid BERT.')
return obj.value
}
const encodeNumber = obj => {
const isInteger = obj % 1 === 0
// Float
if (!isInteger) return encodeFloat(obj)
// Small int
if (isInteger && obj >= 0 && obj < 256) return SMALL_INTEGER + intToBytes(obj, 1)
// 4 byte int
if (isInteger && obj >= -134217728 && obj <= 134217727) return INTEGER + intToBytes(obj, 4)
obj = bignumToBytes(obj)
if (obj.length < 256) {
return SMALL_BIG + intToBytes(obj.length - 1, 1) + obj
} else {
return LARGE_BIG + intToBytes(obj.length - 1, 4) + obj
}
}
const encodeFloat = obj => {
obj = obj.toExponential(20)
const match = /([^e]+)(e[+-])(\d+)/.exec(obj)
let exponentialPart = match[3].length == 1 ? "0" + match[3] : match[3]
let num = match[1] + match[2] + exponentialPart
return FLOAT + num + ZERO.repeat(32 - num.length)
}
const encodeObject = obj => {
if (obj === null) return encodeInner(atom('null'))
if (obj.type === 'Atom') return encodeAtom(obj)
if (obj.type === 'Tuple') return encodeTuple(obj)
if (obj.type === 'Charlist') return encodeCharlist(obj)
// Check if it's an array...
if (obj.constructor.toString().includes('Array')) return encodeArray(obj)
// Treat the object as a map
return encodeMap(obj)
}
const encodeTuple = obj => {
let s
if (obj.length < 256) {
s = SMALL_TUPLE + intToBytes(obj.length, 1)
} else {
s = LARGE_TUPLE + intToBytes(obj.length, 4)
}
return s + obj.items.reduce((acc, curr) => acc + encodeInner(curr), '')
}
const encodeMap = obj => {
const { map } = obj
const arity = Object.keys(obj).length
return MAP + intToBytes(arity, 4) + Object.keys(obj).map(key => encodeInner(atom(key)) + encodeInner(obj[key])).join('')
}
const encodeArray = obj => {
if (obj.length === 0) return encodeInner(tuple(atom('bert'), atom('nil')))
return LIST + intToBytes(obj.length, 4) + obj.reduce((acc, curr) => acc + encodeInner(curr), '') + NIL
}
const decodeInner = s => {
const type = s[0]
s = s.substring(1)
switch(type) {
case SMALL_ATOM: return decodeAtom(s, 1)
case SMALL_ATOM_UTF8: return decodeAtom(s, 1)
case ATOM: return decodeAtom(s, 2)
case ATOM_UTF8: return decodeAtom(s, 1)
case SMALL_INTEGER: return decodeSmallInteger(s)
case INTEGER: return decodeInteger(s, 4)
case SMALL_BIG: return decodeBig(s, 1)
case LARGE_BIG: return decodeBig(s, 4)
case MAP: return decodeMap(s)
case FLOAT: return decodeFloat(s)
case STRING: return decodeString(s)
case CHARLIST: return decodeCharlist(s)
case LIST: return decodeList(s)
case SMALL_TUPLE: return decodeTuple(s, 1)
case LARGE_TUPLE: return decodeLargeTuple(s, 4)
case NIL: return decodeNil(s)
default: throw(`Unexpected BERT type: ${type.charCodeAt(0)}`)
}
}
const decodeAtom = (s, count) => {
let size = bytesToInt(s, count)
s = s.substring(count)
let value = s.substring(0, size)
return { value: atom(value), rest: s.substring(size) }
}
const decodeBig = (s, count) => {
let size = bytesToInt(s, count)
s = s.substring(count)
return { value: bytesToBignum(s, size), rest: s.substring(size + 1) }
}
const decodeFloat = s => ({ value: parseFloat(s.substring(0, 31)), rest: s.substring(31) })
const decodeString = s => {
let size = bytesToInt(s, 4)
s = s.substring(4)
return { value: s.substring(0, size), rest: s.substring(size) }
}
const decodeCharlist = s => {
let size = bytesToInt(s, 2)
s = s.substring(2)
return { value: charlist(s.substring(0, size)), rest: s.substring(size) }
}
const decodeList = s => {
let size = bytesToInt(s, 4)
let arr = []
s = s.substring(4)
for (let i = 0; i < size; i++) {
let { value, rest } = decodeInner(s)
arr.push(value)
s = rest
}
if (s[0] !== NIL) throw('List does not end with NIL!')
s = s.substring(1)
return { value: arr, rest: s }
}
const decodeMap = s => {
let size = bytesToInt(s, 4)
let obj = {}
s = s.substring(4)
for (let i = 0; i < size; i++) {
let { value: atom, rest: r } = decodeInner(s)
s = r
let { value, rest } = decodeInner(s)
obj[atom] = value
s = rest
}
return { value: obj, rest: s }
}
const decodeTuple = (s, count) => {
let size = bytesToInt(s, count)
let arr = []
s = s.substring(count)
for (let i = 0; i < size; i++) {
let { value, rest } = decodeInner(s)
arr.push(value)
s = rest
}
if (size >= 2) {
let head = arr[0]
if (typeof head === 'object' && head.type === 'Atom' && head.value === 'bert') {
let kind = arr[1]
if (typeof kind !== 'object' || kind.type !== 'Atom') throw('Invalid {bert, _} tuple!')
switch(kind.value) {
case 'true': return { value: true, rest: s }
case 'false': return { value: false, rest: s }
case 'nil': return { value: null, rest: s }
case 'time':
case 'dict':
case 'regex': throw(`TODO: decode ${kind.value}`)
default: throw(`Invalid {bert, ${kind.value.toString()}} tuple!`)
}
}
}
return { value: tuple(...arr), rest: s }
}
const decodeNil = s => ({ value: [], rest: s })
// Encode an integer to a big-endian byte-string of length Length.
// Throw an exception if the integer is too large
// to fit into the specified number of bytes.
const intToBytes = (int, length) => {
let isNegative = int < 0
let s = ''
if (isNegative) {
int = -int - 1
}
let originalInt = int
for (let i = 0; i < length; i++) {
rem = isNegative ? 255 - (int % 256) : int % 256
s = String.fromCharCode(rem) + s
int = Math.floor(int / 256)
}
if (int > 0) throw(`Argument out of range: ${originalInt}`)
return s
}
// Read a big-endian encoded integer from the first Length bytes
// of the supplied string.
const bytesToInt = (s, length) => {
let isNegative = s.charCodeAt(0) > 128
let num = 0
for (let i = 0; i < length; i++) {
let n = isNegative ? 255 - s.charCodeAt(i) : s.charCodeAt(i)
num = num === 0 ? n : num * 256 + n
}
if (isNegative) num = -num - 1
return num
}
// Encode an integer into an Erlang bignum,
// which is a byte of 1 or 0 representing
// whether the number is negative or positive,
// followed by little-endian bytes.
const bignumToBytes = int => {
let s = ''
let isNegative = int < 0
if (isNegative) {
int *= -1
s += String.fromCharCode(1)
} else {
s += String.fromCharCode(0)
}
while (int !== 0) {
let rem = int % 256
s += String.fromCharCode(rem)
int = Math.floor(int / 256)
}
return s
}
// Encode a list of bytes into an Erlang bignum.
const bytesToBignum = (s, count) => {
let num = 0
s = s.substring(1)
for (i = count - 1; i >= 0; i--) {
let n = s.charCodeAt(i)
num = num === 0 ? n : num * 256 + n
}
if (s.charCodeAt(0) === 1) return num * -1
return num
}
// Convert an array of bytes into a string.
const bytesToString = arr => arr.reduce((acc, curr) => acc + String.fromCharCode(curr), '')
// Pretty Print a byte-string in Erlang binary form.
const ppBytes = bin => bin.split('').map(c => c.charCodeAt(0)).join(', ')
const ppTerm = obj => obj.toString()
// Convert string of byes to an array
const binaryToList = str => {
let ret = []
for (let i = 0; i < str.length; i++) ret.push(str.charCodeAt(i))
return ret
}
module.exports = {
atom,
tuple,
charlist,
encode,
encodeString,
encodeBoolean,
encodeAtom,
decodeSmallInteger,
decodeInteger,
encodeAssociativeArray,
decode,
encodeNumber,
encodeFloat,
encodeObject,
encodeTuple,
encodeArray,
decodeAtom,
decodeBig,
decodeFloat,
decodeString,
decodeList,
decodeTuple,
decodeNil,
binaryToList,
ppBytes,
ppTerm
}