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;
33 if (n < 16) return '0' + n.toString(16);
34 return n.toString(16);
38 SlowBuffer.prototype.hexSlice = function(start, end) {
39 var len = this.length;
41 if (!start || start < 0) start = 0;
42 if (!end || end < 0 || end > len) end = len;
45 for (var i = start; i < end; i++) {
46 out += toHex(this[i]);
53 SlowBuffer.prototype.toString = function(encoding, start, end) {
54 encoding = String(encoding || 'utf8').toLowerCase();
56 if (typeof end == 'undefined') end = this.length;
58 // Fastpath empty strings
65 return this.hexSlice(start, end);
69 return this.utf8Slice(start, end);
72 return this.asciiSlice(start, end);
75 return this.binarySlice(start, end);
78 return this.base64Slice(start, end);
84 return this.ucs2Slice(start, end);
87 throw new Error('Unknown encoding: ' + encoding);
92 SlowBuffer.prototype.hexWrite = function(string, offset, length) {
93 offset = +offset || 0;
94 var remaining = this.length - offset;
99 if (length > remaining) {
104 // must be an even number of digits
105 var strLen = string.length;
107 throw new Error('Invalid hex string');
109 if (length > strLen / 2) {
112 for (var i = 0; i < length; i++) {
113 var byte = parseInt(string.substr(i * 2, 2), 16);
114 if (isNaN(byte)) throw new Error('Invalid hex string');
115 this[offset + i] = byte;
117 SlowBuffer._charsWritten = i * 2;
122 SlowBuffer.prototype.write = function(string, offset, length, encoding) {
123 // Support both (string, offset, length, encoding)
124 // and the legacy (string, encoding, offset, length)
125 if (isFinite(offset)) {
126 if (!isFinite(length)) {
137 offset = +offset || 0;
138 var remaining = this.length - offset;
143 if (length > remaining) {
147 encoding = String(encoding || 'utf8').toLowerCase();
151 return this.hexWrite(string, offset, length);
155 return this.utf8Write(string, offset, length);
158 return this.asciiWrite(string, offset, length);
161 return this.binaryWrite(string, offset, length);
164 return this.base64Write(string, offset, length);
170 return this.ucs2Write(string, offset, length);
173 throw new Error('Unknown encoding: ' + encoding);
179 SlowBuffer.prototype.slice = function(start, end) {
180 if (end === undefined) end = this.length;
182 if (end > this.length) {
183 throw new Error('oob');
186 throw new Error('oob');
189 return new Buffer(this, end - start, +start);
193 function coerce(length) {
194 // Coerce length to a number (possibly NaN), round up
195 // in case it's fractional (e.g. 123.456). Since NaN
196 // comparisons are always false, use to return zero.
197 length = Math.ceil(+length);
198 return length > 0 ? length : 0;
202 var zeroBuffer = new SlowBuffer(0);
205 function Buffer(subject, encoding, offset) {
206 if (!(this instanceof Buffer)) {
207 return new Buffer(subject, encoding, offset);
213 if (typeof offset === 'number') {
214 if (!Buffer.isBuffer(subject)) {
215 throw new Error('First argument must be a Buffer when slicing');
218 this.length = coerce(encoding);
219 this.parent = subject.parent ? subject.parent : subject;
220 this.offset = offset;
223 switch (type = typeof subject) {
225 this.length = coerce(subject);
229 this.length = Buffer.byteLength(subject, encoding);
232 case 'object': // Assume object is an array
233 this.length = coerce(subject.length);
237 throw new Error('First argument needs to be a number, ' +
241 if (this.length > Buffer.poolSize) {
242 // Big buffer, just alloc one.
243 this.parent = new SlowBuffer(this.length);
246 } else if (this.length > 0) {
248 if (!pool || pool.length - pool.used < this.length) allocPool();
250 this.offset = pool.used;
251 pool.used += this.length;
252 if (pool.used & 7) pool.used = (pool.used + 8) & ~7;
255 // Zero-length buffer
256 this.parent = zeroBuffer;
260 // Treat array-ish objects as a byte array.
261 if (isArrayIsh(subject)) {
262 for (var i = 0; i < this.length; i++) {
263 this.parent[i + this.offset] = subject[i];
265 } else if (type == 'string') {
267 this.length = this.write(subject, 0, encoding);
271 SlowBuffer.makeFastBuffer(this.parent, this, this.offset, this.length);
274 function isArrayIsh(subject) {
275 return Array.isArray(subject) || Buffer.isBuffer(subject) ||
276 subject && typeof subject === 'object' &&
277 typeof subject.length === 'number';
280 exports.SlowBuffer = SlowBuffer;
281 exports.Buffer = Buffer;
284 Buffer.isEncoding = function(encoding) {
285 switch (encoding && encoding.toLowerCase()) {
306 Buffer.poolSize = 8 * 1024;
309 function allocPool() {
310 pool = new SlowBuffer(Buffer.poolSize);
316 Buffer.isBuffer = function isBuffer(b) {
317 return b instanceof Buffer;
322 Buffer.prototype.inspect = function inspect() {
325 name = this.constructor.name;
327 for (var i = 0; i < len; i++) {
328 out[i] = toHex(this[i]);
329 if (i == exports.INSPECT_MAX_BYTES) {
335 return '<' + name + ' ' + out.join(' ') + '>';
339 Buffer.prototype.get = function get(i) {
340 if (i < 0 || i >= this.length) throw new Error('oob');
341 return this.parent[this.offset + i];
345 Buffer.prototype.set = function set(i, v) {
346 if (i < 0 || i >= this.length) throw new Error('oob');
347 return this.parent[this.offset + i] = v;
351 // write(string, offset = 0, length = buffer.length-offset, encoding = 'utf8')
352 Buffer.prototype.write = function(string, offset, length, encoding) {
353 // Support both (string, offset, length, encoding)
354 // and the legacy (string, encoding, offset, length)
355 if (isFinite(offset)) {
356 if (!isFinite(length)) {
367 offset = +offset || 0;
368 var remaining = this.length - offset;
373 if (length > remaining) {
377 encoding = String(encoding || 'utf8').toLowerCase();
382 ret = this.parent.hexWrite(string, this.offset + offset, length);
387 ret = this.parent.utf8Write(string, this.offset + offset, length);
391 ret = this.parent.asciiWrite(string, this.offset + offset, length);
395 ret = this.parent.binaryWrite(string, this.offset + offset, length);
399 // Warning: maxLength not taken into account in base64Write
400 ret = this.parent.base64Write(string, this.offset + offset, length);
407 ret = this.parent.ucs2Write(string, this.offset + offset, length);
411 throw new Error('Unknown encoding: ' + encoding);
414 Buffer._charsWritten = SlowBuffer._charsWritten;
420 Buffer.prototype.toJSON = function() {
421 return Array.prototype.slice.call(this, 0);
425 // toString(encoding, start=0, end=buffer.length)
426 Buffer.prototype.toString = function(encoding, start, end) {
427 encoding = String(encoding || 'utf8').toLowerCase();
429 if (typeof start == 'undefined' || start < 0) {
431 } else if (start > this.length) {
435 if (typeof end == 'undefined' || end > this.length) {
437 } else if (end < 0) {
441 start = start + this.offset;
442 end = end + this.offset;
446 return this.parent.hexSlice(start, end);
450 return this.parent.utf8Slice(start, end);
453 return this.parent.asciiSlice(start, end);
456 return this.parent.binarySlice(start, end);
459 return this.parent.base64Slice(start, end);
465 return this.parent.ucs2Slice(start, end);
468 throw new Error('Unknown encoding: ' + encoding);
474 Buffer.byteLength = SlowBuffer.byteLength;
477 // fill(value, start=0, end=buffer.length)
478 Buffer.prototype.fill = function fill(value, start, end) {
479 value || (value = 0);
480 start || (start = 0);
481 end || (end = this.length);
483 if (typeof value === 'string') {
484 value = value.charCodeAt(0);
486 if (!(typeof value === 'number') || isNaN(value)) {
487 throw new Error('value is not a number');
490 if (end < start) throw new Error('end < start');
492 // Fill 0 bytes; we're done
493 if (end === start) return 0;
494 if (this.length == 0) return 0;
496 if (start < 0 || start >= this.length) {
497 throw new Error('start out of bounds');
500 if (end < 0 || end > this.length) {
501 throw new Error('end out of bounds');
504 return this.parent.fill(value,
510 Buffer.concat = function(list, length) {
511 if (!Array.isArray(list)) {
512 throw new Error('Usage: Buffer.concat(list, [length])');
515 if (list.length === 0) {
516 return new Buffer(0);
517 } else if (list.length === 1) {
521 if (typeof length !== 'number') {
523 for (var i = 0; i < list.length; i++) {
525 length += buf.length;
529 var buffer = new Buffer(length);
531 for (var i = 0; i < list.length; i++) {
533 buf.copy(buffer, pos);
542 // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
543 Buffer.prototype.copy = function(target, target_start, start, end) {
544 // set undefined/NaN or out of bounds values equal to their default
545 if (!(target_start >= 0)) target_start = 0;
546 if (!(start >= 0)) start = 0;
547 if (!(end < this.length)) end = this.length;
549 // Copy 0 bytes; we're done
551 target.length === 0 ||
557 throw new RangeError('sourceEnd < sourceStart');
559 if (target_start >= target.length)
560 throw new RangeError('targetStart out of bounds');
562 if (target.length - target_start < end - start)
563 end = target.length - target_start + start;
565 return this.parent.copy(target.parent || target,
566 target_start + (target.offset || 0),
573 Buffer.prototype.slice = function(start, end) {
574 if (end === undefined) end = this.length;
575 if (end > this.length) throw new Error('oob');
576 if (start > end) throw new Error('oob');
577 if (start < 0) throw new Error('start out of bounds');
578 return new Buffer(this.parent, end - start, +start + this.offset);
582 // Legacy methods for backwards compatibility.
584 Buffer.prototype.utf8Slice = function(start, end) {
585 return this.toString('utf8', start, end);
588 Buffer.prototype.binarySlice = function(start, end) {
589 return this.toString('binary', start, end);
592 Buffer.prototype.asciiSlice = function(start, end) {
593 return this.toString('ascii', start, end);
596 Buffer.prototype.utf8Write = function(string, offset) {
597 return this.write(string, offset, 'utf8');
600 Buffer.prototype.binaryWrite = function(string, offset) {
601 return this.write(string, offset, 'binary');
604 Buffer.prototype.asciiWrite = function(string, offset) {
605 return this.write(string, offset, 'ascii');
610 * Need to make sure that buffer isn't trying to write out of bounds.
611 * This check is far too slow internally for fast buffers.
613 function checkOffset(offset, ext, length) {
614 if ((offset % 1) !== 0 || offset < 0)
615 throw new RangeError('offset is not uint');
616 if (offset + ext > length)
617 throw new RangeError('Trying to access beyond buffer length');
621 Buffer.prototype.readUInt8 = function(offset, noAssert) {
623 checkOffset(offset, 1, this.length);
628 function readUInt16(buffer, offset, isBigEndian) {
631 val = buffer[offset] << 8;
632 val |= buffer[offset + 1];
634 val = buffer[offset];
635 val |= buffer[offset + 1] << 8;
642 Buffer.prototype.readUInt16LE = function(offset, noAssert) {
644 checkOffset(offset, 2, this.length);
645 return readUInt16(this, offset, false, noAssert);
649 Buffer.prototype.readUInt16BE = function(offset, noAssert) {
651 checkOffset(offset, 2, this.length);
652 return readUInt16(this, offset, true, noAssert);
656 function readUInt32(buffer, offset, isBigEndian, noAssert) {
660 val = buffer[offset + 1] << 16;
661 val |= buffer[offset + 2] << 8;
662 val |= buffer[offset + 3];
663 val = val + (buffer[offset] << 24 >>> 0);
665 val = buffer[offset + 2] << 16;
666 val |= buffer[offset + 1] << 8;
667 val |= buffer[offset];
668 val = val + (buffer[offset + 3] << 24 >>> 0);
675 Buffer.prototype.readUInt32LE = function(offset, noAssert) {
677 checkOffset(offset, 4, this.length);
678 return readUInt32(this, offset, false, noAssert);
682 Buffer.prototype.readUInt32BE = function(offset, noAssert) {
684 checkOffset(offset, 4, this.length);
685 return readUInt32(this, offset, true, noAssert);
690 * Signed integer types, yay team! A reminder on how two's complement actually
691 * works. The first bit is the signed bit, i.e. tells us whether or not the
692 * number should be positive or negative. If the two's complement value is
693 * positive, then we're done, as it's equivalent to the unsigned representation.
695 * Now if the number is positive, you're pretty much done, you can just leverage
696 * the unsigned translations and return those. Unfortunately, negative numbers
697 * aren't quite that straightforward.
699 * At first glance, one might be inclined to use the traditional formula to
700 * translate binary numbers between the positive and negative values in two's
701 * complement. (Though it doesn't quite work for the most negative value)
703 * - invert all the bits
704 * - add one to the result
706 * Of course, this doesn't quite work in Javascript. Take for example the value
707 * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of
708 * course, Javascript will do the following:
713 * Whoh there, Javascript, that's not quite right. But wait, according to
714 * Javascript that's perfectly correct. When Javascript ends up seeing the
715 * constant 0xff80, it has no notion that it is actually a signed number. It
716 * assumes that we've input the unsigned value 0xff80. Thus, when it does the
717 * binary negation, it casts it into a signed value, (positive 0xff80). Then
718 * when you perform binary negation on that, it turns it into a negative number.
720 * Instead, we're going to have to use the following general formula, that works
721 * in a rather Javascript friendly way. I'm glad we don't support this kind of
722 * weird numbering scheme in the kernel.
724 * (BIT-MAX - (unsigned)val + 1) * -1
726 * The astute observer, may think that this doesn't make sense for 8-bit numbers
727 * (really it isn't necessary for them). However, when you get 16-bit numbers,
728 * you do. Let's go back to our prior example and see how this will look:
730 * (0xffff - 0xff80 + 1) * -1
735 Buffer.prototype.readInt8 = function(offset, noAssert) {
737 checkOffset(offset, 1, this.length);
738 if (!(this[offset] & 0x80))
739 return (this[offset]);
740 return ((0xff - this[offset] + 1) * -1);
744 function readInt16(buffer, offset, isBigEndian) {
745 var val = readUInt16(buffer, offset, isBigEndian);
749 return (0xffff - val + 1) * -1;
753 Buffer.prototype.readInt16LE = function(offset, noAssert) {
755 checkOffset(offset, 2, this.length);
756 return readInt16(this, offset, false);
760 Buffer.prototype.readInt16BE = function(offset, noAssert) {
762 checkOffset(offset, 2, this.length);
763 return readInt16(this, offset, true);
767 function readInt32(buffer, offset, isBigEndian) {
768 var val = readUInt32(buffer, offset, isBigEndian);
770 if (!(val & 0x80000000))
772 return (0xffffffff - val + 1) * -1;
776 Buffer.prototype.readInt32LE = function(offset, noAssert) {
778 checkOffset(offset, 2, this.length);
779 return readInt32(this, offset, false);
783 Buffer.prototype.readInt32BE = function(offset, noAssert) {
785 checkOffset(offset, 2, this.length);
786 return readInt32(this, offset, true);
789 Buffer.prototype.readFloatLE = function(offset, noAssert) {
791 checkOffset(offset, 4, this.length);
792 return this.parent.readFloatLE(this.offset + offset, !!noAssert);
796 Buffer.prototype.readFloatBE = function(offset, noAssert) {
798 checkOffset(offset, 4, this.length);
799 return this.parent.readFloatBE(this.offset + offset, !!noAssert);
803 Buffer.prototype.readDoubleLE = function(offset, noAssert) {
805 checkOffset(offset, 8, this.length);
806 return this.parent.readDoubleLE(this.offset + offset, !!noAssert);
810 Buffer.prototype.readDoubleBE = function(offset, noAssert) {
812 checkOffset(offset, 8, this.length);
813 return this.parent.readDoubleBE(this.offset + offset, !!noAssert);
817 function checkInt(buffer, value, offset, ext, max, min) {
818 if ((value % 1) !== 0 || value > max || value < min)
819 throw TypeError('value is out of bounds');
820 if ((offset % 1) !== 0 || offset < 0)
821 throw TypeError('offset is not uint');
822 if (offset + ext > buffer.length || buffer.length + offset < 0)
823 throw RangeError('Trying to write outside buffer length');
827 Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
829 checkInt(this, value, offset, 1, 0xff, 0);
830 this[offset] = value;
834 function writeUInt16(buffer, value, offset, isBigEndian) {
836 buffer[offset] = (value & 0xff00) >>> 8;
837 buffer[offset + 1] = value & 0x00ff;
839 buffer[offset + 1] = (value & 0xff00) >>> 8;
840 buffer[offset] = value & 0x00ff;
845 Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
847 checkInt(this, value, offset, 2, 0xffff, 0);
848 writeUInt16(this, value, offset, false);
852 Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
854 checkInt(this, value, offset, 2, 0xffff, 0);
855 writeUInt16(this, value, offset, true);
859 function writeUInt32(buffer, value, offset, isBigEndian) {
861 buffer[offset] = (value >>> 24) & 0xff;
862 buffer[offset + 1] = (value >>> 16) & 0xff;
863 buffer[offset + 2] = (value >>> 8) & 0xff;
864 buffer[offset + 3] = value & 0xff;
866 buffer[offset + 3] = (value >>> 24) & 0xff;
867 buffer[offset + 2] = (value >>> 16) & 0xff;
868 buffer[offset + 1] = (value >>> 8) & 0xff;
869 buffer[offset] = value & 0xff;
874 Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
876 checkInt(this, value, offset, 4, 0xffffffff, 0);
877 writeUInt32(this, value, offset, false);
881 Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
883 checkInt(this, value, offset, 4, 0xffffffff, 0);
884 writeUInt32(this, value, offset, true);
889 * We now move onto our friends in the signed number category. Unlike unsigned
890 * numbers, we're going to have to worry a bit more about how we put values into
891 * arrays. Since we are only worrying about signed 32-bit values, we're in
892 * slightly better shape. Unfortunately, we really can't do our favorite binary
893 * & in this system. It really seems to do the wrong thing. For example:
898 * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of
899 * this aren't treated as a signed number. Ultimately a bad thing.
901 * What we're going to want to do is basically create the unsigned equivalent of
902 * our representation and pass that off to the wuint* functions. To do that
903 * we're going to do the following:
905 * - if the value is positive
906 * we can pass it directly off to the equivalent wuint
907 * - if the value is negative
908 * we do the following computation:
909 * mb + val + 1, where
910 * mb is the maximum unsigned value in that byte size
911 * val is the Javascript negative integer
914 * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If
915 * you do out the computations:
921 * You can then encode this value as the signed version. This is really rather
922 * hacky, but it should work and get the job done which is our goal here.
925 Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
927 checkInt(this, value, offset, 1, 0x7f, -0x80);
928 if (value < 0) value = 0xff + value + 1;
929 this[offset] = value;
933 Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
935 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
936 if (value < 0) value = 0xffff + value + 1;
937 writeUInt16(this, value, offset, false);
941 Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
943 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
944 if (value < 0) value = 0xffff + value + 1;
945 writeUInt16(this, value, offset, true);
949 Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
951 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
952 if (value < 0) value = 0xffffffff + value + 1;
953 writeUInt32(this, value, offset, false);
957 Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
959 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
960 if (value < 0) value = 0xffffffff + value + 1;
961 writeUInt32(this, value, offset, true);
965 Buffer.prototype.writeFloatLE = function(value, offset, noAssert) {
967 checkOffset(offset, 4, this.length);
968 this.parent.writeFloatLE(value, this.offset + offset, !!noAssert);
972 Buffer.prototype.writeFloatBE = function(value, offset, noAssert) {
974 checkOffset(offset, 4, this.length);
975 this.parent.writeFloatBE(value, this.offset + offset, !!noAssert);
979 Buffer.prototype.writeDoubleLE = function(value, offset, noAssert) {
981 checkOffset(offset, 8, this.length);
982 this.parent.writeDoubleLE(value, this.offset + offset, !!noAssert);
986 Buffer.prototype.writeDoubleBE = function(value, offset, noAssert) {
988 checkOffset(offset, 8, this.length);
989 this.parent.writeDoubleBE(value, this.offset + offset, !!noAssert);