-
Notifications
You must be signed in to change notification settings - Fork 68
/
ref.js
1480 lines (1317 loc) · 39.1 KB
/
ref.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
'use strict';
const assert = require('assert');
const inspect = require('util').inspect;
const debug = require('debug')('ref');
const os = require('os');
const path = require('path');
exports = module.exports = require('node-gyp-build')(path.join(__dirname, '..'));
exports.endianness = os.endianness();
/**
* A `Buffer` that references the C NULL pointer. That is, its memory address
* points to 0. Its `length` is 0 because accessing any data from this buffer
* would cause a _segmentation fault_.
*
* ```
* console.log(ref.NULL);
* <SlowBuffer@0x0 >
* ```
*
* @name NULL
* @type Buffer
*/
/**
* A string that represents the native endianness of the machine's processor.
* The possible values are either `"LE"` or `"BE"`.
*
* ```
* console.log(ref.endianness);
* 'LE'
* ```
*
* @name endianness
* @type String
*/
/**
* Accepts a `Buffer` instance and returns the memory address of the buffer
* instance. Returns a JavaScript Number, which can't hold 64-bit integers,
* so this function is unsafe on 64-bit systems.
* ```
* console.log(ref.address(new Buffer(1)));
* 4320233616
*
* console.log(ref.address(ref.NULL)));
* 0
* ```
*
* @param {Buffer} buffer The buffer to get the memory address of.
* @return {Number} The memory address the buffer instance.
* @name address
* @type method
*/
/**
* Accepts a `Buffer` instance and returns _true_ if the buffer represents the
* NULL pointer, _false_ otherwise.
*
* ```
* console.log(ref.isNull(new Buffer(1)));
* false
*
* console.log(ref.isNull(ref.NULL));
* true
* ```
*
* @param {Buffer} buffer The buffer to check for NULL.
* @return {Boolean} true or false.
* @name isNull
* @type method
*/
/**
* Reads a JavaScript Object that has previously been written to the given
* _buffer_ at the given _offset_.
*
* ```
* var obj = { foo: 'bar' };
* var buf = ref.alloc('Object', obj);
*
* var obj2 = ref.readObject(buf, 0);
* console.log(obj === obj2);
* true
* ```
*
* @param {Buffer} buffer The buffer to read an Object from.
* @param {Number} offset The offset to begin reading from.
* @return {Object} The Object that was read from _buffer_.
* @name readObject
* @type method
*/
/**
* Reads a Buffer instance from the given _buffer_ at the given _offset_.
* The _size_ parameter specifies the `length` of the returned Buffer instance,
* which defaults to __0__.
*
* ```
* var buf = new Buffer('hello world');
* var pointer = ref.alloc('pointer', buf);
*
* var buf2 = ref.readPointer(pointer, 0, buf.length);
* console.log(buf2.toString());
* 'hello world'
* ```
*
* @param {Buffer} buffer The buffer to read a Buffer from.
* @param {Number} offset The offset to begin reading from.
* @param {Number} length (optional) The length of the returned Buffer. Defaults to 0.
* @return {Buffer} The Buffer instance that was read from _buffer_.
* @name readPointer
* @type method
*/
/**
* Returns a JavaScript String read from _buffer_ at the given _offset_. The
* C String is read until the first NULL byte, which indicates the end of the
* String.
*
* This function can read beyond the `length` of a Buffer.
*
* ```
* var buf = new Buffer('hello\0world\0');
*
* var str = ref.readCString(buf, 0);
* console.log(str);
* 'hello'
* ```
*
* @param {Buffer} buffer The buffer to read a Buffer from.
* @param {Number} offset The offset to begin reading from.
* @return {String} The String that was read from _buffer_.
* @name readCString
* @type method
*/
/**
* Returns a big-endian signed 64-bit int read from _buffer_ at the given
* _offset_.
*
* If the returned value will fit inside a JavaScript Number without losing
* precision, then a Number is returned, otherwise a String is returned.
*
* ```
* var buf = ref.alloc('int64');
* ref.writeInt64BE(buf, 0, '9223372036854775807');
*
* var val = ref.readInt64BE(buf, 0)
* console.log(val)
* '9223372036854775807'
* ```
*
* @param {Buffer} buffer The buffer to read a Buffer from.
* @param {Number} offset The offset to begin reading from.
* @return {Number|String} The Number or String that was read from _buffer_.
* @name readInt64BE
* @type method
*/
/**
* Returns a little-endian signed 64-bit int read from _buffer_ at the given
* _offset_.
*
* If the returned value will fit inside a JavaScript Number without losing
* precision, then a Number is returned, otherwise a String is returned.
*
* ```
* var buf = ref.alloc('int64');
* ref.writeInt64LE(buf, 0, '9223372036854775807');
*
* var val = ref.readInt64LE(buf, 0)
* console.log(val)
* '9223372036854775807'
* ```
*
* @param {Buffer} buffer The buffer to read a Buffer from.
* @param {Number} offset The offset to begin reading from.
* @return {Number|String} The Number or String that was read from _buffer_.
* @name readInt64LE
* @type method
*/
/**
* Returns a big-endian unsigned 64-bit int read from _buffer_ at the given
* _offset_.
*
* If the returned value will fit inside a JavaScript Number without losing
* precision, then a Number is returned, otherwise a String is returned.
*
* ```
* var buf = ref.alloc('uint64');
* ref.writeUInt64BE(buf, 0, '18446744073709551615');
*
* var val = ref.readUInt64BE(buf, 0)
* console.log(val)
* '18446744073709551615'
* ```
*
* @param {Buffer} buffer The buffer to read a Buffer from.
* @param {Number} offset The offset to begin reading from.
* @return {Number|String} The Number or String that was read from _buffer_.
* @name readUInt64BE
* @type method
*/
/**
* Returns a little-endian unsigned 64-bit int read from _buffer_ at the given
* _offset_.
*
* If the returned value will fit inside a JavaScript Number without losing
* precision, then a Number is returned, otherwise a String is returned.
*
* ```
* var buf = ref.alloc('uint64');
* ref.writeUInt64LE(buf, 0, '18446744073709551615');
*
* var val = ref.readUInt64LE(buf, 0)
* console.log(val)
* '18446744073709551615'
* ```
*
* @param {Buffer} buffer The buffer to read a Buffer from.
* @param {Number} offset The offset to begin reading from.
* @return {Number|String} The Number or String that was read from _buffer_.
* @name readUInt64LE
* @type method
*/
/**
* Writes the _input_ Number or String as a big-endian signed 64-bit int into
* _buffer_ at the given _offset_.
*
* ```
* var buf = ref.alloc('int64');
* ref.writeInt64BE(buf, 0, '9223372036854775807');
* ```
*
* @param {Buffer} buffer The buffer to write to.
* @param {Number} offset The offset to begin writing from.
* @param {Number|String} input This String or Number which gets written.
* @name writeInt64BE
* @type method
*/
/**
* Writes the _input_ Number or String as a little-endian signed 64-bit int into
* _buffer_ at the given _offset_.
*
* ```
* var buf = ref.alloc('int64');
* ref.writeInt64LE(buf, 0, '9223372036854775807');
* ```
*
* @param {Buffer} buffer The buffer to write to.
* @param {Number} offset The offset to begin writing from.
* @param {Number|String} input This String or Number which gets written.
* @name writeInt64LE
* @type method
*/
/**
* Writes the _input_ Number or String as a big-endian unsigned 64-bit int into
* _buffer_ at the given _offset_.
*
* ```
* var buf = ref.alloc('uint64');
* ref.writeUInt64BE(buf, 0, '18446744073709551615');
* ```
*
* @param {Buffer} buffer The buffer to write to.
* @param {Number} offset The offset to begin writing from.
* @param {Number|String} input This String or Number which gets written.
* @name writeUInt64BE
* @type method
*/
/**
* Writes the _input_ Number or String as a little-endian unsigned 64-bit int
* into _buffer_ at the given _offset_.
*
* ```
* var buf = ref.alloc('uint64');
* ref.writeUInt64LE(buf, 0, '18446744073709551615');
* ```
*
* @param {Buffer} buffer The buffer to write to.
* @param {Number} offset The offset to begin writing from.
* @param {Number|String} input This String or Number which gets written.
* @name writeUInt64LE
* @type method
*/
/**
* Returns a new clone of the given "type" object, with its
* `indirection` level incremented by **1**.
*
* Say you wanted to create a type representing a `void *`:
*
* ```
* var voidPtrType = ref.refType(ref.types.void);
* ```
*
* @param {Object|String} type The "type" object to create a reference type from. Strings get coerced first.
* @return {Object} The new "type" object with its `indirection` incremented by 1.
*/
exports.refType = function refType (type) {
const _type = exports.coerceType(type);
const rtn = Object.create(_type);
rtn.indirection++;
if (_type.name) {
Object.defineProperty(rtn, 'name', {
value: _type.name + '*',
configurable: true,
enumerable: true,
writable: true
});
}
return rtn;
}
/**
* Returns a new clone of the given "type" object, with its
* `indirection` level decremented by 1.
*
* @param {Object|String} type The "type" object to create a dereference type from. Strings get coerced first.
* @return {Object} The new "type" object with its `indirection` decremented by 1.
*/
exports.derefType = function derefType (type) {
const _type = exports.coerceType(type);
if (_type.indirection === 1) {
throw new Error('Cannot create deref\'d type for type with indirection 1');
}
let rtn = Object.getPrototypeOf(_type);
if (rtn.indirection !== _type.indirection - 1) {
// slow case
rtn = Object.create(_type);
rtn.indirection--;
}
return rtn;
}
/**
* Coerces a "type" object from a String or an actual "type" object. String values
* are looked up from the `ref.types` Object. So:
*
* * `"int"` gets coerced into `ref.types.int`.
* * `"int *"` gets translated into `ref.refType(ref.types.int)`
* * `ref.types.int` gets translated into `ref.types.int` (returns itself)
*
* Throws an Error if no valid "type" object could be determined. Most `ref`
* functions use this function under the hood, so anywhere a "type" object is
* expected, a String may be passed as well, including simply setting the
* `buffer.type` property.
*
* ```
* var type = ref.coerceType('int **');
*
* console.log(type.indirection);
* 3
* ```
*
* @param {Object|String} type The "type" Object or String to coerce.
* @return {Object} A "type" object
*/
exports.coerceType = function coerceType (type) {
let rtn = type;
if (typeof rtn === 'string') {
rtn = exports.types[type];
if (rtn) return rtn;
// strip whitespace
rtn = type.replace(/\s+/g, '').toLowerCase();
if (rtn === 'pointer') {
// legacy "pointer" being used :(
rtn = exports.refType(exports.types.void); // void *
} else if (rtn === 'string') {
rtn = exports.types.CString; // special char * type
} else {
var refCount = 0;
rtn = rtn.replace(/\*/g, function() {
refCount++;
return '';
});
// allow string names to be passed in
rtn = exports.types[rtn];
if (refCount > 0) {
if (!(rtn && 'size' in rtn && 'indirection' in rtn)) {
throw new TypeError('could not determine a proper "type" from: ' + inspect(type));
}
for (let i = 0; i < refCount; i++) {
rtn = exports.refType(rtn);
}
}
}
}
if (!(rtn && 'size' in rtn && 'indirection' in rtn)) {
throw new TypeError('could not determine a proper "type" from: ' + inspect(type));
}
return rtn;
}
/**
* Returns the "type" property of the given Buffer.
* Creates a default type for the buffer when none exists.
*
* @param {Buffer} buffer The Buffer instance to get the "type" object from.
* @return {Object} The "type" object from the given Buffer.
*/
exports.getType = function getType (buffer) {
if (!buffer.type) {
debug('WARN: no "type" found on buffer, setting default "type"', buffer);
buffer.type = {};
buffer.type.size = buffer.length;
buffer.type.indirection = 1;
buffer.type.get = function get () {
throw new Error('unknown "type"; cannot get()');
};
buffer.type.set = function set () {
throw new Error('unknown "type"; cannot set()');
};
}
return exports.coerceType(buffer.type);
}
/**
* Calls the `get()` function of the Buffer's current "type" (or the
* passed in _type_ if present) at the given _offset_.
*
* This function handles checking the "indirection" level and returning a
* proper "dereferenced" Bufffer instance when necessary.
*
* @param {Buffer} buffer The Buffer instance to read from.
* @param {Number} offset (optional) The offset on the Buffer to start reading from. Defaults to 0.
* @param {Object|String} type (optional) The "type" object to use when reading. Defaults to calling `getType()` on the buffer.
* @return {?} Whatever value the "type" used when reading returns.
*/
exports.get = function get (buffer, offset, type) {
if (!offset) {
offset = 0;
}
if (type) {
type = exports.coerceType(type);
} else {
type = exports.getType(buffer);
}
debug('get(): (offset: %d)', offset, buffer);
assert(type.indirection > 0, `"indirection" level must be at least 1, saw ${type.indirection}`);
if (type.indirection === 1) {
// need to check "type"
return type.get(buffer, offset);
} else {
// need to create a deref'd Buffer
const size = type.indirection === 2 ? type.size : exports.sizeof.pointer;
const reference = exports.readPointer(buffer, offset, size);
reference.type = exports.derefType(type);
return reference;
}
}
/**
* Calls the `set()` function of the Buffer's current "type" (or the
* passed in _type_ if present) at the given _offset_.
*
* This function handles checking the "indirection" level writing a pointer rather
* than calling the `set()` function if the indirection is greater than 1.
*
* @param {Buffer} buffer The Buffer instance to write to.
* @param {Number} offset The offset on the Buffer to start writing to.
* @param {?} value The value to write to the Buffer instance.
* @param {Object|String} type (optional) The "type" object to use when reading. Defaults to calling `getType()` on the buffer.
*/
exports.set = function set (buffer, offset, value, type) {
if (!offset) {
offset = 0;
}
if (type) {
type = exports.coerceType(type);
} else {
type = exports.getType(buffer);
}
debug('set(): (offset: %d)', offset, buffer, value);
assert(type.indirection >= 1, '"indirection" level must be at least 1');
if (type.indirection === 1) {
type.set(buffer, offset, value);
} else {
exports.writePointer(buffer, offset, value);
}
}
/**
* Returns a new Buffer instance big enough to hold `type`,
* with the given `value` written to it.
*
* ``` js
* var intBuf = ref.alloc(ref.types.int)
* var int_with_4 = ref.alloc(ref.types.int, 4)
* ```
*
* @param {Object|String} type The "type" object to allocate. Strings get coerced first.
* @param {?} value (optional) The initial value set on the returned Buffer, using _type_'s `set()` function.
* @return {Buffer} A new Buffer instance with it's `type` set to "type", and (optionally) "value" written to it.
*/
exports.alloc = function alloc (_type, value) {
var type = exports.coerceType(_type);
debug('allocating Buffer for type with "size"', type.size);
let size;
if (type.indirection === 1) {
size = type.size;
} else {
size = exports.sizeof.pointer;
}
const buffer = Buffer.alloc(size);
buffer.type = type;
if (arguments.length >= 2) {
debug('setting value on allocated buffer', value);
exports.set(buffer, 0, value, type);
}
return buffer;
}
/**
* Returns a new `Buffer` instance with the given String written to it with the
* given encoding (defaults to __'utf8'__). The buffer is 1 byte longer than the
* string itself, and is NUL terminated.
*
* ```
* var buf = ref.allocCString('hello world');
*
* console.log(buf.toString());
* 'hello world\u0000'
* ```
*
* @param {String} string The JavaScript string to be converted to a C string.
* @param {String} encoding (optional) The encoding to use for the C string. Defaults to __'utf8'__.
* @return {Buffer} The new `Buffer` instance with the specified String wrtten to it, and a trailing NUL byte.
*/
exports.allocCString = function allocCString (string, encoding) {
if (null == string || (Buffer.isBuffer(string) && exports.isNull(string))) {
return exports.NULL;
}
const size = Buffer.byteLength(string, encoding) + 1;
const buffer = Buffer.allocUnsafe(size);
exports.writeCString(buffer, 0, string, encoding);
buffer.type = charPtrType;
return buffer;
}
/**
* Writes the given string as a C String (NULL terminated) to the given buffer
* at the given offset. "encoding" is optional and defaults to __'utf8'__.
*
* Unlike `readCString()`, this function requires the buffer to actually have the
* proper length.
*
* @param {Buffer} buffer The Buffer instance to write to.
* @param {Number} offset The offset of the buffer to begin writing at.
* @param {String} string The JavaScript String to write that will be written to the buffer.
* @param {String} encoding (optional) The encoding to read the C string as. Defaults to __'utf8'__.
*/
exports.writeCString = function writeCString (buffer, offset, string, encoding) {
assert(Buffer.isBuffer(buffer), 'expected a Buffer as the first argument');
assert.strictEqual('string', typeof string, 'expected a "string" as the third argument');
if (!offset) {
offset = 0;
}
if (!encoding) {
encoding = 'utf8';
}
const size = buffer.length - offset - 1;
const len = buffer.write(string, offset, size, encoding);
buffer.writeUInt8(0, offset + len); // NUL terminate
}
exports['readInt64' + exports.endianness] = exports.readInt64;
exports['readUInt64' + exports.endianness] = exports.readUInt64;
exports['writeInt64' + exports.endianness] = exports.writeInt64;
exports['writeUInt64' + exports.endianness] = exports.writeUInt64;
var opposite = exports.endianness == 'LE' ? 'BE' : 'LE';
var int64temp = Buffer.alloc(exports.sizeof.int64);
var uint64temp = Buffer.alloc(exports.sizeof.uint64);
exports['readInt64' + opposite] = function (buffer, offset) {
for (let i = 0; i < exports.sizeof.int64; i++) {
int64temp[i] = buffer[offset + exports.sizeof.int64 - i - 1];
}
return exports.readInt64(int64temp, 0);
}
exports['readUInt64' + opposite] = function (buffer, offset) {
for (let i = 0; i < exports.sizeof.uint64; i++) {
uint64temp[i] = buffer[offset + exports.sizeof.uint64 - i - 1];
}
return exports.readUInt64(uint64temp, 0);
}
exports['writeInt64' + opposite] = function (buffer, offset, value) {
exports.writeInt64(int64temp, 0, value);
for (let i = 0; i < exports.sizeof.int64; i++) {
buffer[offset + i] = int64temp[exports.sizeof.int64 - i - 1];
}
}
exports['writeUInt64' + opposite] = function (buffer, offset, value) {
exports.writeUInt64(uint64temp, 0, value);
for (let i = 0; i < exports.sizeof.uint64; i++) {
buffer[offset + i] = uint64temp[exports.sizeof.uint64 - i - 1];
}
}
/**
* `ref()` accepts a Buffer instance and returns a new Buffer
* instance that is "pointer" sized and has its data pointing to the given
* Buffer instance. Essentially the created Buffer is a "reference" to the
* original pointer, equivalent to the following C code:
*
* ``` c
* char *buf = buffer;
* char **ref = &buf;
* ```
*
* @param {Buffer} buffer A Buffer instance to create a reference to.
* @return {Buffer} A new Buffer instance pointing to _buffer_.
*/
exports.ref = function ref (buffer) {
debug('creating a reference to buffer', buffer);
var type = exports.refType(exports.getType(buffer));
return exports.alloc(type, buffer);
}
/**
* Accepts a Buffer instance and attempts to "dereference" it.
* That is, first it checks the `indirection` count of _buffer_'s "type", and if
* it's greater than __1__ then it merely returns another Buffer, but with one
* level less `indirection`.
*
* When _buffer_'s indirection is at __1__, then it checks for `buffer.type`
* which should be an Object with its own `get()` function.
*
* ```
* var buf = ref.alloc('int', 6);
*
* var val = ref.deref(buf);
* console.log(val);
* 6
* ```
*
*
* @param {Buffer} buffer A Buffer instance to dereference.
* @return {?} The returned value after dereferencing _buffer_.
*/
exports.deref = function deref (buffer) {
debug('dereferencing buffer', buffer);
return exports.get(buffer);
}
const kAttachedRefs = Symbol('attached');
/**
* Attaches _object_ to _buffer_ such that it prevents _object_ from being garbage
* collected until _buffer_ does.
*
* @param {Buffer} buffer A Buffer instance to attach _object_ to.
* @param {Object|Buffer} object An Object or Buffer to prevent from being garbage collected until _buffer_ does.
* @api private
*/
exports._attach = function _attach (buf, obj) {
if (!buf[kAttachedRefs]) {
buf[kAttachedRefs] = [];
}
buf[kAttachedRefs].push(obj);
}
/**
* @param {Buffer} buffer
* @param {Number} offset
* @param {Object} object
* @name _writeObject
* @api private
*/
/**
* Writes a pointer to _object_ into _buffer_ at the specified _offset.
*
* This function "attaches" _object_ to _buffer_ to prevent it from being garbage
* collected.
*
* ```
* var buf = ref.alloc('Object');
* ref.writeObject(buf, 0, { foo: 'bar' });
*
* ```
*
* @param {Buffer} buffer A Buffer instance to write _object_ to.
* @param {Number} offset The offset on the Buffer to start writing at.
* @param {Object} object The Object to be written into _buffer_.
*/
exports.writeObject = function writeObject (buf, offset, obj) {
debug('writing Object to buffer', buf, offset, obj);
exports._writeObject(buf, offset, obj);
exports._attach(buf, obj);
}
/**
* Same as `ref.writePointer()`, except that this version does not attach
* _pointer_ to _buffer_, which is potentially unsafe if the garbage collector
* runs.
*
* @param {Buffer} buffer A Buffer instance to write _pointer to.
* @param {Number} offset The offset on the Buffer to start writing at.
* @param {Buffer} pointer The Buffer instance whose memory address will be written to _buffer_.
* @name _writePointer
* @api private
*/
/**
* Writes the memory address of _pointer_ to _buffer_ at the specified _offset_.
*
* This function "attaches" _object_ to _buffer_ to prevent it from being garbage
* collected.
*
* ```
* var someBuffer = new Buffer('whatever');
* var buf = ref.alloc('pointer');
* ref.writePointer(buf, 0, someBuffer);
* ```
*
* @param {Buffer} buffer A Buffer instance to write _pointer to.
* @param {Number} offset The offset on the Buffer to start writing at.
* @param {Buffer} pointer The Buffer instance whose memory address will be written to _buffer_.
*/
exports.writePointer = function writePointer (buf, offset, ptr) {
debug('writing pointer to buffer', buf, offset, ptr);
// Passing true as a fourth parameter does an a stronger
// version of attach which ensures ptr is only collected after
// the finalizer for buf has run. See
// https://github.com/node-ffi-napi/ref-napi/issues/54
// for why this is necessary
exports._writePointer(buf, offset, ptr, true);
};
/**
* Same as `ref.reinterpret()`, except that this version does not attach
* _buffer_ to the returned Buffer, which is potentially unsafe if the
* garbage collector runs.
*
* @param {Buffer} buffer A Buffer instance to base the returned Buffer off of.
* @param {Number} size The `length` property of the returned Buffer.
* @param {Number} offset The offset of the Buffer to begin from.
* @return {Buffer} A new Buffer instance with the same memory address as _buffer_, and the requested _size_.
* @name _reinterpret
* @api private
*/
/**
* Returns a new Buffer instance with the specified _size_, with the same memory
* address as _buffer_.
*
* This function "attaches" _buffer_ to the returned Buffer to prevent it from
* being garbage collected.
*
* @param {Buffer} buffer A Buffer instance to base the returned Buffer off of.
* @param {Number} size The `length` property of the returned Buffer.
* @param {Number} offset The offset of the Buffer to begin from.
* @return {Buffer} A new Buffer instance with the same memory address as _buffer_, and the requested _size_.
*/
exports.reinterpret = function reinterpret (buffer, size, offset) {
debug('reinterpreting buffer to "%d" bytes', size);
const rtn = exports._reinterpret(buffer, size, offset || 0);
exports._attach(rtn, buffer);
return rtn;
}
/**
* Same as `ref.reinterpretUntilZeros()`, except that this version does not
* attach _buffer_ to the returned Buffer, which is potentially unsafe if the
* garbage collector runs.
*
* @param {Buffer} buffer A Buffer instance to base the returned Buffer off of.
* @param {Number} size The number of sequential, aligned `NULL` bytes that are required to terminate the buffer.
* @param {Number} offset The offset of the Buffer to begin from.
* @return {Buffer} A new Buffer instance with the same memory address as _buffer_, and a variable `length` that is terminated by _size_ NUL bytes.
* @name _reinterpretUntilZeros
* @api private
*/
/**
* Accepts a `Buffer` instance and a number of `NULL` bytes to read from the
* pointer. This function will scan past the boundary of the Buffer's `length`
* until it finds `size` number of aligned `NULL` bytes.
*
* This is useful for finding the end of NUL-termintated array or C string. For
* example, the `readCString()` function _could_ be implemented like:
*
* ```
* function readCString (buf) {
* return ref.reinterpretUntilZeros(buf, 1).toString('utf8')
* }
* ```
*
* This function "attaches" _buffer_ to the returned Buffer to prevent it from
* being garbage collected.
*
* @param {Buffer} buffer A Buffer instance to base the returned Buffer off of.
* @param {Number} size The number of sequential, aligned `NULL` bytes are required to terminate the buffer.
* @param {Number} offset The offset of the Buffer to begin from.
* @return {Buffer} A new Buffer instance with the same memory address as _buffer_, and a variable `length` that is terminated by _size_ NUL bytes.
*/
exports.reinterpretUntilZeros = function reinterpretUntilZeros (buffer, size, offset) {
debug('reinterpreting buffer to until "%d" NULL (0) bytes are found', size);
var rtn = exports._reinterpretUntilZeros(buffer, size, offset || 0);
exports._attach(rtn, buffer);
return rtn;
};
// the built-in "types"
const types = exports.types = {};
/**
* The `void` type.
*
* @section types
*/
types.void = {
size: 0,
indirection: 1,
get: function get (buf, offset) {
debug('getting `void` type (returns `null`)');
return null;
},
set: function set (buf, offset, val) {
debug('setting `void` type (no-op)');
}
};
/**
* The `int8` type.
*/
types.int8 = {
size: exports.sizeof.int8,
indirection: 1,
get: function get (buf, offset) {
return buf.readInt8(offset || 0);
},
set: function set (buf, offset, val) {
if (typeof val === 'string') {
val = val.charCodeAt(0);
}
return buf.writeInt8(val, offset || 0);
}
};
/**
* The `uint8` type.
*/
types.uint8 = {
size: exports.sizeof.uint8,
indirection: 1,
get: function get (buf, offset) {
return buf.readUInt8(offset || 0);
},
set: function set (buf, offset, val) {
if (typeof val === 'string') {
val = val.charCodeAt(0);
}
return buf.writeUInt8(val, offset || 0);
}
};
/**
* The `int16` type.
*/
types.int16 = {
size: exports.sizeof.int16,
indirection: 1,
get: function get (buf, offset) {
return buf['readInt16' + exports.endianness](offset || 0);
},
set: function set (buf, offset, val) {
return buf['writeInt16' + exports.endianness](val, offset || 0);
}
}
/**
* The `uint16` type.
*/
types.uint16 = {
size: exports.sizeof.uint16,
indirection: 1,
get: function get (buf, offset) {
return buf['readUInt16' + exports.endianness](offset || 0);
},
set: function set (buf, offset, val) {
return buf['writeUInt16' + exports.endianness](val, offset || 0);
}
}
/**
* The `int32` type.
*/
types.int32 = {
size: exports.sizeof.int32,
indirection: 1,
get: function get (buf, offset) {
return buf['readInt32' + exports.endianness](offset || 0);
},
set: function set (buf, offset, val) {
return buf['writeInt32' + exports.endianness](val, offset || 0);
}
}
/**
* The `uint32` type.
*/
types.uint32 = {
size: exports.sizeof.uint32,
indirection: 1,
get: function get (buf, offset) {
return buf['readUInt32' + exports.endianness](offset || 0);
},
set: function set (buf, offset, val) {
return buf['writeUInt32' + exports.endianness](val, offset || 0);
}
}
/**
* The `int64` type.
*/
types.int64 = {
size: exports.sizeof.int64,
indirection: 1,
get: function get (buf, offset) {
return buf['readInt64' + exports.endianness](offset || 0);
},
set: function set (buf, offset, val) {
return buf['writeInt64' + exports.endianness](val, offset || 0);
}
}
/**
* The `uint64` type.
*/
types.uint64 = {
size: exports.sizeof.uint64,
indirection: 1,
get: function get (buf, offset) {
return buf['readUInt64' + exports.endianness](offset || 0);
},
set: function set (buf, offset, val) {
return buf['writeUInt64' + exports.endianness](val, offset || 0);
}
}
/**
* The `float` type.
*/
types.float = {
size: exports.sizeof.float,
indirection: 1,
get: function get (buf, offset) {
return buf['readFloat' + exports.endianness](offset || 0);
},
set: function set (buf, offset, val) {
return buf['writeFloat' + exports.endianness](val, offset || 0);
}
}
/**
* The `double` type.
*/
types.double = {