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.
22 var SlowBuffer = process.binding('buffer').SlowBuffer;
23 var assert = require('assert');
25 exports.INSPECT_MAX_BYTES = 50;
27 // Make SlowBuffer inherit from Buffer.
28 // This is an exception to the rule that __proto__ is not allowed in core.
29 SlowBuffer.prototype.__proto__ = Buffer.prototype;
32 function clamp(index, len, defaultValue) {
33 if (typeof index !== 'number') return defaultValue;
34 index = ~~index; // Coerce to integer.
35 if (index >= len) return len;
36 if (index >= 0) return index;
38 if (index >= 0) return index;
44 if (n < 16) return '0' + n.toString(16);
45 return n.toString(16);
49 SlowBuffer.prototype.toString = function(encoding, start, end) {
50 encoding = String(encoding || 'utf8').toLowerCase();
52 if (typeof end !== 'number') end = this.length;
54 // Fastpath empty strings
61 return this.hexSlice(start, end);
65 return this.utf8Slice(start, end);
68 return this.asciiSlice(start, end);
71 return this.binarySlice(start, end);
74 return this.base64Slice(start, end);
80 return this.ucs2Slice(start, end);
83 throw new TypeError('Unknown encoding: ' + encoding);
88 SlowBuffer.prototype.write = function(string, offset, length, encoding) {
89 // Support both (string, offset, length, encoding)
90 // and the legacy (string, encoding, offset, length)
91 if (isFinite(offset)) {
92 if (!isFinite(length)) {
103 offset = +offset || 0;
104 var remaining = this.length - offset;
109 if (length > remaining) {
113 encoding = String(encoding || 'utf8').toLowerCase();
117 return this.hexWrite(string, offset, length);
121 return this.utf8Write(string, offset, length);
124 return this.asciiWrite(string, offset, length);
127 return this.binaryWrite(string, offset, length);
130 return this.base64Write(string, offset, length);
136 return this.ucs2Write(string, offset, length);
139 throw new TypeError('Unknown encoding: ' + encoding);
145 SlowBuffer.prototype.slice = function(start, end) {
146 var len = this.length;
147 start = clamp(start, len, 0);
148 end = clamp(end, len, len);
149 return new Buffer(this, end - start, start);
153 var zeroBuffer = new SlowBuffer(0);
156 function Buffer(subject, encoding, offset) {
157 if (!(this instanceof Buffer)) {
158 return new Buffer(subject, encoding, offset);
164 if (typeof offset === 'number') {
165 if (!Buffer.isBuffer(subject)) {
166 throw new TypeError('First argument must be a Buffer when slicing');
169 this.length = +encoding > 0 ? Math.ceil(encoding) : 0;
170 this.parent = subject.parent ? subject.parent : subject;
171 this.offset = offset;
174 switch (type = typeof subject) {
176 this.length = +subject > 0 ? Math.ceil(subject) : 0;
180 this.length = Buffer.byteLength(subject, encoding);
183 case 'object': // Assume object is array-ish
184 this.length = +subject.length > 0 ? Math.ceil(subject.length) : 0;
188 throw new TypeError('First argument needs to be a number, ' +
192 if (this.length > Buffer.poolSize) {
193 // Big buffer, just alloc one.
194 this.parent = new SlowBuffer(this.length);
197 } else if (this.length > 0) {
199 if (!pool || pool.length - pool.used < this.length) allocPool();
201 this.offset = pool.used;
202 pool.used += this.length;
203 if (pool.used & 7) pool.used = (pool.used + 8) & ~7;
206 // Zero-length buffer
207 this.parent = zeroBuffer;
211 // optimize by branching logic for new allocations
212 if (typeof subject !== 'number') {
213 if (type === 'string') {
215 this.length = this.write(subject, 0, encoding);
216 // if subject is buffer then use built-in copy method
217 } else if (Buffer.isBuffer(subject)) {
219 subject.parent.copy(this.parent,
222 this.length + subject.offset);
224 subject.copy(this.parent, this.offset, 0, this.length);
225 } else if (isArrayIsh(subject)) {
226 for (var i = 0; i < this.length; i++)
227 this.parent[i + this.offset] = subject[i];
232 SlowBuffer.makeFastBuffer(this.parent, this, this.offset, this.length);
235 function isArrayIsh(subject) {
236 return Array.isArray(subject) ||
237 subject && typeof subject === 'object' &&
238 typeof subject.length === 'number';
241 exports.SlowBuffer = SlowBuffer;
242 exports.Buffer = Buffer;
245 Buffer.isEncoding = function(encoding) {
246 switch (encoding && encoding.toLowerCase()) {
267 Buffer.poolSize = 8 * 1024;
270 function allocPool() {
271 pool = new SlowBuffer(Buffer.poolSize);
277 Buffer.isBuffer = function isBuffer(b) {
278 return b instanceof Buffer;
283 Buffer.prototype.inspect = function inspect() {
286 name = this.constructor.name;
288 for (var i = 0; i < len; i++) {
289 out[i] = toHex(this[i]);
290 if (i == exports.INSPECT_MAX_BYTES) {
296 return '<' + name + ' ' + out.join(' ') + '>';
300 Buffer.prototype.get = function get(offset) {
301 if (offset < 0 || offset >= this.length)
302 throw new RangeError('offset is out of bounds');
303 return this.parent[this.offset + offset];
307 Buffer.prototype.set = function set(offset, v) {
308 if (offset < 0 || offset >= this.length)
309 throw new RangeError('offset is out of bounds');
310 return this.parent[this.offset + offset] = v;
314 // write(string, offset = 0, length = buffer.length-offset, encoding = 'utf8')
315 Buffer.prototype.write = function(string, offset, length, encoding) {
316 // Support both (string, offset, length, encoding)
317 // and the legacy (string, encoding, offset, length)
318 if (isFinite(offset)) {
319 if (!isFinite(length)) {
330 offset = +offset || 0;
331 var remaining = this.length - offset;
336 if (length > remaining) {
340 encoding = String(encoding || 'utf8').toLowerCase();
345 ret = this.parent.hexWrite(string, this.offset + offset, length);
350 ret = this.parent.utf8Write(string, this.offset + offset, length);
354 ret = this.parent.asciiWrite(string, this.offset + offset, length);
358 ret = this.parent.binaryWrite(string, this.offset + offset, length);
362 // Warning: maxLength not taken into account in base64Write
363 ret = this.parent.base64Write(string, this.offset + offset, length);
370 ret = this.parent.ucs2Write(string, this.offset + offset, length);
374 throw new TypeError('Unknown encoding: ' + encoding);
381 Buffer.prototype.toJSON = function() {
384 data: Array.prototype.slice.call(this, 0)
389 // toString(encoding, start=0, end=buffer.length)
390 Buffer.prototype.toString = function(encoding, start, end) {
391 encoding = String(encoding || 'utf8').toLowerCase();
393 if (typeof start !== 'number' || start < 0) {
395 } else if (start > this.length) {
399 if (typeof end !== 'number' || end > this.length) {
401 } else if (end < 0) {
405 start = start + this.offset;
406 end = end + this.offset;
410 return this.parent.hexSlice(start, end);
414 return this.parent.utf8Slice(start, end);
417 return this.parent.asciiSlice(start, end);
420 return this.parent.binarySlice(start, end);
423 return this.parent.base64Slice(start, end);
429 return this.parent.ucs2Slice(start, end);
432 throw new TypeError('Unknown encoding: ' + encoding);
438 Buffer.byteLength = SlowBuffer.byteLength;
441 // fill(value, start=0, end=buffer.length)
442 Buffer.prototype.fill = function fill(value, start, end) {
443 value || (value = 0);
444 start || (start = 0);
445 end || (end = this.length);
447 if (typeof value === 'string') {
448 value = value.charCodeAt(0);
450 if (typeof value !== 'number' || isNaN(value)) {
451 throw new TypeError('value is not a number');
454 if (end < start) throw new RangeError('end < start');
456 // Fill 0 bytes; we're done
457 if (end === start) return 0;
458 if (this.length == 0) return 0;
460 if (start < 0 || start >= this.length) {
461 throw new RangeError('start out of bounds');
464 if (end < 0 || end > this.length) {
465 throw new RangeError('end out of bounds');
468 return this.parent.fill(value,
474 Buffer.concat = function(list, length) {
475 if (!Array.isArray(list)) {
476 throw new TypeError('Usage: Buffer.concat(list, [length])');
479 if (list.length === 0) {
480 return new Buffer(0);
481 } else if (list.length === 1) {
485 if (typeof length !== 'number') {
487 for (var i = 0; i < list.length; i++) {
489 length += buf.length;
493 var buffer = new Buffer(length);
495 for (var i = 0; i < list.length; i++) {
497 buf.copy(buffer, pos);
506 // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
507 Buffer.prototype.copy = function(target, target_start, start, end) {
508 // set undefined/NaN or out of bounds values equal to their default
509 if (!(target_start >= 0)) target_start = 0;
510 if (!(start >= 0)) start = 0;
511 if (!(end < this.length)) end = this.length;
513 // Copy 0 bytes; we're done
515 target.length === 0 ||
521 throw new RangeError('sourceEnd < sourceStart');
523 if (target_start >= target.length)
524 throw new RangeError('targetStart out of bounds');
526 if (target.length - target_start < end - start)
527 end = target.length - target_start + start;
529 return this.parent.copy(target.parent || target,
530 target_start + (target.offset || 0),
537 Buffer.prototype.slice = function(start, end) {
538 var len = this.length;
539 start = clamp(start, len, 0);
540 end = clamp(end, len, len);
541 return new Buffer(this.parent, end - start, start + this.offset);
545 // Legacy methods for backwards compatibility.
547 Buffer.prototype.utf8Slice = function(start, end) {
548 return this.toString('utf8', start, end);
551 Buffer.prototype.binarySlice = function(start, end) {
552 return this.toString('binary', start, end);
555 Buffer.prototype.asciiSlice = function(start, end) {
556 return this.toString('ascii', start, end);
559 Buffer.prototype.utf8Write = function(string, offset) {
560 return this.write(string, offset, 'utf8');
563 Buffer.prototype.binaryWrite = function(string, offset) {
564 return this.write(string, offset, 'binary');
567 Buffer.prototype.asciiWrite = function(string, offset) {
568 return this.write(string, offset, 'ascii');
573 * Need to make sure that buffer isn't trying to write out of bounds.
574 * This check is far too slow internally for fast buffers.
576 function checkOffset(offset, ext, length) {
577 if ((offset % 1) !== 0 || offset < 0)
578 throw new RangeError('offset is not uint');
579 if (offset + ext > length)
580 throw new RangeError('Trying to access beyond buffer length');
584 Buffer.prototype.readUInt8 = function(offset, noAssert) {
586 checkOffset(offset, 1, this.length);
591 function readUInt16(buffer, offset, isBigEndian) {
594 val = buffer[offset] << 8;
595 val |= buffer[offset + 1];
597 val = buffer[offset];
598 val |= buffer[offset + 1] << 8;
605 Buffer.prototype.readUInt16LE = function(offset, noAssert) {
607 checkOffset(offset, 2, this.length);
608 return readUInt16(this, offset, false, noAssert);
612 Buffer.prototype.readUInt16BE = function(offset, noAssert) {
614 checkOffset(offset, 2, this.length);
615 return readUInt16(this, offset, true, noAssert);
619 function readUInt32(buffer, offset, isBigEndian, noAssert) {
623 val = buffer[offset + 1] << 16;
624 val |= buffer[offset + 2] << 8;
625 val |= buffer[offset + 3];
626 val = val + (buffer[offset] << 24 >>> 0);
628 val = buffer[offset + 2] << 16;
629 val |= buffer[offset + 1] << 8;
630 val |= buffer[offset];
631 val = val + (buffer[offset + 3] << 24 >>> 0);
638 Buffer.prototype.readUInt32LE = function(offset, noAssert) {
640 checkOffset(offset, 4, this.length);
641 return readUInt32(this, offset, false, noAssert);
645 Buffer.prototype.readUInt32BE = function(offset, noAssert) {
647 checkOffset(offset, 4, this.length);
648 return readUInt32(this, offset, true, noAssert);
653 * Signed integer types, yay team! A reminder on how two's complement actually
654 * works. The first bit is the signed bit, i.e. tells us whether or not the
655 * number should be positive or negative. If the two's complement value is
656 * positive, then we're done, as it's equivalent to the unsigned representation.
658 * Now if the number is positive, you're pretty much done, you can just leverage
659 * the unsigned translations and return those. Unfortunately, negative numbers
660 * aren't quite that straightforward.
662 * At first glance, one might be inclined to use the traditional formula to
663 * translate binary numbers between the positive and negative values in two's
664 * complement. (Though it doesn't quite work for the most negative value)
666 * - invert all the bits
667 * - add one to the result
669 * Of course, this doesn't quite work in Javascript. Take for example the value
670 * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of
671 * course, Javascript will do the following:
676 * Whoh there, Javascript, that's not quite right. But wait, according to
677 * Javascript that's perfectly correct. When Javascript ends up seeing the
678 * constant 0xff80, it has no notion that it is actually a signed number. It
679 * assumes that we've input the unsigned value 0xff80. Thus, when it does the
680 * binary negation, it casts it into a signed value, (positive 0xff80). Then
681 * when you perform binary negation on that, it turns it into a negative number.
683 * Instead, we're going to have to use the following general formula, that works
684 * in a rather Javascript friendly way. I'm glad we don't support this kind of
685 * weird numbering scheme in the kernel.
687 * (BIT-MAX - (unsigned)val + 1) * -1
689 * The astute observer, may think that this doesn't make sense for 8-bit numbers
690 * (really it isn't necessary for them). However, when you get 16-bit numbers,
691 * you do. Let's go back to our prior example and see how this will look:
693 * (0xffff - 0xff80 + 1) * -1
698 Buffer.prototype.readInt8 = function(offset, noAssert) {
700 checkOffset(offset, 1, this.length);
701 if (!(this[offset] & 0x80))
702 return (this[offset]);
703 return ((0xff - this[offset] + 1) * -1);
707 function readInt16(buffer, offset, isBigEndian) {
708 var val = readUInt16(buffer, offset, isBigEndian);
712 return (0xffff - val + 1) * -1;
716 Buffer.prototype.readInt16LE = function(offset, noAssert) {
718 checkOffset(offset, 2, this.length);
719 return readInt16(this, offset, false);
723 Buffer.prototype.readInt16BE = function(offset, noAssert) {
725 checkOffset(offset, 2, this.length);
726 return readInt16(this, offset, true);
730 function readInt32(buffer, offset, isBigEndian) {
731 var val = readUInt32(buffer, offset, isBigEndian);
733 if (!(val & 0x80000000))
735 return (0xffffffff - val + 1) * -1;
739 Buffer.prototype.readInt32LE = function(offset, noAssert) {
741 checkOffset(offset, 4, this.length);
742 return readInt32(this, offset, false);
746 Buffer.prototype.readInt32BE = function(offset, noAssert) {
748 checkOffset(offset, 4, this.length);
749 return readInt32(this, offset, true);
752 Buffer.prototype.readFloatLE = function(offset, noAssert) {
754 checkOffset(offset, 4, this.length);
755 return this.parent.readFloatLE(this.offset + offset, !!noAssert);
759 Buffer.prototype.readFloatBE = function(offset, noAssert) {
761 checkOffset(offset, 4, this.length);
762 return this.parent.readFloatBE(this.offset + offset, !!noAssert);
766 Buffer.prototype.readDoubleLE = function(offset, noAssert) {
768 checkOffset(offset, 8, this.length);
769 return this.parent.readDoubleLE(this.offset + offset, !!noAssert);
773 Buffer.prototype.readDoubleBE = function(offset, noAssert) {
775 checkOffset(offset, 8, this.length);
776 return this.parent.readDoubleBE(this.offset + offset, !!noAssert);
780 function checkInt(buffer, value, offset, ext, max, min) {
781 if ((value % 1) !== 0 || value > max || value < min)
782 throw TypeError('value is out of bounds');
783 if ((offset % 1) !== 0 || offset < 0)
784 throw TypeError('offset is not uint');
785 if (offset + ext > buffer.length || buffer.length + offset < 0)
786 throw RangeError('Trying to write outside buffer length');
790 Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
792 checkInt(this, value, offset, 1, 0xff, 0);
793 this[offset] = value;
797 function writeUInt16(buffer, value, offset, isBigEndian) {
799 buffer[offset] = (value & 0xff00) >>> 8;
800 buffer[offset + 1] = value & 0x00ff;
802 buffer[offset + 1] = (value & 0xff00) >>> 8;
803 buffer[offset] = value & 0x00ff;
808 Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
810 checkInt(this, value, offset, 2, 0xffff, 0);
811 writeUInt16(this, value, offset, false);
815 Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
817 checkInt(this, value, offset, 2, 0xffff, 0);
818 writeUInt16(this, value, offset, true);
822 function writeUInt32(buffer, value, offset, isBigEndian) {
824 buffer[offset] = (value >>> 24) & 0xff;
825 buffer[offset + 1] = (value >>> 16) & 0xff;
826 buffer[offset + 2] = (value >>> 8) & 0xff;
827 buffer[offset + 3] = value & 0xff;
829 buffer[offset + 3] = (value >>> 24) & 0xff;
830 buffer[offset + 2] = (value >>> 16) & 0xff;
831 buffer[offset + 1] = (value >>> 8) & 0xff;
832 buffer[offset] = value & 0xff;
837 Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
839 checkInt(this, value, offset, 4, 0xffffffff, 0);
840 writeUInt32(this, value, offset, false);
844 Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
846 checkInt(this, value, offset, 4, 0xffffffff, 0);
847 writeUInt32(this, value, offset, true);
852 * We now move onto our friends in the signed number category. Unlike unsigned
853 * numbers, we're going to have to worry a bit more about how we put values into
854 * arrays. Since we are only worrying about signed 32-bit values, we're in
855 * slightly better shape. Unfortunately, we really can't do our favorite binary
856 * & in this system. It really seems to do the wrong thing. For example:
861 * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of
862 * this aren't treated as a signed number. Ultimately a bad thing.
864 * What we're going to want to do is basically create the unsigned equivalent of
865 * our representation and pass that off to the wuint* functions. To do that
866 * we're going to do the following:
868 * - if the value is positive
869 * we can pass it directly off to the equivalent wuint
870 * - if the value is negative
871 * we do the following computation:
872 * mb + val + 1, where
873 * mb is the maximum unsigned value in that byte size
874 * val is the Javascript negative integer
877 * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If
878 * you do out the computations:
884 * You can then encode this value as the signed version. This is really rather
885 * hacky, but it should work and get the job done which is our goal here.
888 Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
890 checkInt(this, value, offset, 1, 0x7f, -0x80);
891 if (value < 0) value = 0xff + value + 1;
892 this[offset] = value;
896 Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
898 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
899 if (value < 0) value = 0xffff + value + 1;
900 writeUInt16(this, value, offset, false);
904 Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
906 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
907 if (value < 0) value = 0xffff + value + 1;
908 writeUInt16(this, value, offset, true);
912 Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
914 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
915 if (value < 0) value = 0xffffffff + value + 1;
916 writeUInt32(this, value, offset, false);
920 Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
922 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
923 if (value < 0) value = 0xffffffff + value + 1;
924 writeUInt32(this, value, offset, true);
928 Buffer.prototype.writeFloatLE = function(value, offset, noAssert) {
930 checkOffset(offset, 4, this.length);
931 this.parent.writeFloatLE(value, this.offset + offset, !!noAssert);
935 Buffer.prototype.writeFloatBE = function(value, offset, noAssert) {
937 checkOffset(offset, 4, this.length);
938 this.parent.writeFloatBE(value, this.offset + offset, !!noAssert);
942 Buffer.prototype.writeDoubleLE = function(value, offset, noAssert) {
944 checkOffset(offset, 8, this.length);
945 this.parent.writeDoubleLE(value, this.offset + offset, !!noAssert);
949 Buffer.prototype.writeDoubleBE = function(value, offset, noAssert) {
951 checkOffset(offset, 8, this.length);
952 this.parent.writeDoubleBE(value, this.offset + offset, !!noAssert);