forked from jcalfee/fcbuffer
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathtypes.js
606 lines (542 loc) · 17 KB
/
types.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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
const BN = require('bn.js')
const {Long} = require('bytebuffer')
const assert = require('assert')
const types = {
bytes: () => [bytebuf],
string: () => [string],
vector: (type, sorted = true) => [vector, {type, sorted}],
optional: type => [optional, {type}],
time: () => [time],
map: (annotation) => [map, {annotation}],
static_variant: types => [static_variant, {types}],
fixed_string16: () => [string, {maxLen: 16}],
fixed_string32: () => [string, {maxLen: 32}],
fixed_bytes16: () => [bytebuf, {len: 16}],
fixed_bytes20: () => [bytebuf, {len: 20}],
fixed_bytes28: () => [bytebuf, {len: 28}],
fixed_bytes32: () => [bytebuf, {len: 32}],
fixed_bytes33: () => [bytebuf, {len: 33}],
fixed_bytes64: () => [bytebuf, {len: 64}],
fixed_bytes65: () => [bytebuf, {len: 65}],
uint8: () => [intbuf, {bits: 8}],
uint16: () => [intbuf, {bits: 16}],
uint32: () => [intbuf, {bits: 32}],
uint64: () => [intbuf, {bits: 64}],
uint128: () => [bnbuf, {bits: 128}],
uint224: () => [bnbuf, {bits: 224}],
uint256: () => [bnbuf, {bits: 256}],
uint512: () => [bnbuf, {bits: 512}],
varuint32: () => [intbuf, {bits: 32, variable: true}],
int8: () => [intbuf, {signed: true, bits: 8}],
int16: () => [intbuf, {signed: true, bits: 16}],
int32: () => [intbuf, {signed: true, bits: 32}],
int64: () => [intbuf, {signed: true, bits: 64}],
int128: () => [bnbuf, {signed: true, bits: 128}],
int224: () => [bnbuf, {signed: true, bits: 224}],
int256: () => [bnbuf, {signed: true, bits: 256}],
int512: () => [bnbuf, {signed: true, bits: 512}],
varint32: () => [intbuf, {signed: true, bits: 32, variable: true}],
float32: () => [float, {bits: 32}],
float64: () => [float, {bits: 64}]
}
/*
@arg {SerializerConfig} config
@return {object} {[typeName]: function(args)}
*/
module.exports = config => {
config = Object.assign({defaults: false, debug: false, customTypes: {}}, config)
const allTypes = Object.assign({}, types, config.customTypes)
const createTypeReducer = baseTypes => (customTypes, name) => {
customTypes[name] = (...args) => {
const type = createType(name, config, args, baseTypes, allTypes, customTypes)
return type
}
return customTypes
}
const baseTypes = Object.keys(types)
.reduce(createTypeReducer(), {})
const customTypes = Object.keys(config.customTypes || {})
.reduce(createTypeReducer(baseTypes), {})
return Object.assign({}, baseTypes, customTypes, {config})
}
/**
@args {string} typeName - matches types[]
@args {string} config - Additional arguments for types
*/
function createType (typeName, config, args, baseTypes, allTypes, customTypes) {
const Type = baseTypes ? allTypes[typeName] : types[typeName]
const [fn, v = {}] = Type(...args)
const validation = Object.assign(v, config)
validation.typeName = typeName
const type = fn(validation, baseTypes, customTypes)
type.typeName = typeName
return type
}
const map = validation => {
const {annotation: [type1, type2]} = validation
if (!isSerializer(type1)) { throw new TypeError(`map<type1, > unknown`) }
if (!isSerializer(type2)) { throw new TypeError(`map<, type2> unknown`) }
return {
fromByteBuffer (b) {
const size = b.readVarint32()
const result = {}
for (let i = 0; i < size; i++) {
result[type1.fromByteBuffer(b)] = type2.fromByteBuffer(b)
}
if (validation.debug) {
console.log('0x' + size.toString(16), '(map.fromByteBuffer length)', result)
}
return result
},
appendByteBuffer (b, value) {
validate(value, validation)
const keys = Object.keys(value)
b.writeVarint32(keys.length)
if (validation.debug) {
console.log('0x' + keys.length.toString(16), '(map.appendByteBuffer length)', keys)
}
// if(sorted === true) {
// value = sortKeys(type1, Object.assign({}, value))
// }
for (const o of keys) {
const value2 = value[o]
type1.appendByteBuffer(b, o)
type2.appendByteBuffer(b, value2)
}
},
fromObject (value) {
validate(value, validation)
const result = {}
// if(sorted === true) {
// value = sortKeys(type1, Object.assign({}, value))
// }
for (const o in value) {
result[type1.fromObject(o)] = type2.fromObject(value[o])
}
return result
},
toObject (value) {
if (validation.defaults && value == null) {
return {[type1.toObject(null)]: type2.toObject(null)}
}
validate(value, validation)
const result = {}
// if(sorted === true) {
// value = sortKey(type1, Object.assign({}, value))
// }
for (const o in value) {
result[type1.toObject(o)] = type2.toObject(value[o])
}
return result
}
}
}
const static_variant = validation => {
const {types} = validation
return {
fromByteBuffer (b) {
const typePosition = b.readVarint32()
const type = types[typePosition]
if (validation.debug) {
console.error(`static_variant id ${typePosition} (0x${typePosition.toString(16)})`)
}
assert(type, `static_variant invalid type position ${typePosition}`)
return [typePosition, type.fromByteBuffer(b)]
},
appendByteBuffer(b, object) {
assert(Array.isArray(object) && object.length === 2, 'Required tuple')
const typePosition = object[0]
const type = types[typePosition]
assert(type, `type ${typePosition}`)
b.writeVarint32(typePosition)
type.appendByteBuffer(b, object[1])
},
fromObject(object) {
assert(Array.isArray(object) && object.length === 2, 'Required tuple')
const typePosition = object[0]
const type = types[typePosition]
assert(type, `type ${typePosition}`)
return [
typePosition,
type.fromObject(object[1])
]
},
toObject(object) {
if (validation.defaults && object == null) {
return [0, types[0].toObject(null, debug)]
}
assert(Array.isArray(object) && object.length === 2, 'Required tuple')
const typePosition = object[0]
const type = types[typePosition]
assert(type, `type ${typePosition}`)
return [
typePosition,
type.toObject(object[1])
]
}
}
}
const vector = validation => {
const {type, sorted} = validation
if (!isSerializer(type)) {
throw new TypeError('vector type should be a serializer')
}
return {
fromByteBuffer (b) {
const size = b.readVarint32()
if (validation.debug) {
console.log('fromByteBuffer vector length', size, '(0x' + size.toString(16) + ')')
}
const result = []
for (let i = 0; i < size; i++) {
result.push(type.fromByteBuffer(b))
}
return result
},
appendByteBuffer (b, value) {
if(value == null) {
value = []
}
validate(value, validation)
b.writeVarint32(value.length)
if(sorted === true) {
value = sort(type, Object.assign([], value))
}
if (validation.debug) {
console.log('0x' + value.length.toString(16), '(vector.appendByteBuffer length)', value)
}
for (const o of value) {
type.appendByteBuffer(b, o)
}
},
fromObject (value) {
if(value == null) {
value = []
}
validate(value, validation)
let result = []
for (const o of value) {
result.push(type.fromObject(o))
}
if(sorted === true) {
result = sort(type, Object.assign([], result))
}
return result
},
toObject (value) {
if (validation.defaults && value == null) {
return [type.toObject(value)]
}
if(value == null) {
value = []
}
validate(value, validation)
if(sorted === true) {
value = sort(type, Object.assign([], value))
}
const result = []
for (const o of value) {
result.push(type.toObject(o))
}
return result
}
}
}
const optional = validation => {
const {type} = validation
if (!isSerializer(type)) { throw new TypeError('optional parameter should be a serializer') }
return {
fromByteBuffer (b) {
if (!(b.readUint8() === 1)) {
return null
}
return type.fromByteBuffer(b)
},
appendByteBuffer (b, value) {
if (value != null) {
b.writeUint8(1)
type.appendByteBuffer(b, value)
} else {
b.writeUint8(0)
}
},
fromObject (value) {
if (value == null) {
return null
}
return type.fromObject(value)
},
toObject (value) {
// toObject is only null save if defaults is true
let resultValue
if (value == null && !validation.defaults) {
resultValue = null
} else {
resultValue = type.toObject(value)
}
return resultValue
}
}
}
const intbufType = ({signed = false, bits, variable}) =>
variable ? `Varint${bits}${signed ? 'ZigZag' : ''}` :
`${signed ? 'Int' : 'Uint'}${bits}`
const intbuf = (validation) => ({
fromByteBuffer (b) {
const value = b[`read${intbufType(validation)}`]()
return Long.isLong(value) ? value.toString() : value
},
appendByteBuffer (b, value) {
// validateInt(value, validation)
// value = typeof value === 'string' ? Long.fromString(value) : value
b[`write${intbufType(validation)}`](value)
},
fromObject (value) {
validateInt(value, validation)
// if(validation.bits > 53 && typeof value === 'number')
// value = String(value)
return value
},
toObject (value) {
if (validation.defaults && value == null) {
return validation.bits > 53 ? '0' : 0
}
validateInt(value, validation)
// if(validation.bits > 53 && typeof value === 'number')
// value = String(value)
return Long.isLong(value) ? value.toString() : value
}
})
/** Big Numbers (> 64 bits) */
const bnbuf = (validation) => {
const {signed = false, bits} = validation
const size = bits / 8
return {
fromByteBuffer (b) {
const bcopy = b.copy(b.offset, b.offset + size)
b.skip(size)
let bn = new BN(bcopy.toHex(), 'hex')
let buf = bn.toArrayLike(Buffer, 'le', size) // convert to little endian
bn = new BN(buf.toString('hex'), 'hex')
if(signed) {
bn = bn.fromTwos(bits)
}
const value = bn.toString()
validateInt(value, validation)
return bits > 53 ? value : bn.toNumber()
},
appendByteBuffer (b, value) {
validateInt(value, validation)
let bn = new BN(value)
if(signed) {
bn = bn.toTwos(bits)
}
const buf = bn.toArrayLike(Buffer, 'le', size)
b.append(buf.toString('binary'), 'binary')
},
fromObject (value) {
validateInt(value, validation)
return value
},
toObject (value) {
if (validation.defaults && value == null) {
return validation.bits > 53 ? '0' : 0
}
validateInt(value, validation)
return value
}
}
}
const floatPoint = require('ieee-float')
const float = (validation) => {
const {bits} = validation
// assert(bits === 32 || bits === 64, 'unsupported float bit size: ' + bits)
const sizeName = bits === 32 ? 'Float' : bits === 64 ? 'Double' : null
assert(sizeName, 'unsupported float bit size: ' + bits)
const size = bits / 8
return {
fromByteBuffer (b) {
const bcopy = b.copy(b.offset, b.offset + size)
b.skip(size)
const fb = Buffer.from(bcopy.toBinary(), 'binary')
return floatPoint[`read${sizeName}LE`](fb)
},
appendByteBuffer (b, value) {
const output = []
floatPoint[`write${sizeName}LE`](output, value)
b.append(output)
},
fromObject (value) {
return value
},
toObject (value) {
if (validation.defaults && value == null) {
return 0.0
}
return value
}
}
}
const bytebuf = (validation) => {
const _bytebuf = {
fromByteBuffer (b) {
const {len} = validation
let bCopy
if (len == null) {
const lenPrefix = b.readVarint32()
bCopy = b.copy(b.offset, b.offset + lenPrefix)
b.skip(lenPrefix)
} else {
bCopy = b.copy(b.offset, b.offset + len)
b.skip(len)
}
return Buffer.from(bCopy.toBinary(), 'binary')
},
appendByteBuffer (b, value) {
// value = _bytebuf.fromObject(value)
const {len} = validation
if (len == null) {
b.writeVarint32(value.length)
}
b.append(value.toString('binary'), 'binary')
},
fromObject (value) {
if (typeof value === 'string') {
value = Buffer.from(value, 'hex')
} else if (value instanceof Array) {
value = Buffer.from(value)
} else if (value instanceof Uint8Array) {
value = Buffer.from(value)
}
validate(value, validation)
return value
},
toObject (value) {
const {defaults, len} = validation
if (defaults && value == null) {
return Array(len ? len + 1 : 1).join('00')
}
validate(value, validation)
return value.toString('hex')
},
compare (a, b) {
return Buffer.compare(a, b)
}
}
return _bytebuf
}
const string = (validation) => ({
fromByteBuffer (b) {
return b.readVString()
},
appendByteBuffer (b, value) {
validate(value, validation)
b.writeVString(value.toString())
},
fromObject (value) {
validate(value, validation)
return value
},
toObject (value) {
if (validation.defaults && value == null) {
return ''
}
validate(value, validation)
return value
}
})
const time = (validation) => {
const _time = {
fromByteBuffer (b) {
return b.readUint32()
},
appendByteBuffer (b, value) {
// if(typeof value !== "number")
// value = _time.fromObject(value)
validate(value, validation)
b.writeUint32(value)
},
fromObject (value) {
validate(value, validation)
if (typeof value === 'number') { return value }
if (value.getTime) { return Math.floor(value.getTime() / 1000) }
if (typeof value !== 'string') { throw new Error('Unknown date type: ' + value) }
// Chrome assumes Zulu when missing, Firefox does not
if (typeof value === 'string' && !/Z$/.test(value)) { value += 'Z' }
return Math.floor(new Date(value).getTime() / 1000)
},
toObject (value) {
if (validation.defaults && value == null) { return (new Date(0)).toISOString().split('.')[0] }
validate(value, validation)
// if(typeof value === "string") {
// if(!/Z$/.test(value))
// value += "Z"
//
// return value
// }
// if(value.getTime)
// return value.toISOString().split('.')[0] + 'Z'
validateInt(value, spread(validation, {bits: 32}))
const int = parseInt(value)
return (new Date(int * 1000)).toISOString().split('.')[0]
}
}
return _time
}
const validate = (value, validation) => {
if (isEmpty(value)) {
throw new Error(`Required ${validation.typeName}`)
}
if (validation.len != null) {
if (value.length == null) { throw new Error(`len validation requries a "length" property`) }
const {len} = validation
if (value.length !== len) { throw new Error(`${validation.typeName} length ${value.length} does not equal ${len}`) }
}
if (validation.maxLen != null) {
const {maxLen} = validation
if (value.length == null) { throw new Error(`maxLen validation requries a "length" property`) }
if (value.length > maxLen) { throw new Error(`${validation.typeName} length ${value.length} exceeds maxLen ${maxLen}`) }
}
}
const ZERO = new BN()
const ONE = new BN('1')
function validateInt (value, validation) {
if (isEmpty(value)) {
throw new Error(`Required ${validation.typeName}`)
}
const {signed = false, bits = 54} = validation
value = String(value).trim()
if(
(signed && !/^-?[0-9]+$/.test(value)) ||
(!signed && !/^[0-9]+$/.test(value))
) {
throw new Error(`Number format ${validation.typeName} ${value}`)
}
const max = signed ? maxSigned(bits) : maxUnsigned(bits)
const min = signed ? minSigned(bits) : ZERO
const i = new BN(value)
// console.log('i.toString(), min.toString()', i.toString(), min.toString())
if (i.cmp(min) < 0 || i.cmp(max) > 0) {
throw new Error(`Overflow ${validation.typeName} ${value}, ` +
`max ${max.toString()}, min ${min.toString()}, signed ${signed}, bits ${bits}`)
}
}
const isSerializer = type =>
typeof type === 'object' &&
typeof type.fromByteBuffer === 'function' &&
typeof type.appendByteBuffer === 'function' &&
typeof type.fromObject === 'function' &&
typeof type.toObject === 'function'
const toString = (value, encoding) =>
value == null ? value :
value.toString ? value.toString(encoding) :
value
const sort = (type, values) =>
type.compare ? values.sort(type.compare) : // custom compare
values.sort()
const spread = (...args) => Object.assign(...args)
const isEmpty = value => value == null
// 1 << N === Math.pow(2, N)
const maxUnsigned = bits => new BN(1).ishln(bits).isub(ONE)
const maxSigned = bits => new BN(1).ishln(bits - 1).isub(ONE)
const minSigned = bits => new BN(1).ishln(bits - 1).ineg()