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);
27 function Buffer(arg) {
28 if (!(this instanceof Buffer)) {
29 // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
30 if (arguments.length > 1)
31 return new Buffer(arg, arguments[1]);
33 return new Buffer(arg);
37 this.parent = undefined;
40 if (typeof(arg) === 'number') {
41 fromNumber(this, arg);
45 // Slightly less common case.
46 if (typeof(arg) === 'string') {
47 fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8');
52 fromObject(this, arg);
55 function fromNumber(that, length) {
56 allocate(that, length < 0 ? 0 : checked(length) | 0);
59 function fromString(that, string, encoding) {
60 if (typeof(encoding) !== 'string' || encoding === '')
63 // Assumption: byteLength() return value is always < kMaxLength.
64 var length = byteLength(string, encoding) | 0;
65 allocate(that, length);
67 var actual = that.write(string, encoding) | 0;
68 if (actual !== length) {
69 // Fix up for truncated base64 input. Don't bother returning
70 // the unused two or three bytes to the pool.
72 truncate(that, actual);
76 function fromObject(that, object) {
77 if (object instanceof Buffer)
78 return fromBuffer(that, object);
80 if (Array.isArray(object))
81 return fromArray(that, object);
84 throw new TypeError('must start with number, buffer, array or string');
86 if (object.buffer instanceof ArrayBuffer)
87 return fromTypedArray(that, object);
90 return fromArrayLike(that, object);
92 return fromJsonObject(that, object);
95 function fromBuffer(that, buffer) {
96 var length = checked(buffer.length) | 0;
97 allocate(that, length);
98 buffer.copy(that, 0, 0, length);
101 function fromArray(that, array) {
102 var length = checked(array.length) | 0;
103 allocate(that, length);
104 for (var i = 0; i < length; i += 1)
105 that[i] = array[i] & 255;
108 // Duplicate of fromArray() to keep fromArray() monomorphic.
109 function fromTypedArray(that, array) {
110 var length = checked(array.length) | 0;
111 allocate(that, length);
112 // Truncating the elements is probably not what people expect from typed
113 // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
114 // of the old Buffer constructor.
115 for (var i = 0; i < length; i += 1)
116 that[i] = array[i] & 255;
119 function fromArrayLike(that, array) {
120 var length = checked(array.length) | 0;
121 allocate(that, length);
122 for (var i = 0; i < length; i += 1)
123 that[i] = array[i] & 255;
126 // Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
127 // Returns a zero-length buffer for inputs that don't conform to the spec.
128 function fromJsonObject(that, object) {
132 if (object.type === 'Buffer' && Array.isArray(object.data)) {
134 length = checked(array.length) | 0;
136 allocate(that, length);
138 for (var i = 0; i < length; i += 1)
139 that[i] = array[i] & 255;
142 function allocate(that, length) {
143 var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1;
144 that.parent = fromPool ? palloc(that, length) : alloc(that, length);
145 that.length = length;
148 function palloc(that, length) {
149 if (length > poolSize - poolOffset)
152 var start = poolOffset;
153 var end = start + length;
154 var buf = sliceOnto(allocPool, that, start, end);
160 function checked(length) {
161 // Note: cannot use `length < kMaxLength` here because that fails when
162 // length is NaN (which is otherwise coerced to zero.)
163 if (length >= kMaxLength) {
164 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
165 'size: 0x' + kMaxLength.toString(16) + ' bytes');
170 function SlowBuffer(length) {
171 length = length >>> 0;
172 if (length > kMaxLength) {
173 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
174 'size: 0x' + kMaxLength.toString(16) + ' bytes');
176 var b = new NativeBuffer(length);
182 // Bypass all checks for instantiating unallocated Buffer required for
183 // Objects created in C++. Significantly faster than calling the Buffer
185 function NativeBuffer(length) {
186 this.length = length >>> 0;
187 // Set this to keep the object map the same.
188 this.parent = undefined;
190 NativeBuffer.prototype = Buffer.prototype;
193 // add methods to Buffer prototype
194 binding.setupBufferJS(NativeBuffer);
199 Buffer.isBuffer = function isBuffer(b) {
200 return b instanceof Buffer;
204 Buffer.compare = function compare(a, b) {
205 if (!(a instanceof Buffer) ||
206 !(b instanceof Buffer))
207 throw new TypeError('Arguments must be Buffers');
212 return binding.compare(a, b);
216 Buffer.isEncoding = function(encoding) {
217 switch ((encoding + '').toLowerCase()) {
237 Buffer.concat = function(list, length) {
238 if (!Array.isArray(list))
239 throw new TypeError('list argument must be an Array of Buffers.');
241 if (length === undefined) {
243 for (var i = 0; i < list.length; i++)
244 length += list[i].length;
246 length = length >>> 0;
249 if (list.length === 0)
250 return new Buffer(0);
251 else if (list.length === 1)
254 var buffer = new Buffer(length);
256 for (var i = 0; i < list.length; i++) {
258 buf.copy(buffer, pos);
266 function byteLength(string, encoding) {
267 if (typeof(string) !== 'string')
268 string = String(string);
274 return string.length;
280 return string.length * 2;
283 return string.length >>> 1;
286 return binding.byteLength(string, encoding);
289 Buffer.byteLength = byteLength;
291 // toString(encoding, start=0, end=buffer.length)
292 Buffer.prototype.toString = function(encoding, start, end) {
293 var loweredCase = false;
296 end = end === undefined || end === Infinity ? this.length : end >>> 0;
298 if (!encoding) encoding = 'utf8';
299 if (start < 0) start = 0;
300 if (end > this.length) end = this.length;
301 if (end <= start) return '';
306 return this.hexSlice(start, end);
310 return this.utf8Slice(start, end);
313 return this.asciiSlice(start, end);
316 return this.binarySlice(start, end);
319 return this.base64Slice(start, end);
325 return this.ucs2Slice(start, end);
329 throw new TypeError('Unknown encoding: ' + encoding);
330 encoding = (encoding + '').toLowerCase();
337 Buffer.prototype.equals = function equals(b) {
338 if (!(b instanceof Buffer))
339 throw new TypeError('Argument must be a Buffer');
344 return binding.compare(this, b) === 0;
349 Buffer.prototype.inspect = function inspect() {
351 var max = exports.INSPECT_MAX_BYTES;
352 if (this.length > 0) {
353 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
354 if (this.length > max)
357 return '<' + this.constructor.name + ' ' + str + '>';
361 Buffer.prototype.compare = function compare(b) {
362 if (!(b instanceof Buffer))
363 throw new TypeError('Argument must be a Buffer');
368 return binding.compare(this, b);
372 Buffer.prototype.indexOf = function indexOf(val, byteOffset) {
373 if (byteOffset > 0x7fffffff)
374 byteOffset = 0x7fffffff;
375 else if (byteOffset < -0x80000000)
376 byteOffset = -0x80000000;
379 if (typeof val === 'string')
380 return binding.indexOfString(this, val, byteOffset);
381 if (val instanceof Buffer)
382 return binding.indexOfBuffer(this, val, byteOffset);
383 if (typeof val === 'number')
384 return binding.indexOfNumber(this, val, byteOffset);
386 throw new TypeError('val must be string, number or Buffer');
390 Buffer.prototype.fill = function fill(val, start, end) {
392 end = (end === undefined) ? this.length : end >> 0;
394 if (start < 0 || end > this.length)
395 throw new RangeError('out of range index');
399 if (typeof val !== 'string') {
401 } else if (val.length === 1) {
402 var code = val.charCodeAt(0);
407 binding.fill(this, val, start, end);
413 // XXX remove in v0.13
414 Buffer.prototype.get = util.deprecate(function get(offset) {
416 if (offset < 0 || offset >= this.length)
417 throw new RangeError('index out of range');
419 }, '.get() is deprecated. Access using array indexes instead.');
422 // XXX remove in v0.13
423 Buffer.prototype.set = util.deprecate(function set(offset, v) {
425 if (offset < 0 || offset >= this.length)
426 throw new RangeError('index out of range');
427 return this[offset] = v;
428 }, '.set() is deprecated. Set using array indexes instead.');
431 // TODO(trevnorris): fix these checks to follow new standard
432 // write(string, offset = 0, length = buffer.length, encoding = 'utf8')
433 var writeWarned = false;
434 const writeMsg = '.write(string, encoding, offset, length) is deprecated.' +
435 ' Use write(string[, offset[, length]][, encoding]) instead.';
436 Buffer.prototype.write = function(string, offset, length, encoding) {
437 // Buffer#write(string);
438 if (offset === undefined) {
440 length = this.length;
443 // Buffer#write(string, encoding)
444 } else if (length === undefined && typeof offset === 'string') {
446 length = this.length;
449 // Buffer#write(string, offset[, length][, encoding])
450 } else if (isFinite(offset)) {
451 offset = offset >>> 0;
452 if (isFinite(length)) {
453 length = length >>> 0;
454 if (encoding === undefined)
461 // XXX legacy write(string, encoding, offset, length) - remove in v0.13
464 if (process.throwDeprecation)
465 throw new Error(writeMsg);
466 else if (process.traceDeprecation)
467 console.trace(writeMsg);
469 console.error(writeMsg);
475 offset = length >>> 0;
479 var remaining = this.length - offset;
480 if (length === undefined || length > remaining)
483 if (string.length > 0 && (length < 0 || offset < 0))
484 throw new RangeError('attempt to write outside buffer bounds');
489 var loweredCase = false;
493 return this.hexWrite(string, offset, length);
497 return this.utf8Write(string, offset, length);
500 return this.asciiWrite(string, offset, length);
503 return this.binaryWrite(string, offset, length);
506 // Warning: maxLength not taken into account in base64Write
507 return this.base64Write(string, offset, length);
513 return this.ucs2Write(string, offset, length);
517 throw new TypeError('Unknown encoding: ' + encoding);
518 encoding = ('' + encoding).toLowerCase();
525 Buffer.prototype.toJSON = function() {
528 data: Array.prototype.slice.call(this, 0)
533 // TODO(trevnorris): currently works like Array.prototype.slice(), which
534 // doesn't follow the new standard for throwing on out of range indexes.
535 Buffer.prototype.slice = function(start, end) {
536 var len = this.length;
538 end = end === undefined ? len : ~~end;
544 } else if (start > len) {
552 } else if (end > len) {
559 var buf = new NativeBuffer();
560 sliceOnto(this, buf, start, end);
561 buf.length = end - start;
563 buf.parent = this.parent === undefined ? this : this.parent;
569 function checkOffset(offset, ext, length) {
570 if (offset + ext > length)
571 throw new RangeError('index out of range');
575 Buffer.prototype.readUIntLE = function(offset, byteLength, noAssert) {
576 offset = offset >>> 0;
577 byteLength = byteLength >>> 0;
579 checkOffset(offset, byteLength, this.length);
581 var val = this[offset];
584 while (++i < byteLength && (mul *= 0x100))
585 val += this[offset + i] * mul;
591 Buffer.prototype.readUIntBE = function(offset, byteLength, noAssert) {
592 offset = offset >>> 0;
593 byteLength = byteLength >>> 0;
595 checkOffset(offset, byteLength, this.length);
597 var val = this[offset + --byteLength];
599 while (byteLength > 0 && (mul *= 0x100))
600 val += this[offset + --byteLength] * mul;
606 Buffer.prototype.readUInt8 = function(offset, noAssert) {
607 offset = offset >>> 0;
609 checkOffset(offset, 1, this.length);
614 Buffer.prototype.readUInt16LE = function(offset, noAssert) {
615 offset = offset >>> 0;
617 checkOffset(offset, 2, this.length);
618 return this[offset] | (this[offset + 1] << 8);
622 Buffer.prototype.readUInt16BE = function(offset, noAssert) {
623 offset = offset >>> 0;
625 checkOffset(offset, 2, this.length);
626 return (this[offset] << 8) | this[offset + 1];
630 Buffer.prototype.readUInt32LE = function(offset, noAssert) {
631 offset = offset >>> 0;
633 checkOffset(offset, 4, this.length);
635 return ((this[offset]) |
636 (this[offset + 1] << 8) |
637 (this[offset + 2] << 16)) +
638 (this[offset + 3] * 0x1000000);
642 Buffer.prototype.readUInt32BE = function(offset, noAssert) {
643 offset = offset >>> 0;
645 checkOffset(offset, 4, this.length);
647 return (this[offset] * 0x1000000) +
648 ((this[offset + 1] << 16) |
649 (this[offset + 2] << 8) |
654 Buffer.prototype.readIntLE = function(offset, byteLength, noAssert) {
655 offset = offset >>> 0;
656 byteLength = byteLength >>> 0;
658 checkOffset(offset, byteLength, this.length);
660 var val = this[offset];
663 while (++i < byteLength && (mul *= 0x100))
664 val += this[offset + i] * mul;
668 val -= Math.pow(2, 8 * byteLength);
674 Buffer.prototype.readIntBE = function(offset, byteLength, noAssert) {
675 offset = offset >>> 0;
676 byteLength = byteLength >>> 0;
678 checkOffset(offset, byteLength, this.length);
682 var val = this[offset + --i];
683 while (i > 0 && (mul *= 0x100))
684 val += this[offset + --i] * mul;
688 val -= Math.pow(2, 8 * byteLength);
694 Buffer.prototype.readInt8 = function(offset, noAssert) {
695 offset = offset >>> 0;
697 checkOffset(offset, 1, this.length);
698 var val = this[offset];
699 return !(val & 0x80) ? val : (0xff - val + 1) * -1;
703 Buffer.prototype.readInt16LE = function(offset, noAssert) {
704 offset = offset >>> 0;
706 checkOffset(offset, 2, this.length);
707 var val = this[offset] | (this[offset + 1] << 8);
708 return (val & 0x8000) ? val | 0xFFFF0000 : val;
712 Buffer.prototype.readInt16BE = function(offset, noAssert) {
713 offset = offset >>> 0;
715 checkOffset(offset, 2, this.length);
716 var val = this[offset + 1] | (this[offset] << 8);
717 return (val & 0x8000) ? val | 0xFFFF0000 : val;
721 Buffer.prototype.readInt32LE = function(offset, noAssert) {
722 offset = offset >>> 0;
724 checkOffset(offset, 4, this.length);
726 return (this[offset]) |
727 (this[offset + 1] << 8) |
728 (this[offset + 2] << 16) |
729 (this[offset + 3] << 24);
733 Buffer.prototype.readInt32BE = function(offset, noAssert) {
734 offset = offset >>> 0;
736 checkOffset(offset, 4, this.length);
738 return (this[offset] << 24) |
739 (this[offset + 1] << 16) |
740 (this[offset + 2] << 8) |
745 Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
746 offset = offset >>> 0;
748 checkOffset(offset, 4, this.length);
749 return binding.readFloatLE(this, offset);
753 Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
754 offset = offset >>> 0;
756 checkOffset(offset, 4, this.length);
757 return binding.readFloatBE(this, offset);
761 Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
762 offset = offset >>> 0;
764 checkOffset(offset, 8, this.length);
765 return binding.readDoubleLE(this, offset);
769 Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
770 offset = offset >>> 0;
772 checkOffset(offset, 8, this.length);
773 return binding.readDoubleBE(this, offset);
777 function checkInt(buffer, value, offset, ext, max, min) {
778 if (!(buffer instanceof Buffer))
779 throw new TypeError('buffer must be a Buffer instance');
780 if (value > max || value < min)
781 throw new TypeError('value is out of bounds');
782 if (offset + ext > buffer.length)
783 throw new RangeError('index out of range');
787 Buffer.prototype.writeUIntLE = function(value, offset, byteLength, noAssert) {
789 offset = offset >>> 0;
790 byteLength = byteLength >>> 0;
792 checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0);
796 this[offset] = value;
797 while (++i < byteLength && (mul *= 0x100))
798 this[offset + i] = (value / mul) >>> 0;
800 return offset + byteLength;
804 Buffer.prototype.writeUIntBE = function(value, offset, byteLength, noAssert) {
806 offset = offset >>> 0;
807 byteLength = byteLength >>> 0;
809 checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0);
811 var i = byteLength - 1;
813 this[offset + i] = value;
814 while (--i >= 0 && (mul *= 0x100))
815 this[offset + i] = (value / mul) >>> 0;
817 return offset + byteLength;
821 Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
823 offset = offset >>> 0;
825 checkInt(this, value, offset, 1, 0xff, 0);
826 this[offset] = value;
831 Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
833 offset = offset >>> 0;
835 checkInt(this, value, offset, 2, 0xffff, 0);
836 this[offset] = value;
837 this[offset + 1] = (value >>> 8);
842 Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
844 offset = offset >>> 0;
846 checkInt(this, value, offset, 2, 0xffff, 0);
847 this[offset] = (value >>> 8);
848 this[offset + 1] = value;
853 Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
855 offset = offset >>> 0;
857 checkInt(this, value, offset, 4, 0xffffffff, 0);
858 this[offset + 3] = (value >>> 24);
859 this[offset + 2] = (value >>> 16);
860 this[offset + 1] = (value >>> 8);
861 this[offset] = value;
866 Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
868 offset = offset >>> 0;
870 checkInt(this, value, offset, 4, 0xffffffff, 0);
871 this[offset] = (value >>> 24);
872 this[offset + 1] = (value >>> 16);
873 this[offset + 2] = (value >>> 8);
874 this[offset + 3] = value;
879 Buffer.prototype.writeIntLE = function(value, offset, byteLength, noAssert) {
881 offset = offset >>> 0;
887 Math.pow(2, 8 * byteLength - 1) - 1,
888 -Math.pow(2, 8 * byteLength - 1));
893 var sub = value < 0 ? 1 : 0;
894 this[offset] = value;
895 while (++i < byteLength && (mul *= 0x100))
896 this[offset + i] = ((value / mul) >> 0) - sub;
898 return offset + byteLength;
902 Buffer.prototype.writeIntBE = function(value, offset, byteLength, noAssert) {
904 offset = offset >>> 0;
910 Math.pow(2, 8 * byteLength - 1) - 1,
911 -Math.pow(2, 8 * byteLength - 1));
914 var i = byteLength - 1;
916 var sub = value < 0 ? 1 : 0;
917 this[offset + i] = value;
918 while (--i >= 0 && (mul *= 0x100))
919 this[offset + i] = ((value / mul) >> 0) - sub;
921 return offset + byteLength;
925 Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
927 offset = offset >>> 0;
929 checkInt(this, value, offset, 1, 0x7f, -0x80);
930 this[offset] = value;
935 Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
937 offset = offset >>> 0;
939 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
940 this[offset] = value;
941 this[offset + 1] = (value >>> 8);
946 Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
948 offset = offset >>> 0;
950 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
951 this[offset] = (value >>> 8);
952 this[offset + 1] = value;
957 Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
959 offset = offset >>> 0;
961 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
962 this[offset] = value;
963 this[offset + 1] = (value >>> 8);
964 this[offset + 2] = (value >>> 16);
965 this[offset + 3] = (value >>> 24);
970 Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
972 offset = offset >>> 0;
974 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
975 this[offset] = (value >>> 24);
976 this[offset + 1] = (value >>> 16);
977 this[offset + 2] = (value >>> 8);
978 this[offset + 3] = value;
983 function checkFloat(buffer, value, offset, ext) {
984 if (!(buffer instanceof Buffer))
985 throw new TypeError('buffer must be a Buffer instance');
986 if (offset + ext > buffer.length)
987 throw new RangeError('index out of range');
991 Buffer.prototype.writeFloatLE = function writeFloatLE(val, offset, noAssert) {
993 offset = offset >>> 0;
995 checkFloat(this, val, offset, 4);
996 binding.writeFloatLE(this, val, offset);
1001 Buffer.prototype.writeFloatBE = function writeFloatBE(val, offset, noAssert) {
1003 offset = offset >>> 0;
1005 checkFloat(this, val, offset, 4);
1006 binding.writeFloatBE(this, val, offset);
1011 Buffer.prototype.writeDoubleLE = function writeDoubleLE(val, offset, noAssert) {
1013 offset = offset >>> 0;
1015 checkFloat(this, val, offset, 8);
1016 binding.writeDoubleLE(this, val, offset);
1021 Buffer.prototype.writeDoubleBE = function writeDoubleBE(val, offset, noAssert) {
1023 offset = offset >>> 0;
1025 checkFloat(this, val, offset, 8);
1026 binding.writeDoubleBE(this, val, offset);
1032 var ITERATOR_KIND_KEYS = 1;
1033 var ITERATOR_KIND_ENTRIES = 3;
1035 function BufferIteratorResult(value, done) {
1040 var resultCache = new Array(256);
1042 for (var i = 0; i < 256; i++)
1043 resultCache[i] = Object.freeze(new BufferIteratorResult(i, false));
1045 var finalResult = Object.freeze(new BufferIteratorResult(undefined, true));
1047 function BufferIterator(buffer, kind) {
1048 this._buffer = buffer;
1053 BufferIterator.prototype.next = function() {
1054 var buffer = this._buffer;
1055 var kind = this._kind;
1056 var index = this._index;
1058 if (index >= buffer.length)
1063 if (kind === ITERATOR_KIND_ENTRIES)
1064 return new BufferIteratorResult([index, buffer[index]], false);
1066 return new BufferIteratorResult(index, false);
1069 function BufferValueIterator(buffer) {
1070 BufferIterator.call(this, buffer, null);
1073 BufferValueIterator.prototype.next = function() {
1074 var buffer = this._buffer;
1075 var index = this._index;
1077 if (index >= buffer.length)
1082 return resultCache[buffer[index]];
1086 BufferIterator.prototype[Symbol.iterator] = function() {
1090 BufferValueIterator.prototype[Symbol.iterator] =
1091 BufferIterator.prototype[Symbol.iterator];
1093 Buffer.prototype.keys = function() {
1094 return new BufferIterator(this, ITERATOR_KIND_KEYS);
1097 Buffer.prototype.entries = function() {
1098 return new BufferIterator(this, ITERATOR_KIND_ENTRIES);
1101 Buffer.prototype.values = function() {
1102 return new BufferValueIterator(this);
1105 Buffer.prototype[Symbol.iterator] = Buffer.prototype.values;