-
Notifications
You must be signed in to change notification settings - Fork 29.9k
/
buffer.js
1599 lines (1343 loc) Β· 43.3 KB
/
buffer.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
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const {
byteLengthUtf8,
copy: _copy,
compare: _compare,
compareOffset,
createFromString,
fill: _fill,
indexOfBuffer,
indexOfNumber,
indexOfString,
readDoubleBE: _readDoubleBE,
readDoubleLE: _readDoubleLE,
readFloatBE: _readFloatBE,
readFloatLE: _readFloatLE,
swap16: _swap16,
swap32: _swap32,
swap64: _swap64,
writeDoubleBE: _writeDoubleBE,
writeDoubleLE: _writeDoubleLE,
writeFloatBE: _writeFloatBE,
writeFloatLE: _writeFloatLE,
kMaxLength,
kStringMaxLength
} = process.binding('buffer');
const { isAnyArrayBuffer } = process.binding('util');
const {
customInspectSymbol,
normalizeEncoding,
kIsEncodingSymbol
} = require('internal/util');
const {
isArrayBufferView,
isUint8Array
} = require('internal/util/types');
const {
pendingDeprecation
} = process.binding('config');
const errors = require('internal/errors');
const internalBuffer = require('internal/buffer');
const { setupBufferJS } = internalBuffer;
const bindingObj = {};
class FastBuffer extends Uint8Array {
constructor(arg1, arg2, arg3) {
super(arg1, arg2, arg3);
}
}
FastBuffer.prototype.constructor = Buffer;
internalBuffer.FastBuffer = FastBuffer;
Buffer.prototype = FastBuffer.prototype;
const constants = Object.defineProperties({}, {
MAX_LENGTH: {
value: kMaxLength,
writable: false,
enumerable: true
},
MAX_STRING_LENGTH: {
value: kStringMaxLength,
writable: false,
enumerable: true
}
});
Buffer.poolSize = 8 * 1024;
var poolSize, poolOffset, allocPool;
setupBufferJS(Buffer.prototype, bindingObj);
// |zeroFill| can be undefined when running inside an isolate where we
// do not own the ArrayBuffer allocator. Zero fill is always on in that case.
const zeroFill = bindingObj.zeroFill || [0];
function createUnsafeBuffer(size) {
return new FastBuffer(createUnsafeArrayBuffer(size));
}
function createUnsafeArrayBuffer(size) {
zeroFill[0] = 0;
try {
return new ArrayBuffer(size);
} finally {
zeroFill[0] = 1;
}
}
function createPool() {
poolSize = Buffer.poolSize;
allocPool = createUnsafeArrayBuffer(poolSize);
poolOffset = 0;
}
createPool();
function alignPool() {
// Ensure aligned slices
if (poolOffset & 0x7) {
poolOffset |= 0x7;
poolOffset++;
}
}
var bufferWarn = true;
const bufferWarning = 'The Buffer() and new Buffer() constructors are not ' +
'recommended for use due to security and usability ' +
'concerns. Please use the new Buffer.alloc(), ' +
'Buffer.allocUnsafe(), or Buffer.from() construction ' +
'methods instead.';
function showFlaggedDeprecation() {
if (bufferWarn) {
// This is a *pending* deprecation warning. It is not emitted by
// default unless the --pending-deprecation command-line flag is
// used or the NODE_PENDING_DEPRECATION=1 env var is set.
process.emitWarning(bufferWarning, 'DeprecationWarning', 'DEP0005');
bufferWarn = false;
}
}
const doFlaggedDeprecation =
pendingDeprecation ?
showFlaggedDeprecation :
function() {};
/**
* The Buffer() constructor is deprecated in documentation and should not be
* used moving forward. Rather, developers should use one of the three new
* factory APIs: Buffer.from(), Buffer.allocUnsafe() or Buffer.alloc() based on
* their specific needs. There is no runtime deprecation because of the extent
* to which the Buffer constructor is used in the ecosystem currently -- a
* runtime deprecation would introduce too much breakage at this time. It's not
* likely that the Buffer constructors would ever actually be removed.
* Deprecation Code: DEP0005
**/
function Buffer(arg, encodingOrOffset, length) {
doFlaggedDeprecation();
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new errors.TypeError(
'ERR_INVALID_ARG_TYPE', 'string', 'string', arg
);
}
return Buffer.alloc(arg);
}
return Buffer.from(arg, encodingOrOffset, length);
}
Object.defineProperty(Buffer, Symbol.species, {
enumerable: false,
configurable: true,
get() { return FastBuffer; }
});
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function from(value, encodingOrOffset, length) {
if (typeof value === 'string')
return fromString(value, encodingOrOffset);
if (isAnyArrayBuffer(value))
return fromArrayBuffer(value, encodingOrOffset, length);
if (value === null || value === undefined) {
throw new errors.TypeError(
'ERR_INVALID_ARG_TYPE',
'first argument',
['string', 'Buffer', 'ArrayBuffer', 'Array', 'Array-like Object'],
value
);
}
if (typeof value === 'number')
throw new errors.TypeError(
'ERR_INVALID_ARG_TYPE', 'value', 'not number', value
);
const valueOf = value.valueOf && value.valueOf();
if (valueOf !== null && valueOf !== undefined && valueOf !== value)
return Buffer.from(valueOf, encodingOrOffset, length);
var b = fromObject(value);
if (b)
return b;
if (typeof value[Symbol.toPrimitive] === 'function') {
return Buffer.from(value[Symbol.toPrimitive]('string'),
encodingOrOffset,
length);
}
throw new errors.TypeError(
'ERR_INVALID_ARG_TYPE',
'first argument',
['string', 'Buffer', 'ArrayBuffer', 'Array', 'Array-like Object'],
value
);
};
Object.setPrototypeOf(Buffer, Uint8Array);
// The 'assertSize' method will remove itself from the callstack when an error
// occurs. This is done simply to keep the internal details of the
// implementation from bleeding out to users.
function assertSize(size) {
let err = null;
if (typeof size !== 'number') {
err = new errors.TypeError('ERR_INVALID_ARG_TYPE', 'size', 'number', size);
} else if (size < 0) {
err = new errors.RangeError('ERR_INVALID_OPT_VALUE', 'size', size);
} else if (size > kMaxLength) {
err = new errors.RangeError('ERR_INVALID_OPT_VALUE', 'size', size);
}
if (err) {
Error.captureStackTrace(err, assertSize);
throw err;
}
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function alloc(size, fill, encoding) {
assertSize(size);
if (size > 0 && fill !== undefined) {
// Since we are filling anyway, don't zero fill initially.
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpreted as a start offset.
if (typeof encoding !== 'string')
encoding = undefined;
return createUnsafeBuffer(size).fill(fill, encoding);
}
return new FastBuffer(size);
};
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer
* instance. If `--zero-fill-buffers` is set, will zero-fill the buffer.
**/
Buffer.allocUnsafe = function allocUnsafe(size) {
assertSize(size);
return allocate(size);
};
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled
* Buffer instance that is not allocated off the pre-initialized pool.
* If `--zero-fill-buffers` is set, will zero-fill the buffer.
**/
Buffer.allocUnsafeSlow = function allocUnsafeSlow(size) {
assertSize(size);
return createUnsafeBuffer(size);
};
// If --zero-fill-buffers command line argument is set, a zero-filled
// buffer is returned.
function SlowBuffer(length) {
// eslint-disable-next-line eqeqeq
if (+length != length)
length = 0;
assertSize(+length);
return createUnsafeBuffer(+length);
}
Object.setPrototypeOf(SlowBuffer.prototype, Uint8Array.prototype);
Object.setPrototypeOf(SlowBuffer, Uint8Array);
function allocate(size) {
if (size <= 0) {
return new FastBuffer();
}
if (size < (Buffer.poolSize >>> 1)) {
if (size > (poolSize - poolOffset))
createPool();
var b = new FastBuffer(allocPool, poolOffset, size);
poolOffset += size;
alignPool();
return b;
} else {
return createUnsafeBuffer(size);
}
}
function fromString(string, encoding) {
var length;
if (typeof encoding !== 'string' || encoding.length === 0) {
if (string.length === 0)
return new FastBuffer();
encoding = 'utf8';
length = byteLengthUtf8(string);
} else {
length = byteLength(string, encoding, true);
if (length === -1)
throw new errors.TypeError('ERR_UNKNOWN_ENCODING', encoding);
if (string.length === 0)
return new FastBuffer();
}
if (length >= (Buffer.poolSize >>> 1))
return createFromString(string, encoding);
if (length > (poolSize - poolOffset))
createPool();
var b = new FastBuffer(allocPool, poolOffset, length);
const actual = b.write(string, encoding);
if (actual !== length) {
// byteLength() may overestimate. That's a rare case, though.
b = new FastBuffer(allocPool, poolOffset, actual);
}
poolOffset += actual;
alignPool();
return b;
}
function fromArrayLike(obj) {
const length = obj.length;
const b = allocate(length);
for (var i = 0; i < length; i++)
b[i] = obj[i];
return b;
}
function fromArrayBuffer(obj, byteOffset, length) {
// convert byteOffset to integer
if (byteOffset === undefined) {
byteOffset = 0;
} else {
byteOffset = +byteOffset;
// check for NaN
if (byteOffset !== byteOffset)
byteOffset = 0;
}
const maxLength = obj.byteLength - byteOffset;
if (maxLength < 0)
throw new errors.RangeError('ERR_BUFFER_OUT_OF_BOUNDS', 'offset');
if (length === undefined) {
length = maxLength;
} else {
// convert length to non-negative integer
length = +length;
// Check for NaN
if (length !== length) {
length = 0;
} else if (length > 0) {
if (length > maxLength)
throw new errors.RangeError('ERR_BUFFER_OUT_OF_BOUNDS', 'length');
} else {
length = 0;
}
}
return new FastBuffer(obj, byteOffset, length);
}
function fromObject(obj) {
if (isUint8Array(obj)) {
const b = allocate(obj.length);
if (b.length === 0)
return b;
_copy(obj, b, 0, 0, obj.length);
return b;
}
if (obj.length !== undefined || isAnyArrayBuffer(obj.buffer)) {
if (typeof obj.length !== 'number' || obj.length !== obj.length) {
return new FastBuffer();
}
return fromArrayLike(obj);
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data);
}
}
// Static methods
Buffer.isBuffer = function isBuffer(b) {
return b instanceof Buffer;
};
Buffer.compare = function compare(a, b) {
if (!isUint8Array(a) || !isUint8Array(b)) {
throw new errors.TypeError(
'ERR_INVALID_ARG_TYPE', ['buf1', 'buf2'], ['Buffer', 'Uint8Array']
);
}
if (a === b) {
return 0;
}
return _compare(a, b);
};
Buffer.isEncoding = function isEncoding(encoding) {
return typeof encoding === 'string' &&
typeof normalizeEncoding(encoding) === 'string';
};
Buffer[kIsEncodingSymbol] = Buffer.isEncoding;
Buffer.concat = function concat(list, length) {
var i;
if (!Array.isArray(list))
throw new errors.TypeError(
'ERR_INVALID_ARG_TYPE', 'list', ['Array', 'Buffer', 'Uint8Array']
);
if (list.length === 0)
return new FastBuffer();
if (length === undefined) {
length = 0;
for (i = 0; i < list.length; i++)
length += list[i].length;
} else {
length = length >>> 0;
}
var buffer = Buffer.allocUnsafe(length);
var pos = 0;
for (i = 0; i < list.length; i++) {
var buf = list[i];
if (!isUint8Array(buf))
throw new errors.TypeError(
'ERR_INVALID_ARG_TYPE', 'list', ['Array', 'Buffer', 'Uint8Array']
);
_copy(buf, buffer, pos);
pos += buf.length;
}
// Note: `length` is always equal to `buffer.length` at this point
if (pos < length) {
// Zero-fill the remaining bytes if the specified `length` was more than
// the actual total length, i.e. if we have some remaining allocated bytes
// there were not initialized.
buffer.fill(0, pos, length);
}
return buffer;
};
function base64ByteLength(str, bytes) {
// Handle padding
if (str.charCodeAt(bytes - 1) === 0x3D)
bytes--;
if (bytes > 1 && str.charCodeAt(bytes - 1) === 0x3D)
bytes--;
// Base64 ratio: 3/4
return (bytes * 3) >>> 2;
}
function byteLength(string, encoding) {
if (typeof string !== 'string') {
if (isArrayBufferView(string) || isAnyArrayBuffer(string)) {
return string.byteLength;
}
throw new errors.TypeError(
'ERR_INVALID_ARG_TYPE', 'string',
['string', 'Buffer', 'ArrayBuffer'], string
);
}
const len = string.length;
const mustMatch = (arguments.length > 2 && arguments[2] === true);
if (!mustMatch && len === 0)
return 0;
if (!encoding)
return (mustMatch ? -1 : byteLengthUtf8(string));
encoding += '';
switch (encoding.length) {
case 4:
if (encoding === 'utf8') return byteLengthUtf8(string);
if (encoding === 'ucs2') return len * 2;
encoding = encoding.toLowerCase();
if (encoding === 'utf8') return byteLengthUtf8(string);
if (encoding === 'ucs2') return len * 2;
break;
case 5:
if (encoding === 'utf-8') return byteLengthUtf8(string);
if (encoding === 'ascii') return len;
if (encoding === 'ucs-2') return len * 2;
encoding = encoding.toLowerCase();
if (encoding === 'utf-8') return byteLengthUtf8(string);
if (encoding === 'ascii') return len;
if (encoding === 'ucs-2') return len * 2;
break;
case 7:
if (encoding === 'utf16le' || encoding.toLowerCase() === 'utf16le')
return len * 2;
break;
case 8:
if (encoding === 'utf-16le' || encoding.toLowerCase() === 'utf-16le')
return len * 2;
break;
case 6:
if (encoding === 'latin1' || encoding === 'binary') return len;
if (encoding === 'base64') return base64ByteLength(string, len);
encoding = encoding.toLowerCase();
if (encoding === 'latin1' || encoding === 'binary') return len;
if (encoding === 'base64') return base64ByteLength(string, len);
break;
case 3:
if (encoding === 'hex' || encoding.toLowerCase() === 'hex')
return len >>> 1;
break;
}
return (mustMatch ? -1 : byteLengthUtf8(string));
}
Buffer.byteLength = byteLength;
// For backwards compatibility.
Object.defineProperty(Buffer.prototype, 'parent', {
enumerable: true,
get() {
if (!(this instanceof Buffer))
return undefined;
return this.buffer;
}
});
Object.defineProperty(Buffer.prototype, 'offset', {
enumerable: true,
get() {
if (!(this instanceof Buffer))
return undefined;
return this.byteOffset;
}
});
function stringSlice(buf, encoding, start, end) {
if (encoding === undefined) return buf.utf8Slice(start, end);
encoding += '';
switch (encoding.length) {
case 4:
if (encoding === 'utf8') return buf.utf8Slice(start, end);
if (encoding === 'ucs2') return buf.ucs2Slice(start, end);
encoding = encoding.toLowerCase();
if (encoding === 'utf8') return buf.utf8Slice(start, end);
if (encoding === 'ucs2') return buf.ucs2Slice(start, end);
break;
case 5:
if (encoding === 'utf-8') return buf.utf8Slice(start, end);
if (encoding === 'ascii') return buf.asciiSlice(start, end);
if (encoding === 'ucs-2') return buf.ucs2Slice(start, end);
encoding = encoding.toLowerCase();
if (encoding === 'utf-8') return buf.utf8Slice(start, end);
if (encoding === 'ascii') return buf.asciiSlice(start, end);
if (encoding === 'ucs-2') return buf.ucs2Slice(start, end);
break;
case 6:
if (encoding === 'latin1' || encoding === 'binary')
return buf.latin1Slice(start, end);
if (encoding === 'base64') return buf.base64Slice(start, end);
encoding = encoding.toLowerCase();
if (encoding === 'latin1' || encoding === 'binary')
return buf.latin1Slice(start, end);
if (encoding === 'base64') return buf.base64Slice(start, end);
break;
case 3:
if (encoding === 'hex' || encoding.toLowerCase() === 'hex')
return buf.hexSlice(start, end);
break;
case 7:
if (encoding === 'utf16le' || encoding.toLowerCase() === 'utf16le')
return buf.ucs2Slice(start, end);
break;
case 8:
if (encoding === 'utf-16le' || encoding.toLowerCase() === 'utf-16le')
return buf.ucs2Slice(start, end);
break;
}
throw new errors.TypeError('ERR_UNKNOWN_ENCODING', encoding);
}
Buffer.prototype.copy =
function copy(target, targetStart, sourceStart, sourceEnd) {
return _copy(this, target, targetStart, sourceStart, sourceEnd);
};
// No need to verify that "buf.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
Buffer.prototype.toString = function toString(encoding, start, end) {
if (arguments.length === 0) {
return this.utf8Slice(0, this.length);
}
const len = this.length;
if (len === 0)
return '';
if (!start || start < 0)
start = 0;
else if (start >= len)
return '';
if (end === undefined || end > len)
end = len;
else if (end <= 0)
return '';
start |= 0;
end |= 0;
if (end <= start)
return '';
return stringSlice(this, encoding, start, end);
};
Buffer.prototype.equals = function equals(b) {
if (!isUint8Array(b)) {
throw new errors.TypeError(
'ERR_INVALID_ARG_TYPE', 'otherBuffer',
['Buffer', 'Uint8Array'], b
);
}
if (this === b)
return true;
return _compare(this, b) === 0;
};
// Override how buffers are presented by util.inspect().
Buffer.prototype[customInspectSymbol] = function inspect() {
var str = '';
var max = exports.INSPECT_MAX_BYTES;
str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim();
if (this.length > max)
str += ' ... ';
return `<${this.constructor.name} ${str}>`;
};
Buffer.prototype.inspect = Buffer.prototype[customInspectSymbol];
Buffer.prototype.compare = function compare(target,
start,
end,
thisStart,
thisEnd) {
if (!isUint8Array(target)) {
throw new errors.TypeError(
'ERR_INVALID_ARG_TYPE', 'target',
['Buffer', 'Uint8Array'], target
);
}
if (arguments.length === 1)
return _compare(this, target);
if (start === undefined)
start = 0;
else if (start < 0)
throw new errors.RangeError('ERR_INDEX_OUT_OF_RANGE');
else
start >>>= 0;
if (end === undefined)
end = target.length;
else if (end > target.length)
throw new errors.RangeError('ERR_INDEX_OUT_OF_RANGE');
else
end >>>= 0;
if (thisStart === undefined)
thisStart = 0;
else if (thisStart < 0)
throw new errors.RangeError('ERR_INDEX_OUT_OF_RANGE');
else
thisStart >>>= 0;
if (thisEnd === undefined)
thisEnd = this.length;
else if (thisEnd > this.length)
throw new errors.RangeError('ERR_INDEX_OUT_OF_RANGE');
else
thisEnd >>>= 0;
if (thisStart >= thisEnd)
return (start >= end ? 0 : -1);
else if (start >= end)
return 1;
return compareOffset(this, target, start, thisStart, end, thisEnd);
};
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
if (typeof byteOffset === 'string') {
encoding = byteOffset;
byteOffset = undefined;
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff;
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000;
}
// Coerce to Number. Values like null and [] become 0.
byteOffset = +byteOffset;
// If the offset is undefined, "foo", {}, coerces to NaN, search whole buffer.
// `x !== x`-style conditionals are a faster form of `isNaN(x)`
if (byteOffset !== byteOffset) {
byteOffset = dir ? 0 : buffer.length;
}
dir = !!dir; // Cast to bool.
if (typeof val === 'string') {
if (encoding === undefined) {
return indexOfString(buffer, val, byteOffset, encoding, dir);
}
return slowIndexOf(buffer, val, byteOffset, encoding, dir);
} else if (isUint8Array(val)) {
return indexOfBuffer(buffer, val, byteOffset, encoding, dir);
} else if (typeof val === 'number') {
return indexOfNumber(buffer, val, byteOffset, dir);
}
throw new errors.TypeError(
'ERR_INVALID_ARG_TYPE', 'value',
['string', 'Buffer', 'Uint8Array'], val
);
}
function slowIndexOf(buffer, val, byteOffset, encoding, dir) {
var loweredCase = false;
for (;;) {
switch (encoding) {
case 'utf8':
case 'utf-8':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
case 'latin1':
case 'binary':
return indexOfString(buffer, val, byteOffset, encoding, dir);
case 'base64':
case 'ascii':
case 'hex':
return indexOfBuffer(
buffer, Buffer.from(val, encoding), byteOffset, encoding, dir);
default:
if (loweredCase) {
throw new errors.TypeError('ERR_UNKNOWN_ENCODING', encoding);
}
encoding = ('' + encoding).toLowerCase();
loweredCase = true;
}
}
}
Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
};
Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
};
Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1;
};
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill(val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start;
start = 0;
end = this.length;
} else if (typeof end === 'string') {
encoding = end;
end = this.length;
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'encoding',
'string', encoding);
}
var normalizedEncoding = normalizeEncoding(encoding);
if (normalizedEncoding === undefined) {
throw new errors.TypeError('ERR_UNKNOWN_ENCODING', encoding);
}
if (val.length === 0) {
// Previously, if val === '', the Buffer would not fill,
// which is rather surprising.
val = 0;
} else if (val.length === 1) {
var code = val.charCodeAt(0);
if ((normalizedEncoding === 'utf8' && code < 128) ||
normalizedEncoding === 'latin1') {
// Fast path: If `val` fits into a single byte, use that numeric value.
val = code;
}
}
} else if (typeof val === 'number') {
val = val & 255;
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || end > this.length)
throw new errors.RangeError('ERR_INDEX_OUT_OF_RANGE');
if (end <= start)
return this;
start = start >>> 0;
end = end === undefined ? this.length : end >>> 0;
_fill(this, val, start, end, encoding);
return this;
};
Buffer.prototype.write = function write(string, offset, length, encoding) {
// Buffer#write(string);
if (offset === undefined) {
return this.utf8Write(string, 0, this.length);
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset;
length = this.length;
offset = 0;
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0;
if (isFinite(length)) {
length = length >>> 0;
} else {
encoding = length;
length = undefined;
}
var remaining = this.length - offset;
if (length === undefined || length > remaining)
length = remaining;
if (string.length > 0 && (length < 0 || offset < 0))
throw new errors.RangeError('ERR_BUFFER_OUT_OF_BOUNDS', 'length', true);
} else {
// if someone is still calling the obsolete form of write(), tell them.
// we don't want eg buf.write("foo", "utf8", 10) to silently turn into
// buf.write("foo", "utf8"), so we can't ignore extra args
throw new errors.Error(
'ERR_NO_LONGER_SUPPORTED',
'Buffer.write(string, encoding, offset[, length])'
);
}
if (!encoding) return this.utf8Write(string, offset, length);
encoding += '';
switch (encoding.length) {
case 4:
if (encoding === 'utf8') return this.utf8Write(string, offset, length);
if (encoding === 'ucs2') return this.ucs2Write(string, offset, length);
encoding = encoding.toLowerCase();
if (encoding === 'utf8') return this.utf8Write(string, offset, length);
if (encoding === 'ucs2') return this.ucs2Write(string, offset, length);
break;
case 5:
if (encoding === 'utf-8') return this.utf8Write(string, offset, length);
if (encoding === 'ascii') return this.asciiWrite(string, offset, length);
if (encoding === 'ucs-2') return this.ucs2Write(string, offset, length);
encoding = encoding.toLowerCase();
if (encoding === 'utf-8') return this.utf8Write(string, offset, length);
if (encoding === 'ascii') return this.asciiWrite(string, offset, length);
if (encoding === 'ucs-2') return this.ucs2Write(string, offset, length);
break;
case 7:
if (encoding === 'utf16le' || encoding.toLowerCase() === 'utf16le')
return this.ucs2Write(string, offset, length);
break;
case 8:
if (encoding === 'utf-16le' || encoding.toLowerCase() === 'utf-16le')
return this.ucs2Write(string, offset, length);
break;
case 6:
if (encoding === 'latin1' || encoding === 'binary')
return this.latin1Write(string, offset, length);
if (encoding === 'base64')
return this.base64Write(string, offset, length);
encoding = encoding.toLowerCase();
if (encoding === 'latin1' || encoding === 'binary')
return this.latin1Write(string, offset, length);
if (encoding === 'base64')
return this.base64Write(string, offset, length);
break;
case 3:
if (encoding === 'hex' || encoding.toLowerCase() === 'hex')
return this.hexWrite(string, offset, length);
break;
}
throw new errors.TypeError('ERR_UNKNOWN_ENCODING', encoding);
};
Buffer.prototype.toJSON = function toJSON() {
if (this.length > 0) {
const data = new Array(this.length);
for (var i = 0; i < this.length; ++i)
data[i] = this[i];
return { type: 'Buffer', data };
} else {
return { type: 'Buffer', data: [] };
}
};
function adjustOffset(offset, length) {
// Use Math.trunc() to convert offset to an integer value that can be larger
// than an Int32. Hence, don't use offset | 0 or similar techniques.
offset = Math.trunc(offset);
// `x !== x`-style conditionals are a faster form of `isNaN(x)`
if (offset === 0 || offset !== offset) {
return 0;
} else if (offset < 0) {
offset += length;