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 buffer = process.binding('buffer');
23 var smalloc = process.binding('smalloc');
24 var util = require('util');
25 var alloc = smalloc.alloc;
26 var sliceOnto = smalloc.sliceOnto;
27 var kMaxLength = smalloc.kMaxLength;
30 exports.Buffer = Buffer;
31 exports.SlowBuffer = SlowBuffer;
32 exports.INSPECT_MAX_BYTES = 50;
35 Buffer.poolSize = 8 * 1024;
36 var poolSize, poolOffset, allocPool;
39 function createPool() {
40 poolSize = Buffer.poolSize;
41 allocPool = alloc({}, poolSize);
47 function Buffer(subject, encoding) {
48 if (!util.isBuffer(this))
49 return new Buffer(subject, encoding);
51 if (util.isNumber(subject))
52 this.length = subject > 0 ? subject >>> 0 : 0;
53 else if (util.isString(subject))
54 this.length = Buffer.byteLength(subject, encoding = encoding || 'utf8');
55 else if (util.isObject(subject))
56 this.length = +subject.length > 0 ? Math.floor(+subject.length) : 0;
58 throw new TypeError('must start with number, buffer, array or string');
60 if (this.length > kMaxLength) {
61 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
62 'size: 0x' + kMaxLength.toString(16) + ' bytes');
65 if (this.length <= (Buffer.poolSize >>> 1) && this.length > 0) {
66 if (this.length > poolSize - poolOffset)
68 this.parent = sliceOnto(allocPool,
71 poolOffset + this.length);
72 poolOffset += this.length;
74 alloc(this, this.length);
77 if (!util.isNumber(subject)) {
78 if (util.isString(subject)) {
79 // In the case of base64 it's possible that the size of the buffer
80 // allocated was slightly too large. In this case we need to rewrite
81 // the length to the actual length written.
82 this.length = this.write(subject, encoding);
84 if (util.isBuffer(subject))
85 subject.copy(this, 0, 0, this.length);
86 else if (util.isNumber(subject.length) || util.isArray(subject))
87 for (var i = 0; i < this.length; i++)
94 function SlowBuffer(length) {
95 length = length >>> 0;
96 if (this.length > kMaxLength) {
97 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
98 'size: 0x' + kMaxLength.toString(16) + ' bytes');
100 var b = new NativeBuffer(length);
106 // Bypass all checks for instantiating unallocated Buffer required for
107 // Objects created in C++. Significantly faster than calling the Buffer
109 function NativeBuffer(length) {
110 this.length = length;
112 NativeBuffer.prototype = Buffer.prototype;
115 // add methods to Buffer prototype
116 buffer.setupBufferJS(NativeBuffer, internal);
121 Buffer.isBuffer = function isBuffer(b) {
122 return util.isBuffer(b);
126 Buffer.isEncoding = function(encoding) {
127 switch ((encoding + '').toLowerCase()) {
147 Buffer.concat = function(list, length) {
148 if (!util.isArray(list))
149 throw new TypeError('Usage: Buffer.concat(list[, length])');
151 if (util.isUndefined(length)) {
153 for (var i = 0; i < list.length; i++)
154 length += list[i].length;
156 length = length >>> 0;
159 if (list.length === 0)
160 return new Buffer(0);
161 else if (list.length === 1)
164 var buffer = new Buffer(length);
166 for (var i = 0; i < list.length; i++) {
168 buf.copy(buffer, pos);
176 Buffer.byteLength = function(str, enc) {
189 ret = str.length * 2;
192 ret = str.length >>> 1;
195 ret = internal.byteLength(str, enc);
201 // pre-set for values that may exist in the future
202 Buffer.prototype.length = undefined;
203 Buffer.prototype.parent = undefined;
206 // toString(encoding, start=0, end=buffer.length)
207 Buffer.prototype.toString = function(encoding, start, end) {
208 var loweredCase = false;
211 end = util.isUndefined(end) ? this.length : end >>> 0;
213 if (!encoding) encoding = 'utf8';
214 if (start < 0) start = 0;
215 if (end > this.length) end = this.length;
216 if (end <= start) return '';
221 return this.hexSlice(start, end);
225 return this.utf8Slice(start, end);
228 return this.asciiSlice(start, end);
231 return this.binarySlice(start, end);
234 return this.base64Slice(start, end);
240 return this.ucs2Slice(start, end);
244 throw new TypeError('Unknown encoding: ' + encoding);
245 encoding = (encoding + '').toLowerCase();
253 Buffer.prototype.inspect = function inspect() {
255 var max = exports.INSPECT_MAX_BYTES;
256 if (this.length > 0) {
257 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
258 if (this.length > max)
261 return '<' + this.constructor.name + ' ' + str + '>';
265 // XXX remove in v0.13
266 Buffer.prototype.get = util.deprecate(function get(offset) {
268 if (offset < 0 || offset >= this.length)
269 throw new RangeError('index out of range');
271 }, '.get() is deprecated. Access using array indexes instead.');
274 // XXX remove in v0.13
275 Buffer.prototype.set = util.deprecate(function set(offset, v) {
277 if (offset < 0 || offset >= this.length)
278 throw new RangeError('index out of range');
279 return this[offset] = v;
280 }, '.set() is deprecated. Set using array indexes instead.');
283 // TODO(trevnorris): fix these checks to follow new standard
284 // write(string, offset = 0, length = buffer.length, encoding = 'utf8')
285 var writeWarned = false;
286 var writeMsg = '.write(string, encoding, offset, length) is deprecated.' +
287 ' Use write(string[, offset[, length]][, encoding]) instead.';
288 Buffer.prototype.write = function(string, offset, length, encoding) {
289 // Buffer#write(string);
290 if (util.isUndefined(offset)) {
292 length = this.length;
295 // Buffer#write(string, encoding)
296 } else if (util.isUndefined(length) && util.isString(offset)) {
298 length = this.length;
301 // Buffer#write(string, offset[, length][, encoding])
302 } else if (isFinite(offset)) {
303 offset = offset >>> 0;
304 if (isFinite(length)) {
305 length = length >>> 0;
306 if (util.isUndefined(encoding))
313 // XXX legacy write(string, encoding, offset, length) - remove in v0.13
316 if (process.throwDeprecation)
317 throw new Error(writeMsg);
318 else if (process.traceDeprecation)
319 console.trace(writeMsg);
321 console.error(writeMsg);
327 offset = length >>> 0;
331 var remaining = this.length - offset;
332 if (util.isUndefined(length) || length > remaining)
335 encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
337 if (string.length > 0 && (length < 0 || offset < 0))
338 throw new RangeError('attempt to write outside buffer bounds');
343 ret = this.hexWrite(string, offset, length);
348 ret = this.utf8Write(string, offset, length);
352 ret = this.asciiWrite(string, offset, length);
356 ret = this.binaryWrite(string, offset, length);
360 // Warning: maxLength not taken into account in base64Write
361 ret = this.base64Write(string, offset, length);
368 ret = this.ucs2Write(string, offset, length);
372 throw new TypeError('Unknown encoding: ' + encoding);
379 Buffer.prototype.toJSON = function() {
382 data: Array.prototype.slice.call(this, 0)
387 // TODO(trevnorris): currently works like Array.prototype.slice(), which
388 // doesn't follow the new standard for throwing on out of range indexes.
389 Buffer.prototype.slice = function(start, end) {
390 var len = this.length;
392 end = util.isUndefined(end) ? len : ~~end;
398 } else if (start > len) {
406 } else if (end > len) {
413 var buf = new NativeBuffer();
414 sliceOnto(this, buf, start, end);
415 buf.length = end - start;
417 buf.parent = util.isUndefined(this.parent) ? this : this.parent;
423 function checkOffset(offset, ext, length) {
424 if (offset + ext > length)
425 throw new RangeError('index out of range');
429 Buffer.prototype.readUInt8 = function(offset, noAssert) {
430 offset = offset >>> 0;
432 checkOffset(offset, 1, this.length);
437 function readUInt16(buffer, offset, isBigEndian) {
440 val = buffer[offset] << 8;
441 val |= buffer[offset + 1];
443 val = buffer[offset];
444 val |= buffer[offset + 1] << 8;
450 Buffer.prototype.readUInt16LE = function(offset, noAssert) {
451 offset = offset >>> 0;
453 checkOffset(offset, 2, this.length);
454 return readUInt16(this, offset, false, noAssert);
458 Buffer.prototype.readUInt16BE = function(offset, noAssert) {
459 offset = offset >>> 0;
461 checkOffset(offset, 2, this.length);
462 return readUInt16(this, offset, true, noAssert);
466 function readUInt32(buffer, offset, isBigEndian) {
469 val = buffer[offset + 1] << 16;
470 val |= buffer[offset + 2] << 8;
471 val |= buffer[offset + 3];
472 val = val + (buffer[offset] << 24 >>> 0);
474 val = buffer[offset + 2] << 16;
475 val |= buffer[offset + 1] << 8;
476 val |= buffer[offset];
477 val = val + (buffer[offset + 3] << 24 >>> 0);
483 Buffer.prototype.readUInt32LE = function(offset, noAssert) {
484 offset = offset >>> 0;
486 checkOffset(offset, 4, this.length);
487 return readUInt32(this, offset, false);
491 Buffer.prototype.readUInt32BE = function(offset, noAssert) {
492 offset = offset >>> 0;
494 checkOffset(offset, 4, this.length);
495 return readUInt32(this, offset, true);
500 * Signed integer types, yay team! A reminder on how two's complement actually
501 * works. The first bit is the signed bit, i.e. tells us whether or not the
502 * number should be positive or negative. If the two's complement value is
503 * positive, then we're done, as it's equivalent to the unsigned representation.
505 * Now if the number is positive, you're pretty much done, you can just leverage
506 * the unsigned translations and return those. Unfortunately, negative numbers
507 * aren't quite that straightforward.
509 * At first glance, one might be inclined to use the traditional formula to
510 * translate binary numbers between the positive and negative values in two's
511 * complement. (Though it doesn't quite work for the most negative value)
513 * - invert all the bits
514 * - add one to the result
516 * Of course, this doesn't quite work in Javascript. Take for example the value
517 * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of
518 * course, Javascript will do the following:
523 * Whoh there, Javascript, that's not quite right. But wait, according to
524 * Javascript that's perfectly correct. When Javascript ends up seeing the
525 * constant 0xff80, it has no notion that it is actually a signed number. It
526 * assumes that we've input the unsigned value 0xff80. Thus, when it does the
527 * binary negation, it casts it into a signed value, (positive 0xff80). Then
528 * when you perform binary negation on that, it turns it into a negative number.
530 * Instead, we're going to have to use the following general formula, that works
531 * in a rather Javascript friendly way. I'm glad we don't support this kind of
532 * weird numbering scheme in the kernel.
534 * (BIT-MAX - (unsigned)val + 1) * -1
536 * The astute observer, may think that this doesn't make sense for 8-bit numbers
537 * (really it isn't necessary for them). However, when you get 16-bit numbers,
538 * you do. Let's go back to our prior example and see how this will look:
540 * (0xffff - 0xff80 + 1) * -1
545 Buffer.prototype.readInt8 = function(offset, noAssert) {
546 offset = offset >>> 0;
548 checkOffset(offset, 1, this.length);
549 var val = this[offset];
550 return !(val & 0x80) ? val : (0xff - val + 1) * -1;
554 function readInt16(buffer, offset, isBigEndian) {
555 var val = readUInt16(buffer, offset, isBigEndian);
556 return !(val & 0x8000) ? val : (0xffff - val + 1) * -1;
560 Buffer.prototype.readInt16LE = function(offset, noAssert) {
561 offset = offset >>> 0;
563 checkOffset(offset, 2, this.length);
564 return readInt16(this, offset, false);
568 Buffer.prototype.readInt16BE = function(offset, noAssert) {
569 offset = offset >>> 0;
571 checkOffset(offset, 2, this.length);
572 return readInt16(this, offset, true);
576 function readInt32(buffer, offset, isBigEndian) {
577 var val = readUInt32(buffer, offset, isBigEndian);
578 return !(val & 0x80000000) ? val : (0xffffffff - val + 1) * -1;
582 Buffer.prototype.readInt32LE = function(offset, noAssert) {
583 offset = offset >>> 0;
585 checkOffset(offset, 4, this.length);
586 return readInt32(this, offset, false);
590 Buffer.prototype.readInt32BE = function(offset, noAssert) {
591 offset = offset >>> 0;
593 checkOffset(offset, 4, this.length);
594 return readInt32(this, offset, true);
598 function checkInt(buffer, value, offset, ext, max, min) {
599 if (!(buffer instanceof Buffer))
600 throw new TypeError('buffer must be a Buffer instance');
601 if (value > max || value < min)
602 throw new TypeError('value is out of bounds');
603 if (offset + ext > buffer.length)
604 throw new RangeError('index out of range');
608 Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
610 offset = offset >>> 0;
612 checkInt(this, value, offset, 1, 0xff, 0);
613 this[offset] = value;
618 function writeUInt16(buffer, value, offset, isBigEndian) {
620 buffer[offset] = (value & 0xff00) >>> 8;
621 buffer[offset + 1] = value & 0x00ff;
623 buffer[offset + 1] = (value & 0xff00) >>> 8;
624 buffer[offset] = value & 0x00ff;
630 Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
632 offset = offset >>> 0;
634 checkInt(this, value, offset, 2, 0xffff, 0);
635 return writeUInt16(this, value, offset, false);
639 Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
641 offset = offset >>> 0;
643 checkInt(this, value, offset, 2, 0xffff, 0);
644 return writeUInt16(this, value, offset, true);
648 function writeUInt32(buffer, value, offset, isBigEndian) {
650 buffer[offset] = (value >>> 24) & 0xff;
651 buffer[offset + 1] = (value >>> 16) & 0xff;
652 buffer[offset + 2] = (value >>> 8) & 0xff;
653 buffer[offset + 3] = value & 0xff;
655 buffer[offset + 3] = (value >>> 24) & 0xff;
656 buffer[offset + 2] = (value >>> 16) & 0xff;
657 buffer[offset + 1] = (value >>> 8) & 0xff;
658 buffer[offset] = value & 0xff;
664 Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
666 offset = offset >>> 0;
668 checkInt(this, value, offset, 4, 0xffffffff, 0);
669 return writeUInt32(this, value, offset, false);
673 Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
675 offset = offset >>> 0;
677 checkInt(this, value, offset, 4, 0xffffffff, 0);
678 return writeUInt32(this, value, offset, true);
683 * We now move onto our friends in the signed number category. Unlike unsigned
684 * numbers, we're going to have to worry a bit more about how we put values into
685 * arrays. Since we are only worrying about signed 32-bit values, we're in
686 * slightly better shape. Unfortunately, we really can't do our favorite binary
687 * & in this system. It really seems to do the wrong thing. For example:
692 * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of
693 * this aren't treated as a signed number. Ultimately a bad thing.
695 * What we're going to want to do is basically create the unsigned equivalent of
696 * our representation and pass that off to the wuint* functions. To do that
697 * we're going to do the following:
699 * - if the value is positive
700 * we can pass it directly off to the equivalent wuint
701 * - if the value is negative
702 * we do the following computation:
703 * mb + val + 1, where
704 * mb is the maximum unsigned value in that byte size
705 * val is the Javascript negative integer
708 * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If
709 * you do out the computations:
715 * You can then encode this value as the signed version. This is really rather
716 * hacky, but it should work and get the job done which is our goal here.
719 Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
721 offset = offset >>> 0;
723 checkInt(this, value, offset, 1, 0x7f, -0x80);
724 if (value < 0) value = 0xff + value + 1;
725 this[offset] = value;
730 Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
732 offset = offset >>> 0;
734 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
735 if (value < 0) value = 0xffff + value + 1;
736 return writeUInt16(this, value, offset, false);
740 Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
742 offset = offset >>> 0;
744 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
745 if (value < 0) value = 0xffff + value + 1;
746 return writeUInt16(this, value, offset, true);
750 Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
752 offset = offset >>> 0;
754 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
755 if (value < 0) value = 0xffffffff + value + 1;
756 return writeUInt32(this, value, offset, false);
760 Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
762 offset = offset >>> 0;
764 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
765 if (value < 0) value = 0xffffffff + value + 1;
766 return writeUInt32(this, value, offset, true);