-
Notifications
You must be signed in to change notification settings - Fork 25
/
language.js
1170 lines (1132 loc) · 43.4 KB
/
language.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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Node.js API.
const assert = require('assert')
const util = require('util')
// Wrapper around Buffer float parsing to exclude from NYC coverage.
const inlines = require('./inlines')
// Inline function argument parser.
const args = require('./arguments')
// Compare JSON object tree.
const deepEqual = require('fast-deep-equal')
// Determine the vivified literal of the given field, descending into the actual
// field type for ethereal fields like inlines and literals.
function vivified (field) {
if (field.vivify == 'descend') {
return vivified(field.fields[0])
}
return field.vivify
}
// TODO It always needs to be an array of fields because we need to be able to
// insert checkpoints, even for ostensible fixed fields like literal.
// TODO Note that if a child of a literal starts with fixed, this is only the
// length encoding, it can be merged into the checkpoint before the literal.
// This can be done by adding and `arrayed` property to everything that loops
// and merging any initial fields are are unarrayed.
// Interpret integers.
function integer (value, pack, extra = {}) {
// Whole integers are expected to be multiples of 8-bits and if they are off
// by one then someone applied bitwise NOT. We have to revert the bitwise
// NOT to get the bit length. Two's compliment is indicated by a positive
// value for bit length instead of a negative value.
if (!pack) {
const abs = Math.abs(value % 8)
const bits = abs != 0
? abs == 1
? value < 0
? ~value
: ~-value
: -~value
: Math.abs(value)
const bytes = []
for (let i = 0, I = bits / 8; i < I; i++) {
bytes.push({
mask: 0xff,
size: 8,
shift: (I - i - 1) * 8,
upper: 0x0
})
}
if (Math.abs(value % 8) == 1) {
if (value < 0) {
return {
type: 'integer',
vivify: 'number',
dotted: '',
fixed: true,
bits: ~value,
bytes: bytes.reverse(),
endianness: 'little',
compliment: false,
...extra
}
}
return {
type: 'integer',
vivify: 'number',
dotted: '',
fixed: true,
bytes: bytes.reverse(),
bits: ~-value,
endianness: 'little',
compliment: true,
...extra
}
}
if (value % 8 == 7) {
return {
type: 'integer',
vivify: 'number',
dotted: '',
fixed: true,
bytes: bytes.reverse(),
bits: -~value,
endianness: 'little',
compliment: true,
...extra
}
}
// Big-endian integer. Two's compliment if the bit length is negative.
return {
type: 'integer',
vivify: 'number',
dotted: '',
fixed: true,
bytes: bytes,
bits: Math.abs(value),
endianness: 'big',
compliment: value < 0,
...extra
}
}
// Big-endian integer. Two's compliment if the bit length is negative.
return {
type: 'integer',
vivify: 'number',
dotted: '',
fixed: true,
bits: Math.abs(value),
endianness: 'big',
compliment: value < 0,
...extra
}
}
function buffered (field) {
if (field === Buffer) {
return [{
type: 'buffer',
vivify: 'number',
dotted: '',
concat: true,
bits: 8,
fixed: true,
dotted: '',
endianness: 'big',
compliment: false
}]
}
if (
Array.isArray(field) &&
field.length == 1 &&
field[0] === Buffer
) {
return [{
type: 'buffer',
vivify: 'number',
dotted: '',
concat: false,
bits: 8,
fixed: true,
endianness: 'big',
compliment: false
}]
}
return null
}
module.exports = function (packets) {
const definitions = [], lookups = { values: [], index: 0 }, snippets = {}
// Please resist the urge to refactor based on, oh look, I'm performing this
// test twice. A single if/else ladder will be easier to return to for
// maintainence and expansion. Outer array.
const is = {
ultimately: function (packet, test, sip = false) {
if (test(packet)) {
return true
// **TODO**: See literal ambiguities. We're going to assume we've
// forced them into arrays.
}
if (is.literal.padded(packet)) {
if (Array.isArray(packet[0]) && packet[0].some(item => typeof item == 'string')) {
return is.ultimately(packet[1], test)
}
return is.ultimately(packet[0], test)
}
if (is.inline.split(packet) || is.inline.mirrored(packet)) {
return is.ultimately(packet[1], test)
}
if (is.accumulator(packet)) {
return is.ultimately(packet[packet.length - 1], test)
}
if (is.switched(packet)) {
return packet[1].filter((_, index) => index % 2 == 1).every(packet => {
return is.ultimately(packet, test)
})
}
if (is.conditional.mirrored(packet)) {
return packet.filter((_, index) => index % 2 == 1).every(packet => {
return is.ultimately(packet, test)
})
}
if (is.conditional.split(packet)) {
if (!packet[0].filter((_, index) => index % 2 == 1).every(packet => {
return is.ultimately(packet, test)
})) {
return false
}
const sliced = packet[1].slice()
if (typeof sliced[0] == 'number') {
sliced.shift()
}
return sliced.filter((_, index) => index % 2 == 1).every(packet => {
return is.ultimately(packet, test, true)
})
}
if (sip && is.conditional.sip(packet)) {
return packet.slice(1).filter((_, index) => index % 2 == 1).every(packet => {
return is.ultimately(packet, test, true)
})
}
return false
},
spread: function (packet) {
if (
Array.isArray(packet) &&
Number.isInteger(packet[0]) &&
packet[0] % 8 == 0 &&
packet[0] > 0 &&
packet.slice(1).every(item => {
return (
Number.isInteger(item) && 0 < item && item <= 8
) || (
Array.isArray(item) &&
item.length == 2 &&
0 <= item[0] && item[0] <= 0xff &&
0 < item[1] && item[1] <= 8
)
})
) {
const spread = packet.slice(1)
const abs = Math.abs(packet[0] % 8)
const bits = abs != 0
? abs == 1
? packet[0] < 0
? ~packet[0]
: ~-packet[0]
: -~packet[0]
: Math.abs(packet[0])
const bytes = bits / 8
while (bytes < spread.length) {
spread.splice(1, 0, spread[1])
}
return bits > spread.reduce((sum, item) => {
return sum + (Array.isArray(item) ? item[1] : item)
}, 0)
}
return false
},
integer: function (packet) {
if (Number.isInteger(packet)) {
return true
}
},
absent: function (packet) {
return packet == null || (
Array.isArray(packet) && packet.length == 0
)
},
ieee: {
// A floating point number whose integer part is 64 or 32.
shorthand: function (packet) {
const floor = Math.floor(packet)
return packet - floor != 0 && (floor == 64 || floor == 32)
},
explicit: function (packet) {
return packet.length == 2 &&
typeof packet[0] == 'number' &&
Math.floor(packet[0]) == 0 &&
(
packet[0] * 100 == packet[1] ||
packet[0] * 100 == ~packet[1]
)
}
},
// **Mapped integers**: A two element array with an integer defintion
// followed by an array entirely of strings with more than one element.
mapped: function (packet) {
return packet.length == 2 &&
is.integer(packet[0]) &&
(
Array.isArray(packet[1]) &&
packet[1].length > 1 &&
packet[1].filter(value => typeof value == 'string').length == packet[1].length
) ||
(
typeof packet[1] == 'object' &&
Object.keys(packet[1]).length > 1 &&
function () {
for (const key in packet[1]) {
if (typeof packet[1][key] != 'string') {
return false
}
}
return true
} ()
)
},
// **Literals**: Constant value padding bytes. A type definition with a
// preceding or following literal or both. The preceding or following
// element is defined by a either string of hexidecimal or an array with
// a bit size as number preceding a string hexidecimal value, or a
// string hexdecimal value followed by a repeat count as number.
literal: {
pattern: function (part) {
return typeof part == 'string' ||
(
Array.isArray(part) &&
(
part.length == 1 &&
typeof part[0] == 'string'
) ||
(
part.length == 2 &&
part.filter(item => typeof item == 'string').length == 1 &&
part.filter(item => typeof item == 'number').length == 1
)
)
},
constant: function (packet) {
return is.literal.pattern(packet)
},
padded: function (packet) {
return Array.isArray(packet) &&
(
packet.length == 2 &&
(
is.literal.pattern(packet[0]) ||
is.literal.pattern(packet[1])
)
) ||
(
packet.length == 3 &&
is.literal.pattern(packet[0]) &&
is.literal.pattern(packet[2])
)
}
},
// **Inline functions**: User defined functions that perform inline
// transformations and assertions.
inline: {
split: function (packet) {
return Array.isArray(packet) &&
packet.length == 3 &&
Array.isArray(packet[0]) &&
Array.isArray(packet[packet.length - 1]) &&
(
typeof packet[0][0] == 'function' ||
typeof packet[packet.length - 1][0] == 'function'
)
},
// **Inline mirrored functions**: User defined functions that
// perform inline transformations or assertions defined once for
// both pre-serialization and post-parsing.
mirrored: function (packet) {
return Array.isArray(packet) &&
packet.length == 2 &&
Array.isArray(packet[0]) &&
packet[0].length == 1 &&
Array.isArray(packet[0][0]) &&
typeof packet[0][0][0] == 'function'
}
},
// **Packed integers**: Defined by an object that is not an array
// followed by a number.
packed: function (packet) {
return typeof packet[0] == 'object' &&
! Array.isArray(packet[0]) &&
typeof packet[1] == 'number'
},
// **Terminated arrays**: An array followed by one or more numbers
// representing termination bytes.
terminated: function (packet) {
return Array.isArray(packet[0]) &&
typeof packet[1] == 'number'
},
// **Fixed length arrays**: Arrays of fixed length or calculated length.
fixed: function (packet) {
return Array.isArray(packet[0]) &&
(
packet[0].length == 1 &&
(
is.integer(packet[0][0]) ||
typeof packet[0][0] == 'function'
)
) &&
Array.isArray(packet[1]) &&
packet[1].length == 1
},
// **Length-encoded arrays**: Length encoded by a leading integer.
lengthEncoded: function (packet) {
return packet.length == 2 &&
Array.isArray(packet[1]) &&
packet[1].length == 1 &&
is.ultimately(packet[0], value => is.integer(value) || is.spread(value))
},
switched: function (packet) {
return typeof packet[0] == 'function' &&
Array.isArray(packet[1]) &&
packet[1].length % 2 == 0 &&
packet[1].filter((value, index) => {
return index % 2 == 1 ||
(
typeof value == 'object' &&
(
(
Object.keys(value).length == 1 &&
('$_' in value)
) ||
(
Object.keys(value).length == 0 &&
index == packet[1].length - 2
)
)
)
}).length == packet[1].length
},
// *Accumulators*:
accumulator: function (packet) {
return Array.isArray(packet) &&
packet.length == 2 &&
typeof packet[0] == 'object' &&
! Array.isArray(packet[0]) &&
! Array.isArray(packet[0][0])
},
// **Conditionals**: TODO Come back and create a set of test functions
// and maybe put them in an object. It would simplify this ladder. Kind
// of don't want them named and scattered.
//
// TODO This is a weak test. We could test that every other element is a
// function.
conditional: {
ladder: function (array) {
if (!Array.isArray(array) || array.length % 2 != 0) {
return false
}
if (typeof array[array.length - 2] == 'boolean') {
array = array.slice(0, array.length - 2)
} else if (array.length < 4) {
return false
}
return array.filter((value, index) => {
return index % 2 == 1 || typeof value == 'function'
}).length == array.length
},
sip: function (array) {
return Array.isArray(array) &&
typeof array[0] == 'number' &&
is.conditional.ladder(array.slice(1))
},
split: function (packet) {
return packet.length == 2 &&
is.conditional.ladder(packet[0]) &&
(
is.conditional.ladder(packet[1]) ||
is.conditional.sip(packet[1])
)
},
mirrored: function (packet) {
return is.conditional.ladder(packet)
}
}
}
function map (packet, extra = {}, pack = false) {
const ieee = {
shorthand: function () {
const fractional = packet - Math.floor(packet) != 0
switch (Math.floor(packet)) {
case 64:
if (fractional == 0.46) {
return map([ 0.64, ~64 ], extra)
}
return map([ 0.64, 64 ], extra)
case 32:
default:
if (fractional == 0.23) {
return map([ 0.32, ~32 ], extra)
}
return map([ 0.32, 32 ], extra)
}
},
explicit: function () {
if (Math.abs(packet[1]) % 8 == 1) {
const bits = Math.abs(packet[1] + 1)
assert.equal(packet[0] * 100, bits, 'bits mismatch')
switch (bits) {
case 64:
return map([[
inlines.writeDoubleLE
], [[ 8 ], [ Buffer ]], [
inlines.readDoubleLE
]], extra)
case 32:
return map([[
inlines.writeFloatLE
], [[ 4 ], [ Buffer ]], [
inlines.readFloatLE
]], extra)
}
}
assert.equal(packet[0] * 100, packet[1], 'bits mismatch')
switch (packet[1]) {
case 64:
return map([[
inlines.writeDoubleBE
], [[ 8 ], [ Buffer ]], [
inlines.readDoubleBE
]], extra)
case 32:
return map([[
inlines.writeFloatBE
], [[ 4 ], [ Buffer ]], [
inlines.readFloatBE
]], extra)
}
}
}
//
// **Integers or IEEE754 shorthand**:
function number () {
if (is.ieee.shorthand(packet)) return ieee.shorthand()
else return [ integer(packet, pack, extra) ]
}
//
// **BigtInt**
function bigint () {
return [ integer(Number(packet), pack, { ...extra, type: 'bigint', vivify: 'bigint' }) ]
}
//
// **Absent**: A `null` or empty array `[]` on parse, ignored on
// serialize. Used when there should be no value, combined with
// conditionals to implement optional fields.
function absent (value) {
return [{
type: 'absent',
vivify: value == null ? 'variant' : 'array',
value: value,
dotted: '',
bits: 0,
fixed: true,
...extra
}]
}
//
// **Spread**: An integer spread out across multiple bytes that may or
// may not use every bit in that byte.
function spread () {
const abs = Math.abs(packet[0] % 8)
const bits = abs != 0
? abs == 1
? Math.abs(~packet[0])
: -~packet[0]
: Math.abs(packet[0])
let spread = packet.slice(1)
while (spread.length < bits / 8) {
spread.splice(1, 0, spread[1])
}
spread = spread.map((item, index) => {
return Array.isArray(item)
? { upper: item[0], size: item[1] }
: { upper: 0, size: item }
})
const bytes = spread.map((item, index) => {
return {
shift: spread.slice(index + 1).reduce((sum, item) => sum + item.size, 0),
size: item.size,
mask: 0xff >>> 8 - item.size,
upper: item.upper
}
})
return [ integer(packet[0], false, { ...extra, bytes }) ]
}
//
// **Mapped integers**: Integers mapped to a string value.
function mapped () {
const lookup = function () {
const values = JSON.parse(JSON.stringify(packet[1]))
for (let i = 0, I = lookups.values.length; i < I; i++) {
if (deepEqual(values, lookups.values[i])) {
return {
index: i,
values: values
}
break
}
}
const index = lookups.index++
lookups.values[index] = values
return { index, values }
} ()
return map(packet[0], { lookup, ...extra }, pack)
}
function literal (sliced, index) {
if (
typeof sliced[index] == 'string'
) {
const value = sliced.splice(index, 1).pop()
return {
repeat: 1,
value: value,
bits: value.length * 4
}
// **TODO**: Ambiguity if we have literals inside literals. Would be
// resolved by insisting on the array surrounding the literal
// definition.
// **TODO**: Second ambiguity. Includes can be confused with
// literals. May have to force literals into arrays, or else force
// includes into arrays. Maybe let's force literals into arrays
// since arrays are there already.
} else if (
Array.isArray(sliced[index]) &
sliced[index].length == 2 &&
typeof sliced[index][1] == 'string'
) {
const packed = sliced.splice(index, 1).pop()
return {
repeat: 1,
value: packed[1],
bits: packed[0]
}
} else if (
Array.isArray(sliced[index]) &&
(
sliced[index].length == 2 ||
sliced[index].length == 1
) &&
typeof sliced[index][0] == 'string'
) {
const repeated = sliced.splice(index, 1).pop()
const repeat = repeated[1] || 1
const value = repeat < 0
? repeated[0].match(/.{1,2}/g).reverse().join('')
: repeated[0]
return {
repeat: repeat < 0 ? ~repeat : repeat,
value: value,
bits: repeated[0].length * 4
}
} else {
return { repeat: 0, value: '', bits: 0 }
}
}
function constant () {
// TODO Do not want to create and then destroy, but this gets this
// done for now.
const before = literal([ packet.slice() ], 0)
return [{
type: 'literal',
dotted: '',
vivify: null,
fixed: true,
bits: before.repeat * before.bits,
before: before,
after: { repeat: 0, value: '', bits: 0 },
fields: []
}]
}
// **Literals**:
function padded () {
const sliced = packet.slice(0)
const before = literal(sliced, 0)
const after = literal(sliced, sliced.length - 1)
// TODO Use `field` as a common child then do bits recursively.
// Aren't we going by fixed anyway?
const fields = map(sliced[0], {}, pack)
// TODO Test literal wrap of a structure.
// TODO Test literal wrap of an array.
return [{
type: 'literal',
dotted: '',
vivify: 'descend',
fixed: fields[0].fixed,
bits: fields[0].fixed
? fields[0].bits + before.repeat * before.bits
+ after.repeat * after.bits
: 0,
before: before,
fields: fields,
after: after,
...extra
}]
}
//
//
const inline = {
inliner: function (inlined, array) {
while (array.length != 0) {
inlined.push(args(array))
}
},
split: function () {
const define = packet.slice()
const before = []
inline.inliner(before, define.shift().slice())
const after = []
inline.inliner(after, define.pop().slice())
const fields = map(define[0], {}, pack)
return [{
type: 'inline',
// TODO Test with a structure member.
// TODO Test with an array member.
vivify: 'descend',
dotted: '',
bits: fields[0].bits,
fixed: fields[0].fixed,
before: before,
fields: fields,
after: after,
...extra
}]
},
mirrored: function () {
const inlines = packet[0][0]
const before = []
inline.inliner(before, inlines.slice())
const after = []
inline.inliner(after, inlines.slice())
const fields = map(packet[1], {}, pack)
return [{
type: 'inline',
// TODO Test with a structure member.
// TODO Test with an array member.
vivify: 'descend',
dotted: '',
bits: fields[0].bits,
fixed: fields[0].fixed,
before: before,
fields: fields,
after: after,
...extra
}]
}
}
function packed () {
if (extra.name != null && extra.name[0] == '_') {
extra = { name: '', dotted: '', vivify: 'elide' }
}
const fields = []
for (const name in packet[0]) {
fields.push.apply(fields, map(packet[0][name], {
name: name, dotted: `.${name}`
}, true))
}
const into = integer(packet[1], pack, {
vivify: 'object',
...extra
})
return [{ ...into, fields, ...extra }]
}
function terminated () {
const terminator = []
for (let i = 1, I = packet.length; i < I; i++) {
terminator.push(packet[i])
}
const fields = buffered(packet[0][0]) || map(packet[0][0], {})
return [{
dotted: '',
...extra,
type: 'terminated',
vivify: fields[0].type == 'buffer' ? 'variant' : 'array',
bits: 0,
fixed: false,
terminator: terminator,
fields: fields
}]
}
function fixed () {
const pad = []
const slice = packet.slice(2)
while (typeof slice[0] == 'number') {
pad.push(slice.shift())
}
const fields = buffered(packet[1][0]) || map(packet[1][0], {})
const fixed = fields.filter(field => ! field.fixed).length == 0
const bits = fixed
? fields.reduce((bits, field) => bits + field.bits, 0)
: 0
const calculated = typeof packet[0][0] == 'function'
const length = calculated ? args([ packet[0][0] ]) : packet[0][0]
return [{
type: 'fixed',
vivify: fields[0].type == 'buffer' ? 'variant' : 'array',
dotted: '',
...extra,
pad,
calculated,
fixed: calculated ? false : fixed,
length: length,
bits: calculated ? 0 : bits * packet[0][0],
fields
}]
}
function lengthEncoded () {
const fields = []
assert(Array.isArray(packet[1]))
const encoding = map(packet[0], { dotted: '' })
const element = buffered(packet[1][0]) || map(packet[1][0], {})
assert.equal(element.length, 1, 'badness')
fields.push({
type: 'lengthEncoded',
vivify: element.type == 'buffer' ? 'variant' : 'array',
encoding: encoding,
dotted: '',
bits: 0,
fixed: false,
// TODO Length encode a structure.
fields: [ element[0] ],
...extra
})
return fields
}
const conditional = {
split: function () {
const fields = []
const serialize = function () {
const serialize = packet[0].slice()
const conditions = []
while (serialize.length) {
const test = serialize.shift()
const field = serialize.shift()
switch (typeof test) {
case 'function':
conditions.push({
test: { ...args([ test ]) },
fields: map(field, {}, pack)
})
break
case 'boolean':
conditions.push({
test: null,
fields: map(field, {}, pack)
})
break
}
}
return {
conditions: conditions,
unconditional: conditions.length == 1 && conditions[0].test == null
}
} ()
function descend (parse, sipping = {}) {
const sip = []
if (typeof parse[0] == 'number') {
sip.push(map(parse.shift(), {}).shift())
}
const conditions = []
while (parse.length) {
const test = parse.shift()
const field = parse.shift()
const fields = function () {
// Described this hack in `parse.inc.js` over `conditional`.
if (is.conditional.sip(field)) {
const sip = descend(field.slice(0), { type: 'sip' })
if (sip.conditions.length == 1 && sip.conditions[0].test == null) {
return sip.conditions[0].fields
}
return [ sip ]
}
return map(field, {}, pack)
} ()
switch (typeof test) {
case 'function':
conditions.push({ test: { ...args([ test ]) }, fields: fields })
break
case 'boolean':
conditions.push({ test: null, fields: fields })
break
}
}
const vivify = conditions.slice(1).reduce((vivify, condition) => {
return vivify == 'variant' || vivify == vivified(condition.fields[0])
? vivify
: 'variant'
}, conditions[0].fields[0].vivify)
return {
...sipping,
sip: sip.length ? sip : null,
vivify: vivify,
unconditional: conditions.length == 1 && conditions[0].test == null,
conditions: conditions
}
}
const parse = descend(packet[1].slice())
// TODO Is fixed if all the alternations are the same length.
fields.push({
type: 'conditional',
dotted: '',
vivify: parse.vivify == 'object' ? 'variant' : parse.vivify,
bits: 0,
fixed: false,
split: true,
serialize, parse, ...extra
})
return fields
},
mirrored: function () {
packet = packet.slice()
const fields = []
const conditions = []
while (packet.length) {
const test = packet.shift()
const fields = map(packet.shift(), {}, pack)
switch (typeof test) {
case 'function':
conditions.push({
body: {
test: { ...args([ test ]) },
fields: fields
},
bits: fields.reduce((bits, field) => {
return bits == -1 || !field.fixed ? -1 : bits + field.bits
}, 0)
})
break
case 'boolean':
conditions.push({
body: {
test: null,
fields: fields
},
bits: fields.reduce((bits, field) => {
return bits == -1 || !field.fixed ? -1 : bits + field.bits
}, 0)
})
break
}
}
const fixed = conditions.reduce((bits, cond) => {
return cond.bits == -1 ? -1
: bits == cond.bits ? bits
: -1
}, conditions[0].bits)
const vivify = conditions.slice(1).reduce((vivify, condition) => {
return vivify == 'variant' || vivify == condition.body.fields[0].vivify
? vivify
: 'variant'
}, conditions[0].body.fields[0].vivify)
const unconditional = conditions.length == 1 && conditions[0].body.test == null
return [{
type: 'conditional',
bits: fixed == -1 ? 0 : conditions[0].bits,
fixed: fixed != -1,
vivify: vivify == 'object' ? 'variant' : vivify,
split: false,
serialize: {
conditions: conditions.map(cond => cond.body),
unconditional: unconditional
},
parse: {
sip: null,
conditions: JSON.parse(JSON.stringify(conditions)).map(cond => cond.body),
unconditional: unconditional
},
...extra
}]
}
}
function accumulator () {
const accumulators = Object.keys(packet[0]).map(name => {
const accumulator = packet[0][name]
switch (typeof accumulator) {
case 'function':
return {
type: 'function',
name: name,
...args([ accumulator ])
}
default:
if (accumulator instanceof RegExp) {
return {
type: 'regex',
name: name,
source: accumulator.toString()
}
}
return {
type: 'object',
name: name,
source: util.inspect(accumulator, { depth: null })
}
}
})
// TODO Would you put an accumulator aroudn a single packed field?
const fields = map(packet[1], {})
return [{
type: 'accumulator',