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.fill = function fill(val, start, end) {
308 end = (end === undefined) ? this.length : end >> 0;
310 if (start < 0 || end > this.length)
311 throw new RangeError('out of range index');
315 if (typeof val !== 'string') {
317 } else if (val.length === 1) {
318 var code = val.charCodeAt(0);
323 binding.fill(this, val, start, end);
329 // XXX remove in v0.13
330 Buffer.prototype.get = util.deprecate(function get(offset) {
332 if (offset < 0 || offset >= this.length)
333 throw new RangeError('index out of range');
335 }, '.get() is deprecated. Access using array indexes instead.');
338 // XXX remove in v0.13
339 Buffer.prototype.set = util.deprecate(function set(offset, v) {
341 if (offset < 0 || offset >= this.length)
342 throw new RangeError('index out of range');
343 return this[offset] = v;
344 }, '.set() is deprecated. Set using array indexes instead.');
347 // TODO(trevnorris): fix these checks to follow new standard
348 // write(string, offset = 0, length = buffer.length, encoding = 'utf8')
349 var writeWarned = false;
350 const writeMsg = '.write(string, encoding, offset, length) is deprecated.' +
351 ' Use write(string[, offset[, length]][, encoding]) instead.';
352 Buffer.prototype.write = function(string, offset, length, encoding) {
353 // Buffer#write(string);
354 if (offset === undefined) {
356 length = this.length;
359 // Buffer#write(string, encoding)
360 } else if (length === undefined && typeof offset === 'string') {
362 length = this.length;
365 // Buffer#write(string, offset[, length][, encoding])
366 } else if (isFinite(offset)) {
367 offset = offset >>> 0;
368 if (isFinite(length)) {
369 length = length >>> 0;
370 if (encoding === undefined)
377 // XXX legacy write(string, encoding, offset, length) - remove in v0.13
380 if (process.throwDeprecation)
381 throw new Error(writeMsg);
382 else if (process.traceDeprecation)
383 console.trace(writeMsg);
385 console.error(writeMsg);
391 offset = length >>> 0;
395 var remaining = this.length - offset;
396 if (length === undefined || length > remaining)
399 encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
401 if (string.length > 0 && (length < 0 || offset < 0))
402 throw new RangeError('attempt to write outside buffer bounds');
407 ret = this.hexWrite(string, offset, length);
412 ret = this.utf8Write(string, offset, length);
416 ret = this.asciiWrite(string, offset, length);
420 ret = this.binaryWrite(string, offset, length);
424 // Warning: maxLength not taken into account in base64Write
425 ret = this.base64Write(string, offset, length);
432 ret = this.ucs2Write(string, offset, length);
436 throw new TypeError('Unknown encoding: ' + encoding);
443 Buffer.prototype.toJSON = function() {
446 data: Array.prototype.slice.call(this, 0)
451 // TODO(trevnorris): currently works like Array.prototype.slice(), which
452 // doesn't follow the new standard for throwing on out of range indexes.
453 Buffer.prototype.slice = function(start, end) {
454 var len = this.length;
456 end = end === undefined ? len : ~~end;
462 } else if (start > len) {
470 } else if (end > len) {
477 var buf = new NativeBuffer();
478 sliceOnto(this, buf, start, end);
479 buf.length = end - start;
481 buf.parent = this.parent === undefined ? this : this.parent;
487 function checkOffset(offset, ext, length) {
488 if (offset + ext > length)
489 throw new RangeError('index out of range');
493 Buffer.prototype.readUIntLE = function(offset, byteLength, noAssert) {
494 offset = offset >>> 0;
495 byteLength = byteLength >>> 0;
497 checkOffset(offset, byteLength, this.length);
499 var val = this[offset];
502 while (++i < byteLength && (mul *= 0x100))
503 val += this[offset + i] * mul;
509 Buffer.prototype.readUIntBE = function(offset, byteLength, noAssert) {
510 offset = offset >>> 0;
511 byteLength = byteLength >>> 0;
513 checkOffset(offset, byteLength, this.length);
515 var val = this[offset + --byteLength];
517 while (byteLength > 0 && (mul *= 0x100))
518 val += this[offset + --byteLength] * mul;
524 Buffer.prototype.readUInt8 = function(offset, noAssert) {
525 offset = offset >>> 0;
527 checkOffset(offset, 1, this.length);
532 Buffer.prototype.readUInt16LE = function(offset, noAssert) {
533 offset = offset >>> 0;
535 checkOffset(offset, 2, this.length);
536 return this[offset] | (this[offset + 1] << 8);
540 Buffer.prototype.readUInt16BE = function(offset, noAssert) {
541 offset = offset >>> 0;
543 checkOffset(offset, 2, this.length);
544 return (this[offset] << 8) | this[offset + 1];
548 Buffer.prototype.readUInt32LE = function(offset, noAssert) {
549 offset = offset >>> 0;
551 checkOffset(offset, 4, this.length);
553 return ((this[offset]) |
554 (this[offset + 1] << 8) |
555 (this[offset + 2] << 16)) +
556 (this[offset + 3] * 0x1000000);
560 Buffer.prototype.readUInt32BE = function(offset, noAssert) {
561 offset = offset >>> 0;
563 checkOffset(offset, 4, this.length);
565 return (this[offset] * 0x1000000) +
566 ((this[offset + 1] << 16) |
567 (this[offset + 2] << 8) |
572 Buffer.prototype.readIntLE = function(offset, byteLength, noAssert) {
573 offset = offset >>> 0;
574 byteLength = byteLength >>> 0;
576 checkOffset(offset, byteLength, this.length);
578 var val = this[offset];
581 while (++i < byteLength && (mul *= 0x100))
582 val += this[offset + i] * mul;
586 val -= Math.pow(2, 8 * byteLength);
592 Buffer.prototype.readIntBE = function(offset, byteLength, noAssert) {
593 offset = offset >>> 0;
594 byteLength = byteLength >>> 0;
596 checkOffset(offset, byteLength, this.length);
600 var val = this[offset + --i];
601 while (i > 0 && (mul *= 0x100))
602 val += this[offset + --i] * mul;
606 val -= Math.pow(2, 8 * byteLength);
612 Buffer.prototype.readInt8 = function(offset, noAssert) {
613 offset = offset >>> 0;
615 checkOffset(offset, 1, this.length);
616 var val = this[offset];
617 return !(val & 0x80) ? val : (0xff - val + 1) * -1;
621 Buffer.prototype.readInt16LE = function(offset, noAssert) {
622 offset = offset >>> 0;
624 checkOffset(offset, 2, this.length);
625 var val = this[offset] | (this[offset + 1] << 8);
626 return (val & 0x8000) ? val | 0xFFFF0000 : val;
630 Buffer.prototype.readInt16BE = function(offset, noAssert) {
631 offset = offset >>> 0;
633 checkOffset(offset, 2, this.length);
634 var val = this[offset + 1] | (this[offset] << 8);
635 return (val & 0x8000) ? val | 0xFFFF0000 : val;
639 Buffer.prototype.readInt32LE = function(offset, noAssert) {
640 offset = offset >>> 0;
642 checkOffset(offset, 4, this.length);
644 return (this[offset]) |
645 (this[offset + 1] << 8) |
646 (this[offset + 2] << 16) |
647 (this[offset + 3] << 24);
651 Buffer.prototype.readInt32BE = function(offset, noAssert) {
652 offset = offset >>> 0;
654 checkOffset(offset, 4, this.length);
656 return (this[offset] << 24) |
657 (this[offset + 1] << 16) |
658 (this[offset + 2] << 8) |
663 Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
664 offset = offset >>> 0;
666 checkOffset(offset, 4, this.length);
667 return binding.readFloatLE(this, offset);
671 Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
672 offset = offset >>> 0;
674 checkOffset(offset, 4, this.length);
675 return binding.readFloatBE(this, offset);
679 Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
680 offset = offset >>> 0;
682 checkOffset(offset, 8, this.length);
683 return binding.readDoubleLE(this, offset);
687 Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
688 offset = offset >>> 0;
690 checkOffset(offset, 8, this.length);
691 return binding.readDoubleBE(this, offset);
695 function checkInt(buffer, value, offset, ext, max, min) {
696 if (!(buffer instanceof Buffer))
697 throw new TypeError('buffer must be a Buffer instance');
698 if (value > max || value < min)
699 throw new TypeError('value is out of bounds');
700 if (offset + ext > buffer.length)
701 throw new RangeError('index out of range');
705 Buffer.prototype.writeUIntLE = function(value, offset, byteLength, noAssert) {
707 offset = offset >>> 0;
708 byteLength = byteLength >>> 0;
710 checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0);
714 this[offset] = value;
715 while (++i < byteLength && (mul *= 0x100))
716 this[offset + i] = (value / mul) >>> 0;
718 return offset + byteLength;
722 Buffer.prototype.writeUIntBE = function(value, offset, byteLength, noAssert) {
724 offset = offset >>> 0;
725 byteLength = byteLength >>> 0;
727 checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0);
729 var i = byteLength - 1;
731 this[offset + i] = value;
732 while (--i >= 0 && (mul *= 0x100))
733 this[offset + i] = (value / mul) >>> 0;
735 return offset + byteLength;
739 Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
741 offset = offset >>> 0;
743 checkInt(this, value, offset, 1, 0xff, 0);
744 this[offset] = value;
749 Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
751 offset = offset >>> 0;
753 checkInt(this, value, offset, 2, 0xffff, 0);
754 this[offset] = value;
755 this[offset + 1] = (value >>> 8);
760 Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
762 offset = offset >>> 0;
764 checkInt(this, value, offset, 2, 0xffff, 0);
765 this[offset] = (value >>> 8);
766 this[offset + 1] = value;
771 Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
773 offset = offset >>> 0;
775 checkInt(this, value, offset, 4, 0xffffffff, 0);
776 this[offset + 3] = (value >>> 24);
777 this[offset + 2] = (value >>> 16);
778 this[offset + 1] = (value >>> 8);
779 this[offset] = value;
784 Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
786 offset = offset >>> 0;
788 checkInt(this, value, offset, 4, 0xffffffff, 0);
789 this[offset] = (value >>> 24);
790 this[offset + 1] = (value >>> 16);
791 this[offset + 2] = (value >>> 8);
792 this[offset + 3] = value;
797 Buffer.prototype.writeIntLE = function(value, offset, byteLength, noAssert) {
799 offset = offset >>> 0;
805 Math.pow(2, 8 * byteLength - 1) - 1,
806 -Math.pow(2, 8 * byteLength - 1));
811 var sub = value < 0 ? 1 : 0;
812 this[offset] = value;
813 while (++i < byteLength && (mul *= 0x100))
814 this[offset + i] = ((value / mul) >> 0) - sub;
816 return offset + byteLength;
820 Buffer.prototype.writeIntBE = function(value, offset, byteLength, noAssert) {
822 offset = offset >>> 0;
828 Math.pow(2, 8 * byteLength - 1) - 1,
829 -Math.pow(2, 8 * byteLength - 1));
832 var i = byteLength - 1;
834 var sub = value < 0 ? 1 : 0;
835 this[offset + i] = value;
836 while (--i >= 0 && (mul *= 0x100))
837 this[offset + i] = ((value / mul) >> 0) - sub;
839 return offset + byteLength;
843 Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
845 offset = offset >>> 0;
847 checkInt(this, value, offset, 1, 0x7f, -0x80);
848 this[offset] = value;
853 Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
855 offset = offset >>> 0;
857 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
858 this[offset] = value;
859 this[offset + 1] = (value >>> 8);
864 Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
866 offset = offset >>> 0;
868 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
869 this[offset] = (value >>> 8);
870 this[offset + 1] = value;
875 Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
877 offset = offset >>> 0;
879 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
880 this[offset] = value;
881 this[offset + 1] = (value >>> 8);
882 this[offset + 2] = (value >>> 16);
883 this[offset + 3] = (value >>> 24);
888 Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
890 offset = offset >>> 0;
892 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
893 this[offset] = (value >>> 24);
894 this[offset + 1] = (value >>> 16);
895 this[offset + 2] = (value >>> 8);
896 this[offset + 3] = value;
901 function checkFloat(buffer, value, offset, ext) {
902 if (!(buffer instanceof Buffer))
903 throw new TypeError('buffer must be a Buffer instance');
904 if (offset + ext > buffer.length)
905 throw new RangeError('index out of range');
909 Buffer.prototype.writeFloatLE = function writeFloatLE(val, offset, noAssert) {
911 offset = offset >>> 0;
913 checkFloat(this, val, offset, 4);
914 binding.writeFloatLE(this, val, offset);
919 Buffer.prototype.writeFloatBE = function writeFloatBE(val, offset, noAssert) {
921 offset = offset >>> 0;
923 checkFloat(this, val, offset, 4);
924 binding.writeFloatBE(this, val, offset);
929 Buffer.prototype.writeDoubleLE = function writeDoubleLE(val, offset, noAssert) {
931 offset = offset >>> 0;
933 checkFloat(this, val, offset, 8);
934 binding.writeDoubleLE(this, val, offset);
939 Buffer.prototype.writeDoubleBE = function writeDoubleBE(val, offset, noAssert) {
941 offset = offset >>> 0;
943 checkFloat(this, val, offset, 8);
944 binding.writeDoubleBE(this, val, offset);
950 var ITERATOR_KIND_KEYS = 1;
951 var ITERATOR_KIND_ENTRIES = 3;
953 function BufferIteratorResult(value, done) {
958 var resultCache = new Array(256);
960 for (var i = 0; i < 256; i++)
961 resultCache[i] = Object.freeze(new BufferIteratorResult(i, false));
963 var finalResult = Object.freeze(new BufferIteratorResult(undefined, true));
965 function BufferIterator(buffer, kind) {
966 this._buffer = buffer;
971 BufferIterator.prototype.next = function() {
972 var buffer = this._buffer;
973 var kind = this._kind;
974 var index = this._index;
976 if (index >= buffer.length)
981 if (kind === ITERATOR_KIND_ENTRIES)
982 return new BufferIteratorResult([index, buffer[index]], false);
984 return new BufferIteratorResult(index, false);
987 function BufferValueIterator(buffer) {
988 BufferIterator.call(this, buffer, null);
991 BufferValueIterator.prototype.next = function() {
992 var buffer = this._buffer;
993 var index = this._index;
995 if (index >= buffer.length)
1000 return resultCache[buffer[index]];
1004 BufferIterator.prototype[Symbol.iterator] = function() {
1008 BufferValueIterator.prototype[Symbol.iterator] =
1009 BufferIterator.prototype[Symbol.iterator];
1011 Buffer.prototype.keys = function() {
1012 return new BufferIterator(this, ITERATOR_KIND_KEYS);
1015 Buffer.prototype.entries = function() {
1016 return new BufferIterator(this, ITERATOR_KIND_ENTRIES);
1019 Buffer.prototype.values = function() {
1020 return new BufferValueIterator(this);
1023 Buffer.prototype[Symbol.iterator] = Buffer.prototype.values;