-
Notifications
You must be signed in to change notification settings - Fork 0
/
datatypes.js
executable file
·618 lines (555 loc) · 20.6 KB
/
datatypes.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
//
// datatypes-js
// Byte encoder and decoder for typical datatypes implemented in Javascript.
//
// Read readme.txt for instructions and LICENSE license.
//
// Copyright (c) 2009 Johan Dahlberg
//
var datatypes = {};
try{ datatypes = exports } catch(e) {}; // Try to export the lib for node.js
(function(self) {
// Name for special classes that datatypes-js recognise. An objects class can be
// determind by reading the _dtclass property.
var OPTION = 'option',
DATATYPE = 'datatype',
STRUCT = 'struct',
POINTER = 'pointer';
// Special data sizes.
var FLEX_DATASIZE = -2;
var DEFINED_DATASIZE = -1;
// Collections of datatypes and other constants.
var DATATYPES = {},
CONSTANTS = {}
// Converts ´´arguments´´ into an array.
function get_array(args) {
return Array.prototype.slice.call(args);
}
// Defines a new datatype with specified options.
//
// datasize - The size of the datatype. Valid values are positive integers
// or one of the following constants:
//
// FLEX_DATASIZE
// The decoder decides when to stop read from buffer
//
// DEFINED_DATASIZE
// The size is user defined.
//
// "choice" - Optional. This indicates that the following two callbacks are
// encoder/decoder chooser's rather than a real encoder/decoder. A
// chooser callback is called takes one argument, the option set,
// and should return the encoder/decoder based on that.
//
// encoder - The encoder to use for the datatype. The encoder is a callback
// that takes one argument. The encoder should always return an
// array with bytes.
//
// function(value) {
// var result = tobytes(value) // Encode value to bytes.
// return result;
// }
//
// decoder - The decoder to use for the datatype. The decoder is a callback
// that takes two arguments. The first argument is a Buffer Pointer.
//
// The second argument is the byte buffer to read from.
//
// The third argument is the size of the datatype. This argument
// will always contain the fixed datasize, for datatypes with
// with specified size. The value will be undefined if the
// datasize is declared as DATASIZE_CUSTOM. The argument has a
// variable value if the datasize is declared as DATASIZE_DEFINE.
//
// function(buffer, bp, length) {
// var result = 0;
// while(!bp.eof()) result += buffer(bp.next());
// return result;
// }
//
function define() {
var args = get_array(arguments);
return {
_dtclass: DATATYPE,
size: args.shift(),
choose_callback: args[0] == 'choice' ? args.shift() == 'choice' : false,
encoder: args.shift(),
decoder: args.shift()
}
}
// Helper fucntion for the struct constructor. Returns a new constant field.
function const_field(dt, value, name, opts) {
var encoder = dt.choose_callback ? dt.encoder(null, opts) : dt.encoder,
decoder = dt.choose_callback ? dt.decoder(null, null, null, opts) : dt.decoder;
var decode, bytes = encoder(value, opts);
var encode = function(values) {
return bytes;
}
if(opts.no_error_check) {
decode = function(buffer, pt) {
pt.pos += bytes.length;
}
} else {
decode = function(buffer, pt) {
var result = decoder(buffer, pt, dt.size, opts);
if(result != value) throw 'Decoding error: Struct[' + name + '] constant value does not match';
return result;
}
}
return {
name: name,
constant: true,
encode: encode,
decode: decode
}
}
// Helper fucntion for the struct constructor. Returns a new dynamic field.
var DYNAMIC = { _dtstruct: 'custom_field', callback: function(dt, args, opts) {
var name = args.shift();
var encoder = dt.choose_callback ? dt.encoder(null, opts) : dt.encoder,
decoder = dt.choose_callback ? dt.decoder(null, null, null, opts) : dt.decoder;
var decode = function(buffer, pt) {
var result = decoder(buffer, pt, dt.size, opts);
return result;
}
return {
name: name,
constant: false,
encode: encoder,
decode: decode,
}
}};
// Adds the struct size (in bytes) to the buffer after encoding
var STRUCT_SIZE = { _dtstruct: 'custom_field', callback: function(dt, args, opts) {
if(dt != DATATYPES['int16'] && dt != DATATYPES['int32'] && dt != DATATYPES['byte']) {
throw 'STRUCT_SIZE only supports int16, int32 and byte.';
}
var encoder = dt.choose_callback ? dt.encoder(null, opts) : dt.encoder,
decoder = dt.choose_callback ? dt.decoder(null, null, null, opts) : dt.decoder;
// We are building a temporary buffer spot for this value,
var encode = function(value, opts) {
return encoder(0, opts)
}
var decode = function(buffer, pt) {
var result = decoder(buffer, pt, dt.size, opts);
return result;
}
var after = function(buffer, pos) {
// Calculate the total number of bytes in the generated buffer and
// encode it to bytes. Then replace the
var bytes = encoder(buffer.length, opts);
var l = bytes.length;
for(var i = 0; i<l; i++) buffer[pos + i] = bytes[i];
return buffer;
}
return {
name: 'size',
constant: true,
after_encoding: after,
encode: encode,
decode: decode,
}
}};
// Defines a new data structure. A datastructure is a set of datatypes, with
// a compiled call sequence to encoders and decoders.
function struct() {
var args = get_array(arguments);
var first, second, options = {}, fields = [];
while(args.length) {
first = args.shift();
switch(first._dtclass) {
case OPTION:
first.callback(options, 'struct');
break;
case DATATYPE:
case STRUCT:
second = args.shift();
if(second._dtstruct == 'custom_field') {
fields.push(second.callback(first, args, options));
} else {
fields.push(const_field(first, second, '_index' + fields.length, options));
}
break;
default:
throw "Unexpected value at " + fields.length;
}
}
function datastruct() {
var args = get_array(arguments);
return args.length == 1 && args[0].constructor != Array ?
datastruct.from_dict(args[0]) :
datastruct.from_array(args);
}
datastruct.from_array = function(values) {
var result = [], l = fields.length, after_callbacks = [];
for(var i = 0; i < l; i++) {
var field = fields[i];
var value = field.constant ? null : values.shift();
var current_size = result.length;
result = result.concat(field.encode(value));
if(field.after_encoding) {
after_callbacks.push({ field: field, pos: current_size});
}
}
if(after_callbacks.length) {
var old_result = result.slice(0);
result = [];
for(var i=0; i<after_callbacks.length; i++) {
var o = after_callbacks[i];
result = result.concat(o.field.after_encoding(old_result, o.pos));
}
}
return result;
}
datastruct.from_dict = function(values) {
var result = [], l = fields.length, after_callbacks = [];
for(var i = 0; i < l; i++) {
var field = fields[i];
var value = values[field.name];
var current_size = result.length;
result = result.concat(field.encode(value));
if(field.after_encoding) {
after_callbacks.push({ field: field, pos: current_size});
}
}
if(after_callbacks.length) {
var old_result = result.slice(0);
result = [];
for(var i=0; i<after_callbacks.length; i++) {
var o = after_callbacks[i];
result = result.concat(o.field.after_encoding(old_result, o.pos));
}
}
return result;
}
datastruct.to_array = function(buffer, pt) {
var pt = pt || new BufferPointer(0, buffer.length),
result = [],l = fields.length;
for(var i = 0; i < l; i++) {
result.push(fields[i].decode(buffer, pt));
}
return result;
}
datastruct.to_dict = function(buffer, pt) {
var pt = pt || new BufferPointer(0, buffer.length),
result = {}, field, l = fields.length;
for(var i = 0; i < l; i++) {
field = fields[i];
result[field.name] = field.decode(buffer, pt);
}
return result;
}
return datastruct;
}
// Defines a new option. An option can give user-defined instructions while
// encoding and decoding datatypes. The option function takes one callback
// function.
//
// The callback function takes two arguments. The first argument is an option
// set, used by current encoder/decoder. The second argument is a String that
// represents the current mode. There is three modes: ´´encode´´, ´´decode´´ and
// ´´struct´´. THe option parser can choose to handle the request differently
// based on which mode.
//
// function(options, mode) {
// options.my_option = 1234
// }
//
// Each datatype encoder and decoder function get's the generated option set.
//
// Built-in datatype's encoder's/decoder's ignores this option set.
//
function option(callback) {
return {
_dtclass: OPTION,
callback: callback
}
}
// Define's the BIG_ENDIAN option. This option sets the buffer byte-order to
// big-endian.
var BIG_ENDIAN = option( function(opts) { opts.little_endian = false } );
// Define's the LITTLE_ENDIAN option. This option sets the buffer byte-order to
// little-endian.
var LITTLE_ENDIAN = option( function(opts) { opts.little_endian = true } );
// Define's the NO_ERROR_CHECK option. This options is only valid on STRUCTS.
// This option will ignore to read all constant fields. The fields will not
// be matched against the original value. This option makes reading faster but
// less accurate.
var NO_ERROR_CHECK = option(
function(opts, mode) {
if(mode == 'struct') opts.no_error_check = true;
}
);
// Define's the DICT option. This option tell's the decoder to return a dict
// with the decoded values.
var DICT = option(
function(opts, mode) {
if(mode == 'decode') opts.array_result = false;
}
);
// Define's the ARRAY option. This option tell's the decoder to return an array
// with decoded values.
var ARRAY = option(
function(opts, mode) {
if(mode == 'decode') opts.array_result = true;
}
);
// Initializes a new BufferPoint instance.
function BufferPointer(pos, buffer_length) {
this.pos = pos;
this.length = buffer_length;
}
BufferPointer.prototype = {
_dtclass: POINTER,
eof: function() { return !(this.pos < this.length) },
next: function() { return this.pos++ },
}
// Define built-in encoders. An encoder takes two arguments: value and
// (optional) options. The value argument represents the Javascript object. The
// option argument is optional and contains a dict with user-defined options.
// It's possible to create new option handles by calling the option
// function.
//
// All built-in encoders can be accessd through the ENCODERS member in the
// exported module.
var ENCODERS = {
// Encodes bytes. If the v argument is a number, then the number is wrapped
// within an array. If not, the v argument is asumed to be an array with bytes.
bytes: function(v) {
return v.constructor === Number ? [v] : v;
},
// Returns an int16 encoder based on the bigendian option
get_int16: function(v, opts) {
return opts.little_endian ? ENCODERS.int16l : ENCODERS.int16;
},
// Encodes an Int16 into big-endian format.
int16: function(v) {
return [(v >> 8) & 0xff, (v & 0xff)];
},
// Encodes an Int16 into little-endian format.
int16l: function(v) {
return [(v & 0xff), (v >> 8) & 0xff];
},
// Returns an int32 encoder based on the bigendian option
get_int32: function(v, opts) {
return opts.little_endian ? ENCODERS.int32l : ENCODERS.int32;
},
// Encodes an Int32 into big-endian format.
int32: function(v) {
return [ (v >> 24) & 0xff, (v >> 16) & 0xff, (v >> 8) & 0xff, (v & 0xff) ];
},
// Encodes an Int32 into little-endian format.
int32l: function (v) {
return [ (v & 0xff), (v >> 8) & 0xff, (v >> 16) & 0xff, (v >> 24) & 0xff ];
},
// Encodes an 8-bit char-string.
string8: function(v) {
var result = [], l = v.length;
for(var i = 0; i < l; i++) result.push(v.charCodeAt(i));
return result;
},
// Encodes an 8-bit char null-terminated string.
cstring: function(v) {
return ENCODERS.string8(v).concat([0]);
}
}
// Define built-in decoders. A decoder is a callback for specified dataype. The
// callback takes three arguments: buffer, pointer and length.
//
// buffer - The buffer is an Array with 1 or more bytes.
// pointer - A BufferPointer instance. The instance points to the buffer
// position to read from.
// length - The total length of the datatype. This argument SHOULD be
// ignored by Datatypes with a fixed size.
// options - OPTIONAL. A dict with user-defined options.
//
// All built-in decoders can be accessd through the ENCODERS member in the
// exported module.
var DECODERS = {
// Decodes an byte array.
bytes: function(buffer, pointer, length) {
if(length == 1) return buffer[pointer.pos++];
var pos = pointer.pos;
pointer.pos += length;
return buffer.slice(pos, length);
},
// Returns an int16 decoder based on the bigendian option
get_int16: function(b, pt, l, opts) {
return opts.little_endian ? DECODERS.int16l : DECODERS.int16;
},
// Decodes an Int16 in big-endian format.
int16: function(b, pt) {
return (b[pt.pos++] << 8) | (b[pt.pos++]);
},
// Decodes an Int16 in little-endian format.
int16l: function(b, pt) {
return (b[pt.pos++]) | (b[pt.pos++] << 8);
},
// Returns an int32 decoder based on the bigendian option
get_int32: function(b, pt, l, opts) {
return opts.little_endian ? DECODERS.int32l : DECODERS.int32;
},
// Decodes an Int32 in big-endian format.
int32: function(b, pt) {
return (b[pt.pos++] << 24) | (b[pt.pos++] << 16) | (b[pt.pos++] << 8) | (b[pt.pos++]);
},
// Decodes an Int32 in little-endian format.
int32l: function(b, pt) {
return (b[pt.pos++]) | (b[pt.pos++] << 8) | (b[pt.pos++] << 16) | (b[pt.pos++] << 24);
},
// Decodes an 8-bit char-string.
string8: function(b, pt, l) {
var result = [], i = index, bl = b.length, v;
while(pt.pos < l && pt.pos < bl) {
result.push(String.fromCharCode(v));
pt.pos++;
}
return result.join('');
},
// Decodes an 8-bit char null-terminated string.
cstring: function(b, pt) {
var result = [], bl = b.length, v;
while(pt.pos < bl && (v = b[pt.pos++]) != 0) {
result.push(String.fromCharCode(v));
}
return result.join('');
}
}
// Encodes Javascript objects into a byte-array.
function encode() {
var args = get_array(arguments), result = [], options = { };
while(args.length > 0) {
var first = args.shift(), second, encoder;
switch(first._dtclass) {
case OPTION:
first.callback(options, 'encode');
break;
case DATATYPE:
second = args.shift();
encoder = first.choose_callback ?
first.encoder(second, options) :
first.encoder;
result = result.concat(encoder(second, options));
break;
case STRUCT:
result = result.concat(first(second.shift()));
break;
default:
throw "Expected datatype, struct or option: " + first._dtclass;
break;
}
}
return result;
}
// Decodes a set of bytes into a javascript object.
function decode_dt(dt, buffer, pt, length, opts) {
var decoder = dt.choose_callback ?
dt.decoder(buffer, pt, length, opts) :
dt.decoder;
return decoder(buffer, pt, length, opts);
}
// Decodes an byte-array into Javascript objects.
function decode() {
var args = get_array(arguments), result = {}, options = {};
var buffer = args.shift(), pt = new BufferPointer(0, buffer.length);
while(args.length > 0) {
var first = args.shift(), second, field, decoder, dtresult;
switch(first._dtclass) {
case POINTER:
pt = first;
continue;
case OPTION:
var array_result = options.array_result;
first.callback(options, 'decode');
if(options.array_result != array_result) {
result = options.array_result ? [] : {};
}
continue;
case STRUCT:
dtresult = options.array_result ?
first.to_array(buffer, pt) :
first.to_dict(buffer, pt);
break;
case DATATYPE:
default:
if(args[0] !== undefined && args[0].size == DEFINED_DATASIZE) {
// Expect a number representing the size
// of the datatype
if(first._dtclass == DATATYPE) {
// Parse size from member
first = decode_dt(first, buffer, pt, length, options);
}
second = args.shift();
dtresult = decode_dt(second, buffer, pt, first, options);
} else {
dtresult = decode_dt(first, buffer, pt, first.size, options);
}
break;
}
if(options.array_result) {
result.push(dtresult);
} else {
field = args.shift();
if(field.constructor !== String) throw "Expected named field";
result[field] = dtresult;
}
}
return result;
}
// Predefined datatype definitions
var defs = [
['byte' , 1],
['bytes' , DEFINED_DATASIZE],
['int16' , 2, 'choice'],
['int32' , 4, 'choice'],
['string8' , DEFINED_DATASIZE],
['cstring' , FLEX_DATASIZE]
];
// Contants and members that should be exported to the public.
var constants = [
['FLEX_DATASIZE', FLEX_DATASIZE], ['DEFINED_DATASIZE', DEFINED_DATASIZE],
['DATATYPES', DATATYPES], ['CONSTANTS', CONSTANTS],
['BIG_ENDIAN', BIG_ENDIAN], ['LITTLE_ENDIAN', LITTLE_ENDIAN],
['ARRAY', ARRAY], ['DICT', DICT], ['ENCODERS', ENCODERS],
['DECODERS', DECODERS], ['dynamic', DYNAMIC], ['struct_size', STRUCT_SIZE],
['NO_ERROR_CHECK', NO_ERROR_CHECK]
];
// Export constants and objects to the public scope.
(function() {
var dtindex = defs.length, cindex = constants.length;
while(dtindex-- > 0) {
var type = defs[dtindex];
var name = type[0];
var uname = name;
var size = type[1];
var prefix = '';
var ctor_args = [size];
if(type[2] == 'choice') {
prefix = 'get_';
ctor_args.push('choice');
}
ctor_args.push(ENCODERS[prefix + name]);
ctor_args.push(DECODERS[prefix + name]);
DATATYPES[uname] = self[uname] = define.apply(null, ctor_args);
}
while(cindex-- > 0) {
var name = constants[cindex][0];
var val = constants[cindex][1];
CONSTANTS[name] = self[name] = val;
}
})();
// Exports all constants such as datatypes and options to the provided scope.
(function(to) {
for(var name in DATATYPES) to[name] = DATATYPES[name];
for(var name in CONSTANTS) to[name] = CONSTANTS[name];
})(self);
// Export functions
self.define = define;
self.option = option;
self.encode = encode;
self.decode = decode;
self.struct = struct;
self.BufferPointer = BufferPointer;
self.DATATYPES = DATATYPES;
self.CONSTANTS = CONSTANTS;
})(datatypes);