3 const binding = process.binding('buffer');
4 const smalloc = process.binding('smalloc');
5 const util = require('util');
6 const alloc = smalloc.alloc;
7 const truncate = smalloc.truncate;
8 const sliceOnto = smalloc.sliceOnto;
9 const kMaxLength = smalloc.kMaxLength;
11 exports.Buffer = Buffer;
12 exports.SlowBuffer = SlowBuffer;
13 exports.INSPECT_MAX_BYTES = 50;
16 Buffer.poolSize = 8 * 1024;
17 var poolSize, poolOffset, allocPool;
20 function createPool() {
21 poolSize = Buffer.poolSize;
22 allocPool = alloc({}, poolSize);
28 function Buffer(subject, encoding) {
29 if (!(this instanceof Buffer))
30 return new Buffer(subject, encoding);
32 if (typeof subject === 'number') {
33 this.length = +subject;
35 } else if (typeof subject === 'string') {
36 if (typeof encoding !== 'string' || encoding.length === 0)
38 this.length = Buffer.byteLength(subject, encoding);
40 // Handle Arrays, Buffers, Uint8Arrays or JSON.
41 } else if (subject !== null && typeof subject === 'object') {
42 if (subject.type === 'Buffer' && Array.isArray(subject.data))
43 subject = subject.data;
44 this.length = +subject.length;
47 throw new TypeError('must start with number, buffer, array or string');
50 if (this.length > kMaxLength) {
51 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
52 'size: 0x' + kMaxLength.toString(16) + ' bytes');
58 this.length >>>= 0; // Coerce to uint32.
60 this.parent = undefined;
61 if (this.length <= (Buffer.poolSize >>> 1) && this.length > 0) {
62 if (this.length > poolSize - poolOffset)
64 this.parent = sliceOnto(allocPool,
67 poolOffset + this.length);
68 poolOffset += this.length;
70 alloc(this, this.length);
73 if (typeof subject === 'number') {
77 if (typeof subject === 'string') {
78 // In the case of base64 it's possible that the size of the buffer
79 // allocated was slightly too large. In this case we need to rewrite
80 // the length to the actual length written.
81 var len = this.write(subject, encoding);
82 // Buffer was truncated after decode, realloc internal ExternalArray
83 if (len !== this.length) {
84 var prevLen = this.length;
86 truncate(this, this.length);
87 // Only need to readjust the poolOffset if the allocation is a slice.
88 if (this.parent != undefined)
89 poolOffset -= (prevLen - len);
92 } else if (subject instanceof Buffer) {
93 subject.copy(this, 0, 0, this.length);
95 } else if (typeof subject.length === 'number' || Array.isArray(subject)) {
96 // Really crappy way to handle Uint8Arrays, but V8 doesn't give a simple
97 // way to access the data from the C++ API.
98 for (var i = 0; i < this.length; i++)
104 function SlowBuffer(length) {
105 length = length >>> 0;
106 if (length > kMaxLength) {
107 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
108 'size: 0x' + kMaxLength.toString(16) + ' bytes');
110 var b = new NativeBuffer(length);
116 // Bypass all checks for instantiating unallocated Buffer required for
117 // Objects created in C++. Significantly faster than calling the Buffer
119 function NativeBuffer(length) {
120 this.length = length >>> 0;
121 // Set this to keep the object map the same.
122 this.parent = undefined;
124 NativeBuffer.prototype = Buffer.prototype;
127 // add methods to Buffer prototype
128 binding.setupBufferJS(NativeBuffer);
133 Buffer.isBuffer = function isBuffer(b) {
134 return b instanceof Buffer;
138 Buffer.compare = function compare(a, b) {
139 if (!(a instanceof Buffer) ||
140 !(b instanceof Buffer))
141 throw new TypeError('Arguments must be Buffers');
146 return binding.compare(a, b);
150 Buffer.isEncoding = function(encoding) {
151 switch ((encoding + '').toLowerCase()) {
171 Buffer.concat = function(list, length) {
172 if (!Array.isArray(list))
173 throw new TypeError('Usage: Buffer.concat(list[, length])');
175 if (length === undefined) {
177 for (var i = 0; i < list.length; i++)
178 length += list[i].length;
180 length = length >>> 0;
183 if (list.length === 0)
184 return new Buffer(0);
185 else if (list.length === 1)
188 var buffer = new Buffer(length);
190 for (var i = 0; i < list.length; i++) {
192 buf.copy(buffer, pos);
200 Buffer.byteLength = function(str, enc) {
213 ret = str.length * 2;
216 ret = str.length >>> 1;
219 ret = binding.byteLength(str, enc);
225 // toString(encoding, start=0, end=buffer.length)
226 Buffer.prototype.toString = function(encoding, start, end) {
227 var loweredCase = false;
230 end = end === undefined || end === Infinity ? this.length : end >>> 0;
232 if (!encoding) encoding = 'utf8';
233 if (start < 0) start = 0;
234 if (end > this.length) end = this.length;
235 if (end <= start) return '';
240 return this.hexSlice(start, end);
244 return this.utf8Slice(start, end);
247 return this.asciiSlice(start, end);
250 return this.binarySlice(start, end);
253 return this.base64Slice(start, end);
259 return this.ucs2Slice(start, end);
263 throw new TypeError('Unknown encoding: ' + encoding);
264 encoding = (encoding + '').toLowerCase();
271 Buffer.prototype.equals = function equals(b) {
272 if (!(b instanceof Buffer))
273 throw new TypeError('Argument must be a Buffer');
278 return binding.compare(this, b) === 0;
283 Buffer.prototype.inspect = function inspect() {
285 var max = exports.INSPECT_MAX_BYTES;
286 if (this.length > 0) {
287 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
288 if (this.length > max)
291 return '<' + this.constructor.name + ' ' + str + '>';
295 Buffer.prototype.compare = function compare(b) {
296 if (!(b instanceof Buffer))
297 throw new TypeError('Argument must be a Buffer');
302 return binding.compare(this, b);
306 Buffer.prototype.indexOf = function indexOf(val, byteOffset) {
307 if (byteOffset > 0x7fffffff)
308 byteOffset = 0x7fffffff;
309 else if (byteOffset < -0x80000000)
310 byteOffset = -0x80000000;
313 if (typeof val === 'string')
314 return binding.indexOfString(this, val, byteOffset);
315 if (val instanceof Buffer)
316 return binding.indexOfBuffer(this, val, byteOffset);
317 if (typeof val === 'number')
318 return binding.indexOfNumber(this, val, byteOffset);
320 throw new TypeError('val must be string, number or Buffer');
324 Buffer.prototype.fill = function fill(val, start, end) {
326 end = (end === undefined) ? this.length : end >> 0;
328 if (start < 0 || end > this.length)
329 throw new RangeError('out of range index');
333 if (typeof val !== 'string') {
335 } else if (val.length === 1) {
336 var code = val.charCodeAt(0);
341 binding.fill(this, val, start, end);
347 // XXX remove in v0.13
348 Buffer.prototype.get = util.deprecate(function get(offset) {
350 if (offset < 0 || offset >= this.length)
351 throw new RangeError('index out of range');
353 }, '.get() is deprecated. Access using array indexes instead.');
356 // XXX remove in v0.13
357 Buffer.prototype.set = util.deprecate(function set(offset, v) {
359 if (offset < 0 || offset >= this.length)
360 throw new RangeError('index out of range');
361 return this[offset] = v;
362 }, '.set() is deprecated. Set using array indexes instead.');
365 // TODO(trevnorris): fix these checks to follow new standard
366 // write(string, offset = 0, length = buffer.length, encoding = 'utf8')
367 var writeWarned = false;
368 const writeMsg = '.write(string, encoding, offset, length) is deprecated.' +
369 ' Use write(string[, offset[, length]][, encoding]) instead.';
370 Buffer.prototype.write = function(string, offset, length, encoding) {
371 // Buffer#write(string);
372 if (offset === undefined) {
374 length = this.length;
377 // Buffer#write(string, encoding)
378 } else if (length === undefined && typeof offset === 'string') {
380 length = this.length;
383 // Buffer#write(string, offset[, length][, encoding])
384 } else if (isFinite(offset)) {
385 offset = offset >>> 0;
386 if (isFinite(length)) {
387 length = length >>> 0;
388 if (encoding === undefined)
395 // XXX legacy write(string, encoding, offset, length) - remove in v0.13
398 if (process.throwDeprecation)
399 throw new Error(writeMsg);
400 else if (process.traceDeprecation)
401 console.trace(writeMsg);
403 console.error(writeMsg);
409 offset = length >>> 0;
413 var remaining = this.length - offset;
414 if (length === undefined || length > remaining)
417 encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
419 if (string.length > 0 && (length < 0 || offset < 0))
420 throw new RangeError('attempt to write outside buffer bounds');
425 ret = this.hexWrite(string, offset, length);
430 ret = this.utf8Write(string, offset, length);
434 ret = this.asciiWrite(string, offset, length);
438 ret = this.binaryWrite(string, offset, length);
442 // Warning: maxLength not taken into account in base64Write
443 ret = this.base64Write(string, offset, length);
450 ret = this.ucs2Write(string, offset, length);
454 throw new TypeError('Unknown encoding: ' + encoding);
461 Buffer.prototype.toJSON = function() {
464 data: Array.prototype.slice.call(this, 0)
469 // TODO(trevnorris): currently works like Array.prototype.slice(), which
470 // doesn't follow the new standard for throwing on out of range indexes.
471 Buffer.prototype.slice = function(start, end) {
472 var len = this.length;
474 end = end === undefined ? len : ~~end;
480 } else if (start > len) {
488 } else if (end > len) {
495 var buf = new NativeBuffer();
496 sliceOnto(this, buf, start, end);
497 buf.length = end - start;
499 buf.parent = this.parent === undefined ? this : this.parent;
505 function checkOffset(offset, ext, length) {
506 if (offset + ext > length)
507 throw new RangeError('index out of range');
511 Buffer.prototype.readUIntLE = function(offset, byteLength, noAssert) {
512 offset = offset >>> 0;
513 byteLength = byteLength >>> 0;
515 checkOffset(offset, byteLength, this.length);
517 var val = this[offset];
520 while (++i < byteLength && (mul *= 0x100))
521 val += this[offset + i] * mul;
527 Buffer.prototype.readUIntBE = function(offset, byteLength, noAssert) {
528 offset = offset >>> 0;
529 byteLength = byteLength >>> 0;
531 checkOffset(offset, byteLength, this.length);
533 var val = this[offset + --byteLength];
535 while (byteLength > 0 && (mul *= 0x100))
536 val += this[offset + --byteLength] * mul;
542 Buffer.prototype.readUInt8 = function(offset, noAssert) {
543 offset = offset >>> 0;
545 checkOffset(offset, 1, this.length);
550 Buffer.prototype.readUInt16LE = function(offset, noAssert) {
551 offset = offset >>> 0;
553 checkOffset(offset, 2, this.length);
554 return this[offset] | (this[offset + 1] << 8);
558 Buffer.prototype.readUInt16BE = function(offset, noAssert) {
559 offset = offset >>> 0;
561 checkOffset(offset, 2, this.length);
562 return (this[offset] << 8) | this[offset + 1];
566 Buffer.prototype.readUInt32LE = function(offset, noAssert) {
567 offset = offset >>> 0;
569 checkOffset(offset, 4, this.length);
571 return ((this[offset]) |
572 (this[offset + 1] << 8) |
573 (this[offset + 2] << 16)) +
574 (this[offset + 3] * 0x1000000);
578 Buffer.prototype.readUInt32BE = function(offset, noAssert) {
579 offset = offset >>> 0;
581 checkOffset(offset, 4, this.length);
583 return (this[offset] * 0x1000000) +
584 ((this[offset + 1] << 16) |
585 (this[offset + 2] << 8) |
590 Buffer.prototype.readIntLE = function(offset, byteLength, noAssert) {
591 offset = offset >>> 0;
592 byteLength = byteLength >>> 0;
594 checkOffset(offset, byteLength, this.length);
596 var val = this[offset];
599 while (++i < byteLength && (mul *= 0x100))
600 val += this[offset + i] * mul;
604 val -= Math.pow(2, 8 * byteLength);
610 Buffer.prototype.readIntBE = function(offset, byteLength, noAssert) {
611 offset = offset >>> 0;
612 byteLength = byteLength >>> 0;
614 checkOffset(offset, byteLength, this.length);
618 var val = this[offset + --i];
619 while (i > 0 && (mul *= 0x100))
620 val += this[offset + --i] * mul;
624 val -= Math.pow(2, 8 * byteLength);
630 Buffer.prototype.readInt8 = function(offset, noAssert) {
631 offset = offset >>> 0;
633 checkOffset(offset, 1, this.length);
634 var val = this[offset];
635 return !(val & 0x80) ? val : (0xff - val + 1) * -1;
639 Buffer.prototype.readInt16LE = function(offset, noAssert) {
640 offset = offset >>> 0;
642 checkOffset(offset, 2, this.length);
643 var val = this[offset] | (this[offset + 1] << 8);
644 return (val & 0x8000) ? val | 0xFFFF0000 : val;
648 Buffer.prototype.readInt16BE = function(offset, noAssert) {
649 offset = offset >>> 0;
651 checkOffset(offset, 2, this.length);
652 var val = this[offset + 1] | (this[offset] << 8);
653 return (val & 0x8000) ? val | 0xFFFF0000 : val;
657 Buffer.prototype.readInt32LE = function(offset, noAssert) {
658 offset = offset >>> 0;
660 checkOffset(offset, 4, this.length);
662 return (this[offset]) |
663 (this[offset + 1] << 8) |
664 (this[offset + 2] << 16) |
665 (this[offset + 3] << 24);
669 Buffer.prototype.readInt32BE = function(offset, noAssert) {
670 offset = offset >>> 0;
672 checkOffset(offset, 4, this.length);
674 return (this[offset] << 24) |
675 (this[offset + 1] << 16) |
676 (this[offset + 2] << 8) |
681 Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
682 offset = offset >>> 0;
684 checkOffset(offset, 4, this.length);
685 return binding.readFloatLE(this, offset);
689 Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
690 offset = offset >>> 0;
692 checkOffset(offset, 4, this.length);
693 return binding.readFloatBE(this, offset);
697 Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
698 offset = offset >>> 0;
700 checkOffset(offset, 8, this.length);
701 return binding.readDoubleLE(this, offset);
705 Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
706 offset = offset >>> 0;
708 checkOffset(offset, 8, this.length);
709 return binding.readDoubleBE(this, offset);
713 function checkInt(buffer, value, offset, ext, max, min) {
714 if (!(buffer instanceof Buffer))
715 throw new TypeError('buffer must be a Buffer instance');
716 if (value > max || value < min)
717 throw new TypeError('value is out of bounds');
718 if (offset + ext > buffer.length)
719 throw new RangeError('index out of range');
723 Buffer.prototype.writeUIntLE = function(value, offset, byteLength, noAssert) {
725 offset = offset >>> 0;
726 byteLength = byteLength >>> 0;
728 checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0);
732 this[offset] = value;
733 while (++i < byteLength && (mul *= 0x100))
734 this[offset + i] = (value / mul) >>> 0;
736 return offset + byteLength;
740 Buffer.prototype.writeUIntBE = function(value, offset, byteLength, noAssert) {
742 offset = offset >>> 0;
743 byteLength = byteLength >>> 0;
745 checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0);
747 var i = byteLength - 1;
749 this[offset + i] = value;
750 while (--i >= 0 && (mul *= 0x100))
751 this[offset + i] = (value / mul) >>> 0;
753 return offset + byteLength;
757 Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
759 offset = offset >>> 0;
761 checkInt(this, value, offset, 1, 0xff, 0);
762 this[offset] = value;
767 Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
769 offset = offset >>> 0;
771 checkInt(this, value, offset, 2, 0xffff, 0);
772 this[offset] = value;
773 this[offset + 1] = (value >>> 8);
778 Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
780 offset = offset >>> 0;
782 checkInt(this, value, offset, 2, 0xffff, 0);
783 this[offset] = (value >>> 8);
784 this[offset + 1] = value;
789 Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
791 offset = offset >>> 0;
793 checkInt(this, value, offset, 4, 0xffffffff, 0);
794 this[offset + 3] = (value >>> 24);
795 this[offset + 2] = (value >>> 16);
796 this[offset + 1] = (value >>> 8);
797 this[offset] = value;
802 Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
804 offset = offset >>> 0;
806 checkInt(this, value, offset, 4, 0xffffffff, 0);
807 this[offset] = (value >>> 24);
808 this[offset + 1] = (value >>> 16);
809 this[offset + 2] = (value >>> 8);
810 this[offset + 3] = value;
815 Buffer.prototype.writeIntLE = function(value, offset, byteLength, noAssert) {
817 offset = offset >>> 0;
823 Math.pow(2, 8 * byteLength - 1) - 1,
824 -Math.pow(2, 8 * byteLength - 1));
829 var sub = value < 0 ? 1 : 0;
830 this[offset] = value;
831 while (++i < byteLength && (mul *= 0x100))
832 this[offset + i] = ((value / mul) >> 0) - sub;
834 return offset + byteLength;
838 Buffer.prototype.writeIntBE = function(value, offset, byteLength, noAssert) {
840 offset = offset >>> 0;
846 Math.pow(2, 8 * byteLength - 1) - 1,
847 -Math.pow(2, 8 * byteLength - 1));
850 var i = byteLength - 1;
852 var sub = value < 0 ? 1 : 0;
853 this[offset + i] = value;
854 while (--i >= 0 && (mul *= 0x100))
855 this[offset + i] = ((value / mul) >> 0) - sub;
857 return offset + byteLength;
861 Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
863 offset = offset >>> 0;
865 checkInt(this, value, offset, 1, 0x7f, -0x80);
866 this[offset] = value;
871 Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
873 offset = offset >>> 0;
875 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
876 this[offset] = value;
877 this[offset + 1] = (value >>> 8);
882 Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
884 offset = offset >>> 0;
886 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
887 this[offset] = (value >>> 8);
888 this[offset + 1] = value;
893 Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
895 offset = offset >>> 0;
897 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
898 this[offset] = value;
899 this[offset + 1] = (value >>> 8);
900 this[offset + 2] = (value >>> 16);
901 this[offset + 3] = (value >>> 24);
906 Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
908 offset = offset >>> 0;
910 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
911 this[offset] = (value >>> 24);
912 this[offset + 1] = (value >>> 16);
913 this[offset + 2] = (value >>> 8);
914 this[offset + 3] = value;
919 function checkFloat(buffer, value, offset, ext) {
920 if (!(buffer instanceof Buffer))
921 throw new TypeError('buffer must be a Buffer instance');
922 if (offset + ext > buffer.length)
923 throw new RangeError('index out of range');
927 Buffer.prototype.writeFloatLE = function writeFloatLE(val, offset, noAssert) {
929 offset = offset >>> 0;
931 checkFloat(this, val, offset, 4);
932 binding.writeFloatLE(this, val, offset);
937 Buffer.prototype.writeFloatBE = function writeFloatBE(val, offset, noAssert) {
939 offset = offset >>> 0;
941 checkFloat(this, val, offset, 4);
942 binding.writeFloatBE(this, val, offset);
947 Buffer.prototype.writeDoubleLE = function writeDoubleLE(val, offset, noAssert) {
949 offset = offset >>> 0;
951 checkFloat(this, val, offset, 8);
952 binding.writeDoubleLE(this, val, offset);
957 Buffer.prototype.writeDoubleBE = function writeDoubleBE(val, offset, noAssert) {
959 offset = offset >>> 0;
961 checkFloat(this, val, offset, 8);
962 binding.writeDoubleBE(this, val, offset);
968 var ITERATOR_KIND_KEYS = 1;
969 var ITERATOR_KIND_ENTRIES = 3;
971 function BufferIteratorResult(value, done) {
976 var resultCache = new Array(256);
978 for (var i = 0; i < 256; i++)
979 resultCache[i] = Object.freeze(new BufferIteratorResult(i, false));
981 var finalResult = Object.freeze(new BufferIteratorResult(undefined, true));
983 function BufferIterator(buffer, kind) {
984 this._buffer = buffer;
989 BufferIterator.prototype.next = function() {
990 var buffer = this._buffer;
991 var kind = this._kind;
992 var index = this._index;
994 if (index >= buffer.length)
999 if (kind === ITERATOR_KIND_ENTRIES)
1000 return new BufferIteratorResult([index, buffer[index]], false);
1002 return new BufferIteratorResult(index, false);
1005 function BufferValueIterator(buffer) {
1006 BufferIterator.call(this, buffer, null);
1009 BufferValueIterator.prototype.next = function() {
1010 var buffer = this._buffer;
1011 var index = this._index;
1013 if (index >= buffer.length)
1018 return resultCache[buffer[index]];
1022 BufferIterator.prototype[Symbol.iterator] = function() {
1026 BufferValueIterator.prototype[Symbol.iterator] =
1027 BufferIterator.prototype[Symbol.iterator];
1029 Buffer.prototype.keys = function() {
1030 return new BufferIterator(this, ITERATOR_KIND_KEYS);
1033 Buffer.prototype.entries = function() {
1034 return new BufferIterator(this, ITERATOR_KIND_ENTRIES);
1037 Buffer.prototype.values = function() {
1038 return new BufferValueIterator(this);
1041 Buffer.prototype[Symbol.iterator] = Buffer.prototype.values;