1 // Copyright Joyent, Inc. and other Node contributors.
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
24 var buffer = process.binding('buffer');
25 var smalloc = process.binding('smalloc');
26 var util = require('util');
27 var alloc = smalloc.alloc;
28 var truncate = smalloc.truncate;
29 var sliceOnto = smalloc.sliceOnto;
30 var kMaxLength = smalloc.kMaxLength;
33 exports.Buffer = Buffer;
34 exports.SlowBuffer = SlowBuffer;
35 exports.INSPECT_MAX_BYTES = 50;
38 Buffer.poolSize = 8 * 1024;
39 var poolSize, poolOffset, allocPool;
42 function createPool() {
43 poolSize = Buffer.poolSize;
44 allocPool = alloc({}, poolSize);
50 function Buffer(subject, encoding) {
51 if (!util.isBuffer(this))
52 return new Buffer(subject, encoding);
54 if (util.isNumber(subject)) {
55 this.length = subject > 0 ? subject >>> 0 : 0;
57 } else if (util.isString(subject)) {
58 if (!util.isString(encoding) || encoding.length === 0)
60 this.length = Buffer.byteLength(subject, encoding);
62 // Handle Arrays, Buffers, Uint8Arrays or JSON.
63 } else if (util.isObject(subject)) {
64 if (subject.type === 'Buffer' && util.isArray(subject.data))
65 subject = subject.data;
66 // Must use floor() because array length may be > kMaxLength.
67 this.length = +subject.length > 0 ? Math.floor(+subject.length) : 0;
70 throw new TypeError('must start with number, buffer, array or string');
73 if (this.length > kMaxLength) {
74 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
75 'size: 0x' + kMaxLength.toString(16) + ' bytes');
78 this.parent = undefined;
79 if (this.length <= (Buffer.poolSize >>> 1) && this.length > 0) {
80 if (this.length > poolSize - poolOffset)
82 this.parent = sliceOnto(allocPool,
85 poolOffset + this.length);
86 poolOffset += this.length;
88 alloc(this, this.length);
91 if (util.isNumber(subject)) {
95 if (util.isString(subject)) {
96 // In the case of base64 it's possible that the size of the buffer
97 // allocated was slightly too large. In this case we need to rewrite
98 // the length to the actual length written.
99 var len = this.write(subject, encoding);
100 // Buffer was truncated after decode, realloc internal ExternalArray
101 if (len !== this.length) {
102 var prevLen = this.length;
104 truncate(this, this.length);
105 poolOffset -= (prevLen - len);
108 } else if (util.isBuffer(subject)) {
109 subject.copy(this, 0, 0, this.length);
111 } else if (util.isNumber(subject.length) || util.isArray(subject)) {
112 // Really crappy way to handle Uint8Arrays, but V8 doesn't give a simple
113 // way to access the data from the C++ API.
114 for (var i = 0; i < this.length; i++)
115 this[i] = subject[i];
120 function SlowBuffer(length) {
121 length = length >>> 0;
122 if (length > kMaxLength) {
123 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
124 'size: 0x' + kMaxLength.toString(16) + ' bytes');
126 var b = new NativeBuffer(length);
132 // Bypass all checks for instantiating unallocated Buffer required for
133 // Objects created in C++. Significantly faster than calling the Buffer
135 function NativeBuffer(length) {
136 this.length = length >>> 0;
137 // Set this to keep the object map the same.
138 this.parent = undefined;
140 NativeBuffer.prototype = Buffer.prototype;
143 // add methods to Buffer prototype
144 buffer.setupBufferJS(NativeBuffer, internal);
149 Buffer.isBuffer = function isBuffer(b) {
150 return util.isBuffer(b);
154 Buffer.compare = function compare(a, b) {
155 if (!(a instanceof Buffer) ||
156 !(b instanceof Buffer))
157 throw new TypeError('Arguments must be Buffers');
159 return internal.compare(a, b);
163 Buffer.isEncoding = function(encoding) {
164 switch ((encoding + '').toLowerCase()) {
184 Buffer.concat = function(list, length) {
185 if (!util.isArray(list))
186 throw new TypeError('Usage: Buffer.concat(list[, length])');
188 if (util.isUndefined(length)) {
190 for (var i = 0; i < list.length; i++)
191 length += list[i].length;
193 length = length >>> 0;
196 if (list.length === 0)
197 return new Buffer(0);
198 else if (list.length === 1)
201 var buffer = new Buffer(length);
203 for (var i = 0; i < list.length; i++) {
205 buf.copy(buffer, pos);
213 Buffer.byteLength = function(str, enc) {
226 ret = str.length * 2;
229 ret = str.length >>> 1;
232 ret = internal.byteLength(str, enc);
238 // toString(encoding, start=0, end=buffer.length)
239 Buffer.prototype.toString = function(encoding, start, end) {
240 var loweredCase = false;
243 end = util.isUndefined(end) || end === Infinity ? this.length : end >>> 0;
245 if (!encoding) encoding = 'utf8';
246 if (start < 0) start = 0;
247 if (end > this.length) end = this.length;
248 if (end <= start) return '';
253 return this.hexSlice(start, end);
257 return this.utf8Slice(start, end);
260 return this.asciiSlice(start, end);
263 return this.binarySlice(start, end);
266 return this.base64Slice(start, end);
272 return this.ucs2Slice(start, end);
276 throw new TypeError('Unknown encoding: ' + encoding);
277 encoding = (encoding + '').toLowerCase();
284 Buffer.prototype.equals = function equals(b) {
285 if (!(b instanceof Buffer))
286 throw new TypeError('Argument must be a Buffer');
288 return internal.compare(this, b) === 0;
293 Buffer.prototype.inspect = function inspect() {
295 var max = exports.INSPECT_MAX_BYTES;
296 if (this.length > 0) {
297 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
298 if (this.length > max)
301 return '<' + this.constructor.name + ' ' + str + '>';
305 Buffer.prototype.compare = function compare(b) {
306 if (!(b instanceof Buffer))
307 throw new TypeError('Argument must be a Buffer');
309 return internal.compare(this, b);
313 Buffer.prototype.fill = function fill(val, start, end) {
315 end = (end === undefined) ? this.length : end >> 0;
317 if (start < 0 || end > this.length)
318 throw new RangeError('out of range index');
322 if (typeof val !== 'string') {
324 } else if (val.length === 1) {
325 var code = val.charCodeAt(0);
330 internal.fill(this, val, start, end);
336 // XXX remove in v0.13
337 Buffer.prototype.get = util.deprecate(function get(offset) {
339 if (offset < 0 || offset >= this.length)
340 throw new RangeError('index out of range');
342 }, '.get() is deprecated. Access using array indexes instead.');
345 // XXX remove in v0.13
346 Buffer.prototype.set = util.deprecate(function set(offset, v) {
348 if (offset < 0 || offset >= this.length)
349 throw new RangeError('index out of range');
350 return this[offset] = v;
351 }, '.set() is deprecated. Set using array indexes instead.');
354 // TODO(trevnorris): fix these checks to follow new standard
355 // write(string, offset = 0, length = buffer.length, encoding = 'utf8')
356 var writeWarned = false;
357 var writeMsg = '.write(string, encoding, offset, length) is deprecated.' +
358 ' Use write(string[, offset[, length]][, encoding]) instead.';
359 Buffer.prototype.write = function(string, offset, length, encoding) {
360 // Buffer#write(string);
361 if (util.isUndefined(offset)) {
363 length = this.length;
366 // Buffer#write(string, encoding)
367 } else if (util.isUndefined(length) && util.isString(offset)) {
369 length = this.length;
372 // Buffer#write(string, offset[, length][, encoding])
373 } else if (isFinite(offset)) {
374 offset = offset >>> 0;
375 if (isFinite(length)) {
376 length = length >>> 0;
377 if (util.isUndefined(encoding))
384 // XXX legacy write(string, encoding, offset, length) - remove in v0.13
387 if (process.throwDeprecation)
388 throw new Error(writeMsg);
389 else if (process.traceDeprecation)
390 console.trace(writeMsg);
392 console.error(writeMsg);
398 offset = length >>> 0;
402 var remaining = this.length - offset;
403 if (util.isUndefined(length) || length > remaining)
406 encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
408 if (string.length > 0 && (length < 0 || offset < 0))
409 throw new RangeError('attempt to write outside buffer bounds');
414 ret = this.hexWrite(string, offset, length);
419 ret = this.utf8Write(string, offset, length);
423 ret = this.asciiWrite(string, offset, length);
427 ret = this.binaryWrite(string, offset, length);
431 // Warning: maxLength not taken into account in base64Write
432 ret = this.base64Write(string, offset, length);
439 ret = this.ucs2Write(string, offset, length);
443 throw new TypeError('Unknown encoding: ' + encoding);
450 Buffer.prototype.toJSON = function() {
453 data: Array.prototype.slice.call(this, 0)
458 // TODO(trevnorris): currently works like Array.prototype.slice(), which
459 // doesn't follow the new standard for throwing on out of range indexes.
460 Buffer.prototype.slice = function(start, end) {
461 var len = this.length;
463 end = util.isUndefined(end) ? len : ~~end;
469 } else if (start > len) {
477 } else if (end > len) {
484 var buf = new NativeBuffer();
485 sliceOnto(this, buf, start, end);
486 buf.length = end - start;
488 buf.parent = util.isUndefined(this.parent) ? this : this.parent;
494 function checkOffset(offset, ext, length) {
495 if (offset + ext > length)
496 throw new RangeError('index out of range');
500 Buffer.prototype.readUIntLE = function(offset, byteLength, noAssert) {
501 offset = offset >>> 0;
502 byteLength = byteLength >>> 0;
504 checkOffset(offset, byteLength, this.length);
506 var val = this[offset];
509 while (++i < byteLength && (mul *= 0x100))
510 val += this[offset + i] * mul;
516 Buffer.prototype.readUIntBE = function(offset, byteLength, noAssert) {
517 offset = offset >>> 0;
518 byteLength = byteLength >>> 0;
520 checkOffset(offset, byteLength, this.length);
522 var val = this[offset + --byteLength];
524 while (byteLength > 0 && (mul *= 0x100))
525 val += this[offset + --byteLength] * mul;
531 Buffer.prototype.readUInt8 = function(offset, noAssert) {
532 offset = offset >>> 0;
534 checkOffset(offset, 1, this.length);
539 Buffer.prototype.readUInt16LE = function(offset, noAssert) {
540 offset = offset >>> 0;
542 checkOffset(offset, 2, this.length);
543 return this[offset] | (this[offset + 1] << 8);
547 Buffer.prototype.readUInt16BE = function(offset, noAssert) {
548 offset = offset >>> 0;
550 checkOffset(offset, 2, this.length);
551 return (this[offset] << 8) | this[offset + 1];
555 Buffer.prototype.readUInt32LE = function(offset, noAssert) {
556 offset = offset >>> 0;
558 checkOffset(offset, 4, this.length);
560 return ((this[offset]) |
561 (this[offset + 1] << 8) |
562 (this[offset + 2] << 16)) +
563 (this[offset + 3] * 0x1000000);
567 Buffer.prototype.readUInt32BE = function(offset, noAssert) {
568 offset = offset >>> 0;
570 checkOffset(offset, 4, this.length);
572 return (this[offset] * 0x1000000) +
573 ((this[offset + 1] << 16) |
574 (this[offset + 2] << 8) |
579 Buffer.prototype.readIntLE = function(offset, byteLength, noAssert) {
580 offset = offset >>> 0;
581 byteLength = byteLength >>> 0;
583 checkOffset(offset, byteLength, this.length);
585 var val = this[offset];
588 while (++i < byteLength && (mul *= 0x100))
589 val += this[offset + i] * mul;
593 val -= Math.pow(2, 8 * byteLength);
599 Buffer.prototype.readIntBE = function(offset, byteLength, noAssert) {
600 offset = offset >>> 0;
601 byteLength = byteLength >>> 0;
603 checkOffset(offset, byteLength, this.length);
607 var val = this[offset + --i];
608 while (i > 0 && (mul *= 0x100))
609 val += this[offset + --i] * mul;
613 val -= Math.pow(2, 8 * byteLength);
619 Buffer.prototype.readInt8 = function(offset, noAssert) {
620 offset = offset >>> 0;
622 checkOffset(offset, 1, this.length);
623 var val = this[offset];
624 return !(val & 0x80) ? val : (0xff - val + 1) * -1;
628 Buffer.prototype.readInt16LE = function(offset, noAssert) {
629 offset = offset >>> 0;
631 checkOffset(offset, 2, this.length);
632 var val = this[offset] | (this[offset + 1] << 8);
633 return (val & 0x8000) ? val | 0xFFFF0000 : val;
637 Buffer.prototype.readInt16BE = function(offset, noAssert) {
638 offset = offset >>> 0;
640 checkOffset(offset, 2, this.length);
641 var val = this[offset + 1] | (this[offset] << 8);
642 return (val & 0x8000) ? val | 0xFFFF0000 : val;
646 Buffer.prototype.readInt32LE = function(offset, noAssert) {
647 offset = offset >>> 0;
649 checkOffset(offset, 4, this.length);
651 return (this[offset]) |
652 (this[offset + 1] << 8) |
653 (this[offset + 2] << 16) |
654 (this[offset + 3] << 24);
658 Buffer.prototype.readInt32BE = function(offset, noAssert) {
659 offset = offset >>> 0;
661 checkOffset(offset, 4, this.length);
663 return (this[offset] << 24) |
664 (this[offset + 1] << 16) |
665 (this[offset + 2] << 8) |
670 Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
671 offset = offset >>> 0;
673 checkOffset(offset, 4, this.length);
674 return internal.readFloatLE(this, offset);
678 Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
679 offset = offset >>> 0;
681 checkOffset(offset, 4, this.length);
682 return internal.readFloatBE(this, offset);
686 Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
687 offset = offset >>> 0;
689 checkOffset(offset, 8, this.length);
690 return internal.readDoubleLE(this, offset);
694 Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
695 offset = offset >>> 0;
697 checkOffset(offset, 8, this.length);
698 return internal.readDoubleBE(this, offset);
702 function checkInt(buffer, value, offset, ext, max, min) {
703 if (!(buffer instanceof Buffer))
704 throw new TypeError('buffer must be a Buffer instance');
705 if (value > max || value < min)
706 throw new TypeError('value is out of bounds');
707 if (offset + ext > buffer.length)
708 throw new RangeError('index out of range');
712 Buffer.prototype.writeUIntLE = function(value, offset, byteLength, noAssert) {
714 offset = offset >>> 0;
715 byteLength = byteLength >>> 0;
717 checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0);
721 this[offset] = value;
722 while (++i < byteLength && (mul *= 0x100))
723 this[offset + i] = (value / mul) >>> 0;
725 return offset + byteLength;
729 Buffer.prototype.writeUIntBE = function(value, offset, byteLength, noAssert) {
731 offset = offset >>> 0;
732 byteLength = byteLength >>> 0;
734 checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0);
736 var i = byteLength - 1;
738 this[offset + i] = value;
739 while (--i >= 0 && (mul *= 0x100))
740 this[offset + i] = (value / mul) >>> 0;
742 return offset + byteLength;
746 Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
748 offset = offset >>> 0;
750 checkInt(this, value, offset, 1, 0xff, 0);
751 this[offset] = value;
756 Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
758 offset = offset >>> 0;
760 checkInt(this, value, offset, 2, 0xffff, 0);
761 this[offset] = value;
762 this[offset + 1] = (value >>> 8);
767 Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
769 offset = offset >>> 0;
771 checkInt(this, value, offset, 2, 0xffff, 0);
772 this[offset] = (value >>> 8);
773 this[offset + 1] = value;
778 Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
780 offset = offset >>> 0;
782 checkInt(this, value, offset, 4, 0xffffffff, 0);
783 this[offset + 3] = (value >>> 24);
784 this[offset + 2] = (value >>> 16);
785 this[offset + 1] = (value >>> 8);
786 this[offset] = value;
791 Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
793 offset = offset >>> 0;
795 checkInt(this, value, offset, 4, 0xffffffff, 0);
796 this[offset] = (value >>> 24);
797 this[offset + 1] = (value >>> 16);
798 this[offset + 2] = (value >>> 8);
799 this[offset + 3] = value;
804 Buffer.prototype.writeIntLE = function(value, offset, byteLength, noAssert) {
806 offset = offset >>> 0;
812 Math.pow(2, 8 * byteLength - 1) - 1,
813 -Math.pow(2, 8 * byteLength - 1));
818 var sub = value < 0 ? 1 : 0;
819 this[offset] = value;
820 while (++i < byteLength && (mul *= 0x100))
821 this[offset + i] = ((value / mul) >> 0) - sub;
823 return offset + byteLength;
827 Buffer.prototype.writeIntBE = function(value, offset, byteLength, noAssert) {
829 offset = offset >>> 0;
835 Math.pow(2, 8 * byteLength - 1) - 1,
836 -Math.pow(2, 8 * byteLength - 1));
839 var i = byteLength - 1;
841 var sub = value < 0 ? 1 : 0;
842 this[offset + i] = value;
843 while (--i >= 0 && (mul *= 0x100))
844 this[offset + i] = ((value / mul) >> 0) - sub;
846 return offset + byteLength;
850 Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
852 offset = offset >>> 0;
854 checkInt(this, value, offset, 1, 0x7f, -0x80);
855 this[offset] = value;
860 Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
862 offset = offset >>> 0;
864 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
865 this[offset] = value;
866 this[offset + 1] = (value >>> 8);
871 Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
873 offset = offset >>> 0;
875 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
876 this[offset] = (value >>> 8);
877 this[offset + 1] = value;
882 Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
884 offset = offset >>> 0;
886 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
887 this[offset] = value;
888 this[offset + 1] = (value >>> 8);
889 this[offset + 2] = (value >>> 16);
890 this[offset + 3] = (value >>> 24);
895 Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
897 offset = offset >>> 0;
899 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
900 this[offset] = (value >>> 24);
901 this[offset + 1] = (value >>> 16);
902 this[offset + 2] = (value >>> 8);
903 this[offset + 3] = value;
908 function checkFloat(buffer, value, offset, ext) {
909 if (!(buffer instanceof Buffer))
910 throw new TypeError('buffer must be a Buffer instance');
911 if (offset + ext > buffer.length)
912 throw new RangeError('index out of range');
916 Buffer.prototype.writeFloatLE = function writeFloatLE(val, offset, noAssert) {
918 offset = offset >>> 0;
920 checkFloat(this, val, offset, 4);
921 internal.writeFloatLE(this, val, offset);
926 Buffer.prototype.writeFloatBE = function writeFloatBE(val, offset, noAssert) {
928 offset = offset >>> 0;
930 checkFloat(this, val, offset, 4);
931 internal.writeFloatBE(this, val, offset);
936 Buffer.prototype.writeDoubleLE = function writeDoubleLE(val, offset, noAssert) {
938 offset = offset >>> 0;
940 checkFloat(this, val, offset, 8);
941 internal.writeDoubleLE(this, val, offset);
946 Buffer.prototype.writeDoubleBE = function writeDoubleBE(val, offset, noAssert) {
948 offset = offset >>> 0;
950 checkFloat(this, val, offset, 8);
951 internal.writeDoubleBE(this, val, offset);