-
Notifications
You must be signed in to change notification settings - Fork 6
/
jpacks.js
1760 lines (1760 loc) · 50.7 KB
/
jpacks.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
(function (exportName) {
/**
* @file jpacks
*
* Binary data packing and unpacking.
* @author
* zswang (http://weibo.com/zswang)
* @version 0.8.6
* @date 2017-06-14
*/
function createSchema() {
/**
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView
*/
var schemas = {};
/**
* 数据结构
* @param options 配置项
* @param {Function} options.unpack 数据解析的方法
* [[[
* @param {ArrayBuffer|Buffer|Array} buffer 数据缓存
* @param {Object=} options 配置项
* @param {Array=} offsets 第一个原始为偏移,数值类型是为了能修改值
* @return {Any} 返回解析后的对象
* ]]]
* function unpack(buffer, options, offsets) {}
* @param {Function} options.pack 数据打包的方法
* [[[
* @param {Any} value 需要打包的对象
* @param {Object=} options 配置项
* @param {buffer=} {Array} 目标字节数组
* ]]]
* function pack(value, options, buffer) {}
* @param {number} options.size 占用大小,如果为负数则为动态类型,绝对值为最小尺寸
* @param {string} options.name 类型名称
* @param {string} options.namespace 命名空间 e.g. ( 'base': 基础类型 )
* @constructor 构造数据结构类型
*/
function Schema(options) {
options = options || {};
var self = this;
Object.keys(options).forEach(function(key) {
self[key] = options[key];
});
}
/**
* 定义数据结构
*
* @param {string} name 数据结构名
* @param {Schema|string|Function} schema 数据结构或者数据结构名
* @return {boolean} 返回是否定义成功
*/
Schema.register = function(name, schema) {
schemas[name] = schema;
if (!Schema[name]) { // 避免覆盖系统方法
Schema[name] = schema;
}
};
/**
* register 别名
*/
Schema.def = Schema.register;
/**
* 匹配数据结构的方法集合
*
* @type {Array}
*/
var schemaPatterns = [
function _pattern(schema) {
var dicts = {};
var findSchema = schema;
while (typeof findSchema === 'string') {
if (dicts[findSchema]) {
return;
}
findSchema = schemas[findSchema];
dicts[findSchema] = true;
}
return findSchema;
}
];
/**
* 添加匹配数据结构的方法集合
*
* @param {Function} pattern 匹配方法
* [[[
* @param {string|object} schema 用于测试的对象
* @return {Schema} 返回匹配的配数据结构,如果没有匹配的结果则返回 undefined
* function _pattern(schema) {}
* ]]]
*/
Schema.pushPattern = function(pattern) {
schemaPatterns.push(pattern);
};
/**
* 确保是数据结构
*
* @param {string|Object|Schema} schema 数据结构名
* @return {Schema} 返回名字对应的数据结构
*/
Schema.from = function(schema) {
if (schema instanceof Schema) {
return schema;
}
var filter = -1;
for (var i = 0; i < schemaPatterns.length; i++) { // 解析表达式
if (filter === i) { // 已经被过滤
continue;
}
var match = schemaPatterns[i](schema);
if (match) {
if (match instanceof Schema) {
return match;
}
schema = match; // 类型改变
filter = i; // 不要走同一个规则
i = 0; // 重新扫描
}
}
};
/**
* 默认低字节序
*
* @type {boolean}
*/
var defaultOptions = {
littleEndian: true
};
/**
* 设置默认配置
*
* @param {boolean} options 默认值
*/
function setDefaultOptions(options) {
options = options || {};
Object.keys(options).forEach(function(key) {
defaultOptions[key] = options[key];
});
}
Schema.setDefaultOptions = setDefaultOptions;
/**
* 确保是 ArrayBuffer 类型
*
* @param {Array|Buffer|string} 数组和缓冲区
* @return {ArrayBuffer} 返回转换后的 ArrayBuffer
'''<example>'''
* @example arrayBufferFrom():string
```js
var _ = jpacks;
var ab = _.arrayBufferFrom('abc');
console.log(new Buffer(new Uint8Array(ab)).toString('hex'));
// > 616263
```
* @example arrayBufferFrom():string Unicode
```js
var _ = jpacks;
var ab = _.arrayBufferFrom('汉字');
console.log(new Buffer(new Uint8Array(ab)).toString('hex'));
// > e6b189e5ad97
```
'''</example>'''
*/
function arrayBufferFrom(buffer, options) {
if (buffer instanceof ArrayBuffer) {
return buffer;
}
if (typeof buffer === 'string' && Schema.stringBytes) {
buffer = Schema.stringBytes(buffer, options);
}
var ab = new ArrayBuffer(buffer.length);
var arr = new Uint8Array(ab, 0, buffer.length);
arr.set(buffer);
return ab;
}
Schema.arrayBufferFrom = arrayBufferFrom;
/**
* 解包
*
* @param {string|Object|Schema} packSchema 数据结构信息
* @param {ArrayBuffer|Buffer} buffer 缓冲区
* @param {Array=} offsets 读取偏移,会被改写
* @return {Number|Object} 返回解包的值
'''<example>'''
* @example together():base
```js
var _ = jpacks;
function f(a, b, c) {
console.log(JSON.stringify([a, b, c]));
}
var t = _.together(f);
t(1)()(2, 3);
// > [1,2,3]
t(4)(5)()(6);
// > [4,5,6]
t(7, 8, 9);
// > [7,8,9]
t('a', 'b')('c');
// > ["a","b","c"]
t()('x')()()('y')()()('z');
// > ["x","y","z"]
```
* @example together():hook
```js
var _ = jpacks;
function f(a, b, c) {}
var t = _.together(f, function(t, args) {
t.schema = 'f(' + args + ')';
});
console.log(t(1)(2).schema);
// > f(1,2)
function go() {
console.log(1);
}
var g = _.together(go);
g();
// > 1
```
'''</example>'''
*/
function unpack(packSchema, buffer, options, offsets) {
if (packSchema === null) {
return null;
}
var schema = Schema.from(packSchema);
options = options || {};
offsets = offsets || [0];
Object.keys(schema.defaultOptions || {}).forEach(function(key) {
if (typeof options[key] === 'undefined') {
options[key] = schema.defaultOptions[key];
}
});
Object.keys(defaultOptions).forEach(function(key) {
if (typeof options[key] === 'undefined') {
options[key] = defaultOptions[key];
}
});
return schema.unpack(arrayBufferFrom(buffer, options), options, offsets); // 解码
}
Schema.unpack = unpack;
/**
* 组包
*
* @param {string|Object|Schema} schema 数据结构信息
* @param {Number|Object} data 数据
* @param {Object} options 配置信息
* @return {ArrayBuffer}
*/
function pack(packSchema, data, options, buffer) {
if (packSchema === null) {
return null;
}
var schema = Schema.from(packSchema);
buffer = buffer || [];
options = options || {};
Object.keys(schema.defaultOptions || {}).forEach(function(key) {
if (typeof options[key] === 'undefined') {
options[key] = schema.defaultOptions[key];
}
});
Object.keys(defaultOptions).forEach(function(key) {
if (typeof options[key] === 'undefined') {
options[key] = defaultOptions[key];
}
});
schema.pack(data, options, buffer);
return buffer;
}
Schema.pack = pack;
/**
* 凑足参数则调用函数
*
* @param {Function} fn 任意函数
* @param {Array=} args 已经凑到的参数
'''<example>'''
* @example together():base
```js
var _ = jpacks;
function f(a, b, c) {
console.log(JSON.stringify([a, b, c]));
}
var t = _.together(f);
t(1)()(2, 3);
// > [1,2,3]
t(4)(5)()(6);
// > [4,5,6]
t(7, 8, 9);
// > [7,8,9]
t('a', 'b')('c');
// > ["a","b","c"]
t()('x')()()('y')()()('z');
// > ["x","y","z"]
```
* @example together():hook
```js
var _ = jpacks;
function f(a, b, c) {}
var t = _.together(f, function(t, args) {
t.schema = 'f(' + args + ')';
});
console.log(t(1)(2).schema);
// > f(1,2)
function go() {
console.log(1);
}
var g = _.together(go);
g();
// > 1
```
'''</example>'''
*/
function together(fn, hook, args) {
if (fn.length <= 0) {
return fn;
}
var result = function() {
var list = [];
[].push.apply(list, args);
[].push.apply(list, arguments);
if (list.length >= fn.length) {
return fn.apply(null, list);
} else {
var result = together(fn, hook, list);
if (typeof hook === 'function') {
hook(result, list);
}
return result;
}
};
return result;
}
Schema.together = together;
/**
* 获取对象的结构表达式
*
* @param {Any} obj 目标对象
*/
function stringify(obj) {
if (arguments.length > 1) {
var result = [];
for (var i = 0; i < arguments.length; i++) {
result.push(stringify(arguments[i]));
}
return result.join();
}
function scan(obj) {
if (obj === null) {
return 'null';
}
if (!obj) {
return obj;
}
if (obj.namespace) {
if (obj.namespace === 'number') {
return "'" + obj.name + "'";
}
if (obj.args) {
return obj.namespace + '(' + stringify.apply(null, obj.args) + ')';
}
return "'" + obj.namespace + "'";
}
if (typeof obj === 'function') {
if (!obj.name) {
obj.namespace = '$fn';
return obj.namespace;
}
} else if (typeof obj === 'object') {
var result = new obj.constructor();
Object.keys(obj).forEach(function(key) {
result[key] = scan(obj[key]);
});
return result;
}
if (obj.name) {
return "'" + obj.name + "'";
}
if (typeof obj === 'string') {
return "'" + obj + "'";
}
return obj;
}
return JSON.stringify(scan(obj) || '').replace(/"/g, '');
}
Schema.stringify = stringify;
Schema.prototype.toString = function() {
return stringify(this);
};
return Schema;
}
/**
* 创建数据结构作用域
*
* @return 返回 Schema
*/
function create() {
var Schema = createSchema();
/**
* 基础类型
*
* @type {Object}
* @key 基础类型名称
* @value
* @field {string} type 对应 DataView 类型名
* @field {number} size 数据大小,单位 byte
* @field {Array of string} alias 别名
'''<example>'''
* @example all number
```js
var _ = jpacks;
var _map = {
bytes: _.bytes(8)
};
'int8,int16,int32,uint8,uint16,uint32,float32,float64,shortint,smallint,longint,byte,word,longword'.split(/,/).forEach(function (item) {
_map[item] = item;
});
var _schema = _.union(_map, 8);
console.log(_.stringify(_schema));
// > union({bytes:array('uint8',8),int8:'int8',int16:'int16',int32:'int32',uint8:'uint8',uint16:'uint16',uint32:'uint32',float32:'float32',float64:'float64',shortint:'shortint',smallint:'smallint',longint:'longint',byte:'byte',word:'word',longword:'longword'},8)
var buffer = _.pack(_schema, {
bytes: [0x12, 0x23, 0x34, 0x45, 0x56, 0x67, 0x78, 0x89]
});
console.log(buffer.join(' '));
// > 18 35 52 69 86 103 120 137
console.log(JSON.stringify(_.unpack(_schema, buffer)));
// > {"bytes":[18,35,52,69,86,103,120,137],"int8":18,"int16":8978,"int32":1161044754,"uint8":18,"uint16":8978,"uint32":1161044754,"float32":2882.19189453125,"float64":-4.843717058781651e-263,"shortint":18,"smallint":8978,"longint":1161044754,"byte":18,"word":8978,"longword":1161044754}
```
'''</example>'''
*/
var bases = {
int8: {
type: 'Int8',
size: 1,
alias: ['shortint'],
array: Int8Array
},
uint8: {
type: 'Uint8',
size: 1,
alias: ['byte'],
array: Uint8Array
},
int16: {
type: 'Int16',
size: 2,
alias: ['smallint'],
array: Int16Array
},
uint16: {
type: 'Uint16',
size: 2,
alias: ['word'],
array: Uint16Array
},
int32: {
type: 'Int32',
size: 4,
alias: ['longint'],
array: Int32Array
},
uint32: {
type: 'Uint32',
size: 4,
alias: ['longword'],
array: Uint32Array
},
float32: {
type: 'Float32',
size: 4,
alias: ['single'],
array: Float32Array
},
float64: {
type: 'Float64',
size: 8,
alias: ['double'],
array: Float64Array
},
};
/**
* 定义基础类型
*/
Object.keys(bases).forEach(function (name) {
var item = bases[name];
var schema = new Schema({
unpack: (function (method) {
return function _unpack(buffer, options, offsets) {
var offset = offsets[0];
offsets[0] += item.size;
var dataView;
if (buffer instanceof DataView) {
dataView = buffer;
} else {
dataView = new DataView(buffer);
}
return dataView[method](offset, options.littleEndian);
};
})('get' + item.type),
pack: (function (method) {
return function _pack(value, options, buffer) {
var arrayBuffer = new ArrayBuffer(item.size);
var dataView = new DataView(arrayBuffer);
var uint8Array = new Uint8Array(arrayBuffer);
dataView[method](0, value, options.littleEndian);
[].push.apply(buffer, uint8Array);
};
})('set' + item.type),
size: item.size,
name: name,
namespace: 'number',
array: item.array
});
Schema.register(name, schema);
(item.alias || []).forEach(function (alias) {
Schema.register(alias, schema);
});
});
/**
* 声明指定长度或者下标的数组
*
* @param {string|Schema} item 元素类型
* @param {string|Schema|number=} count 下标类型或个数
* @return {Schema|Function} 返回数据结构
'''<example>'''
* @example arrayCreator():static array
```js
var _ = jpacks;
var _schema = jpacks.array('int16', 2);
console.log(String(_schema));
// > array('int16',2)
var value = [12337, 12851];
var buffer = jpacks.pack(_schema, value);
console.log(buffer.join(' '));
// > 49 48 51 50
console.log(JSON.stringify(_.unpack(_schema, buffer)));
// > [12337,12851]
```
* @example arrayCreator():dynamic array
```js
var _ = jpacks;
var _schema = jpacks.array('int16', 'int8');
console.log(String(_schema));
// > array('int16','int8')
var value = [12337, 12851];
var buffer = jpacks.pack(_schema, value);
console.log(buffer.join(' '));
// > 2 49 48 51 50
console.log(JSON.stringify(_.unpack(_schema, buffer)));
// > [12337,12851]
```
* @example arrayCreator():dynamic array 2
```js
var _ = jpacks;
var _schema = jpacks.array('int16')(6);
console.log(String(_schema));
// > array('int16',6)
var value = [12337, 12851];
var buffer = jpacks.pack(_schema, value);
console.log(buffer.join(' '));
// > 49 48 51 50 0 0 0 0 0 0 0 0
console.log(JSON.stringify(jpacks.unpack(_schema, buffer)));
// > [12337,12851,0,0,0,0]
```
* @example arrayCreator():auto size int8
```js
var _ = jpacks;
var _schema = _.array('int8', null);
console.log(_.stringify(_schema))
// > array('int8',null)
var buffer = _.pack(_schema, [0, 1, 2, 3, 4, 5, 6, 7]);
console.log(buffer.join(' '));
// > 0 1 2 3 4 5 6 7
console.log(JSON.stringify(_.unpack(_schema, buffer)));
// > [0,1,2,3,4,5,6,7]
```
* @example arrayCreator():auto size int16 littleEndian = true
```js
var _ = jpacks;
var _schema = _.array('int16', null);
var options = {
littleEndian: true
};
console.log(_.stringify(_schema))
// > array('int16',null)
var buffer = _.pack(_schema, [0, 1, 2, 3, 4, 5, 6, 7], options);
console.log(buffer.join(' '));
// > 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0
console.log(JSON.stringify(_.unpack(_schema, buffer, options)));
// > [0,1,2,3,4,5,6,7]
```
* @example arrayCreator():auto size int16 littleEndian = false
```js
var _ = jpacks;
var _schema = _.array('int16', null);
var options = {
littleEndian: false
};
console.log(_.stringify(_schema))
// > array('int16',null)
var buffer = _.pack(_schema, [0, 1, 2, 3, 4, 5, 6, 7], options);
console.log(buffer.join(' '));
// > 0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7
console.log(JSON.stringify(_.unpack(_schema, buffer, options)));
// > [0,1,2,3,4,5,6,7]
```
* @example arrayCreator():size fault tolerant
```js
var _ = jpacks;
var _schema = _.array('int8', 4);
console.log(_.stringify(_schema))
// > array('int8',4)
var buffer = _.pack(_schema, [0, 1, 2, 3, 4, 5, 6, 7]);
console.log(buffer.join(' '));
// > 0 1 2 3
console.log(JSON.stringify(_.unpack(_schema, buffer)));
// > [0,1,2,3]
var buffer = _.pack(_schema, [0, 1, 2]);
console.log(buffer.join(' '));
// > 0 1 2 0
console.log(JSON.stringify(_.unpack(_schema, buffer)));
// > [0,1,2,0]
```
* @example arrayCreator():defaultOptions & littleEndian
```js
var _ = jpacks;
var _schema = _.array('int16', 7);
_schema.defaultOptions = {
littleEndian: false
};
var buffer = _.pack(_schema, [1, 2, 3, 4, 5, 6, 7]);
console.log(buffer.join(' '));
// > 0 1 0 2 0 3 0 4 0 5 0 6 0 7
_schema.defaultOptions = {
littleEndian: true
};
var buffer = _.pack(_schema, [1, 2, 3, 4, 5, 6, 7]);
console.log(buffer.join(' '));
// > 1 0 2 0 3 0 4 0 5 0 6 0 7 0
```
'''</example>'''
*/
function arrayCreator(item, count) {
var countSchema;
if (count !== 'number' && count !== null) { // static size && auto size
countSchema = Schema.from(count);
}
return new Schema({
unpack: function _unpack(buffer, options, offsets) {
var length;
if (countSchema) {
length = Schema.unpack(countSchema, buffer, options, offsets);
} else {
length = count;
}
if (length === 0) {
return [];
}
var result = [];
var itemSchema = Schema.from(item);
if (itemSchema.array && (options.littleEndian || itemSchema.size === 1)) {
var offset = offsets[0];
var size = length === null ? buffer.byteLength - offset : itemSchema.size * length;
/* TypeArray littleEndian is true */
var arrayBuffer = new ArrayBuffer(size);
var typeArray = new itemSchema.array(arrayBuffer);
var uint8Array = new Uint8Array(arrayBuffer);
uint8Array.set(
new Uint8Array(buffer, offset, Math.min(size, buffer.byteLength - offset))
);
[].push.apply(result, typeArray);
offsets[0] += size;
return result;
}
if (length === null) { // auto size
var laseOffset;
while (offsets[0] < buffer.byteLength && laseOffset !== offsets[0]) {
laseOffset = offsets[0];
result.push(Schema.unpack(itemSchema, buffer, options, offsets));
}
} else {
for (var i = 0; i < length; i++) {
result.push(Schema.unpack(itemSchema, buffer, options, offsets));
}
}
return result;
},
pack: function _pack(value, options, buffer) {
var itemSchema = Schema.from(item);
if (!value && !countSchema) { // 数据不变
return;
}
var length;
if (countSchema) {
length = value ? value.length : 0;
Schema.pack(countSchema, length, options, buffer);
} else {
length = count === null ? (value || []).length : count;
}
if (!value || !length) {
return;
}
if (itemSchema.array && (options.littleEndian || itemSchema.size === 1)) {
var size = itemSchema.size * length;
/* TypeArray littleEndian is true */
var arrayBuffer = new ArrayBuffer(size);
var typeArray = new itemSchema.array(arrayBuffer);
typeArray.set(value.slice(0, length));
var uint8Array = new Uint8Array(arrayBuffer);
[].push.apply(buffer, uint8Array);
return;
}
for (var i = 0; i < length; i++) {
Schema.pack(itemSchema, (value || [])[i], options, buffer);
}
},
namespace: 'array',
args: arguments,
size: count === 'number' ? itemSchema.size * count : undefined
});
}
var array = Schema.together(arrayCreator, function(fn, args) {
fn.namespace = 'array';
fn.args = args;
});
Schema.register('array', array);
function shortArray(itemSchema) {
return array(itemSchema, 'uint8');
}
Schema.register('shortArray', shortArray);
function smallArray(itemSchema) {
return array(itemSchema, 'uint16');
}
Schema.register('smallArray', smallArray);
function longArray(itemSchema) {
return array(itemSchema, 'uint32');
}
Schema.register('longArray', longArray);
/**
* 字节数组
*
* @param {string|Schema|number=} count 下标类型或个数
* @return {Schema|Function} 返回数据结构
'''<example>'''
* @example bytes()
```js
var _ = jpacks;
var _schema = jpacks.bytes(6);
console.log(String(_schema));
// > array('uint8',6)
var value = [0, 1, 2, 3, 4, 5];
var buffer = jpacks.pack(_schema, value);
console.log(buffer.join(' '));
// > 0 1 2 3 4 5
console.log(JSON.stringify(_.unpack(_schema, buffer)));
// > [0,1,2,3,4,5]
```
* @example bytes() auto size
```js
var _ = jpacks;
var _schema = jpacks.bytes(null);
console.log(String(_schema));
// > array('uint8',null)
var value = [0, 1, 2, 3, 4, 5];
var buffer = jpacks.pack(_schema, value);
console.log(buffer.join(' '));
// > 0 1 2 3 4 5
console.log(JSON.stringify(_.unpack(_schema, buffer)));
// > [0,1,2,3,4,5]
```
'''</example>'''
*/
function bytes(count) {
return Schema.array('uint8', count);
}
Schema.register('bytes', bytes);
/**
* 定义一个对象结构
*
* @param {object} schema 数据结构
* @return {Schema} 返回构建的数据结构
'''<example>'''
* @example objectCreator:array
```js
var _ = jpacks;
var _schema = _.object([_.shortString, _.word]);
console.log(_.stringify(_schema));
// > object([string('uint8'),'uint16'])
var buffer = _.pack(_schema, ['zswang', 1978]);
console.log(buffer.join(' '));
// > 6 122 115 119 97 110 103 186 7
console.log(JSON.stringify(_.unpack(_schema, buffer)));
// > ["zswang",1978]
```
* @example objectCreator:object
```js
var _ = jpacks;
var _schema = _.object({
name: _.shortString,
year: _.word
});
console.log(_.stringify(_schema));
// > object({name:string('uint8'),year:'uint16'})
var buffer = _.pack(_schema, {
name: 'zswang',
year: 1978
});
console.log(buffer.join(' '));
// > 6 122 115 119 97 110 103 186 7
console.log(JSON.stringify(_.unpack(_schema, buffer)));
// > {"name":"zswang","year":1978}
```
* @example objectCreator:null
```js
var _ = jpacks;
var _schema = _.object({
n1: null,
n2: null,
s1: _.int8
});
console.log(_.stringify(_schema));
// > object({n1:null,n2:null,s1:'int8'})
var buffer = _.pack(_schema, {
n1: 1,
n2: 2,
s1: 1
});
console.log(buffer.join(' '));
// > 1
console.log(JSON.stringify(_.unpack(_schema, buffer)));
// > {"n1":null,"n2":null,"s1":1}
```
'''</example>'''
*/
function objectCreator(objectSchema) {
if (objectSchema instanceof Schema) {
return objectSchema;
}
var keys = Object.keys(objectSchema);
return new Schema({
unpack: function _unpack(buffer, options, offsets) {
var result = new objectSchema.constructor();
var $scope = options.$scope;
options.$scope = {
target: result,
offsets: new objectSchema.constructor(),
schema: objectSchema
};
keys.forEach(function(key) {
if (options.$scope.exit) {
result[key] = null;
} else {
options.$scope.offsets[key] = offsets[0];
result[key] = Schema.unpack(objectSchema[key], buffer, options, offsets);
}
});
options.$scope = $scope;
return result;
},
pack: function _pack(value, options, buffer) {
var $scope = options.$scope;
options.$scope = {
target: value,
offsets: new objectSchema.constructor(),
schema: objectSchema
};
keys.every(function(key) {
if (options.$scope.exit) {
return false;
}
options.$scope.offsets[key] = buffer.length;
Schema.pack(objectSchema[key], value[key], options, buffer);
return true;
});
options.$scope = $scope;
},
args: arguments,
namespace: 'object'
});
}
var object = Schema.together(objectCreator, function(fn, args) {
fn.namespace = 'object';
fn.args = args;
});
Schema.register('object', object);
Schema.pushPattern(function _objectPattern(schema) {
if (typeof schema === 'object') {
if (schema instanceof Schema) {
return;
}
if (schema instanceof Array) {
return;
}
return object(schema);
}
});
/**
* 创建联合类型
*
* @param {number} size 联合类型总大小
* @param {Object} schema 联合类型中出现的字段
* @return {Schema} 返回联合类型
'''<example>'''
* @example unionCreator():base
```js
var _ = jpacks;
var _schema = _.union({
length: _.byte,
content: _.shortString
}, 20);
console.log(_.stringify(_schema));
// > union({length:'uint8',content:string('uint8')},20)
var buffer = _.pack(_schema, {
content: '0123456789'
});
console.log(buffer.join(' '));
// > 10 48 49 50 51 52 53 54 55 56 57 0 0 0 0 0 0 0 0 0
console.log(JSON.stringify(_.unpack(_schema, buffer)));
// > {"length":10,"content":"0123456789"}
```
'''</example>'''
*/
function unionCreator(schemas, size) {
var keys = Object.keys(schemas);
return new Schema({
unpack: function _unpack(buffer, options, offsets) {
var beginOffset = offsets[0];
var result = {};
keys.forEach(function (key) {
offsets[0] = beginOffset;
result[key] = Schema.unpack(schemas[key], buffer, options, offsets);
});
offsets[0] += size;
return result;
},
pack: function _pack(value, options, buffer) {
var arrayBuffer = new ArrayBuffer(size);
var uint8Array = new Uint8Array(arrayBuffer);
keys.forEach(function (key) {
if (typeof value[key] === 'undefined') {
return;
}
var temp = [];
Schema.pack(schemas[key], value[key], options, temp);
uint8Array.set(temp);
});
[].push.apply(buffer, uint8Array);
},
size: size,
args: arguments,
namespace: 'union'
});
}
var union = Schema.together(unionCreator, function (fn, args) {
fn.namespace = 'union';
fn.args = args;
});
Schema.register('union', union);
/**
* 定义一个枚举结构
*
* @param {Schema} baseSchema 枚举结构的基础类型
* @param {Array|Object} map 枚举类型字典
* @return {Schema} 返回构建的数据结构
'''<example>'''
* @example enumsCreator():map is array
```js
var _ = jpacks;
var _schema = _.enums(['Sun', 'Mon', 'Tues', 'Wed', 'Thur', 'Fri', 'Sat'], 'uint8');
console.log(_.stringify(_schema));
// > enums({Sun:0,Mon:1,Tues:2,Wed:3,Thur:4,Fri:5,Sat:6},'uint8')
var buffer = _.pack(_schema, 'Tues');
console.log(buffer.join(' '));
// > 2
console.log(JSON.stringify(_.unpack(_schema, buffer)));
// > "Tues"
```
* @example enumsCreator():map is object
```js
var _ = jpacks;
var _schema = _.enums({
Unknown: -1,
Continue: 100,
Processing: 100,
OK: 200,
Created: 201,
NotFound: 404
}, 'int8');
console.log(_.stringify(_schema));
// > enums({Unknown:-1,Continue:100,Processing:100,OK:200,Created:201,NotFound:404},'int8')
var buffer = _.pack(_schema, 'Unknown');
console.log(buffer.join(' '));
// > 255
console.log(JSON.stringify(_.unpack(_schema, buffer)));
// > "Unknown"
```
* @example enumsCreator():fault tolerant
```js
var _ = jpacks;
var _schema = _.enums({
Unknown: -1,
Continue: 100,
Processing: 100,