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 = Buffer.poolSize;
38 var allocPool = alloc({}, poolSize);
41 function createPool() {
42 poolSize = Buffer.poolSize;
43 allocPool = alloc({}, poolSize);
48 function Buffer(subject, encoding) {
49 if (!util.isBuffer(this))
50 return new Buffer(subject, encoding);
52 if (util.isNumber(subject))
53 this.length = subject > 0 ? Math.floor(subject) : 0;
54 else if (util.isString(subject))
55 this.length = Buffer.byteLength(subject, encoding = encoding || 'utf8');
56 else if (util.isObject(subject))
57 this.length = +subject.length > 0 ? Math.floor(+subject.length) : 0;
59 throw new TypeError('must start with number, buffer, array or string');
61 if (this.length > kMaxLength)
62 throw new RangeError('length > kMaxLength');
64 if (this.length < Buffer.poolSize / 2 && this.length > 0) {
65 if (this.length > poolSize - poolOffset)
67 this.parent = sliceOnto(allocPool,
70 poolOffset + this.length);
71 poolOffset += this.length;
73 alloc(this, this.length);
76 if (!util.isNumber(subject)) {
77 if (util.isString(subject)) {
78 // FIXME: the number of bytes hasn't changed, so why change the length?
79 this.length = this.write(subject, 0, encoding);
81 if (util.isBuffer(subject))
82 subject.copy(this, 0, 0, this.length);
83 else if (util.isNumber(subject.length) || util.isArray(subject))
84 for (var i = 0; i < this.length; i++)
91 function SlowBuffer(length) {
92 length = length >>> 0;
93 if (length > kMaxLength)
94 throw new RangeError('length > kMaxLength');
95 var b = new NativeBuffer(length);
101 // Bypass all checks for instantiating unallocated Buffer required for
102 // Objects created in C++. Significantly faster than calling the Buffer
104 function NativeBuffer(length) {
105 this.length = length;
107 NativeBuffer.prototype = Buffer.prototype;
110 // add methods to Buffer prototype
111 buffer.setupBufferJS(NativeBuffer, internal);
116 Buffer.isBuffer = function isBuffer(b) {
117 return util.isBuffer(b);
121 Buffer.isEncoding = function(encoding) {
122 switch ((encoding + '').toLowerCase()) {
142 Buffer.concat = function(list, length) {
143 if (!util.isArray(list))
144 throw new TypeError('Usage: Buffer.concat(list[, length])');
146 if (util.isUndefined(length)) {
148 for (var i = 0; i < list.length; i++)
149 length += list[i].length;
154 if (length < 0) length = 0;
156 if (list.length === 0)
157 return new Buffer(0);
158 else if (list.length === 1)
161 var buffer = new Buffer(length);
163 for (var i = 0; i < list.length; i++) {
165 buf.copy(buffer, pos);
173 Buffer.byteLength = function(str, enc) {
186 ret = str.length * 2;
189 ret = str.length >>> 1;
192 ret = internal.byteLength(str, enc);
198 // pre-set for values that may exist in the future
199 Buffer.prototype.length = undefined;
200 Buffer.prototype.parent = undefined;
203 // toString(encoding, start=0, end=buffer.length)
204 Buffer.prototype.toString = function(encoding, start, end) {
205 encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
208 end = util.isUndefined(end) ? this.length : ~~end;
210 if (start < 0) start = 0;
211 if (end > this.length) end = this.length;
212 if (end <= start) return '';
216 return this.hexSlice(start, end);
220 return this.utf8Slice(start, end);
223 return this.asciiSlice(start, end);
226 return this.binarySlice(start, end);
229 return this.base64Slice(start, end);
235 return this.ucs2Slice(start, end);
238 throw new TypeError('Unknown encoding: ' + encoding);
244 Buffer.prototype.inspect = function inspect() {
246 var max = exports.INSPECT_MAX_BYTES;
247 if (this.length > 0) {
248 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
249 if (this.length > max)
252 return '<' + this.constructor.name + ' ' + str + '>';
256 // XXX remove in v0.13
257 Buffer.prototype.get = util.deprecate(function get(offset) {
259 if (offset < 0 || offset >= this.length)
260 throw new RangeError('index out of range');
262 }, '.get() is deprecated. Access using array indexes instead.');
265 // XXX remove in v0.13
266 Buffer.prototype.set = util.deprecate(function set(offset, v) {
268 if (offset < 0 || offset >= this.length)
269 throw new RangeError('index out of range');
270 return this[offset] = v;
271 }, '.set() is deprecated. Set using array indexes instead.');
274 // TODO(trevnorris): fix these checks to follow new standard
275 // write(string, offset = 0, length = buffer.length, encoding = 'utf8')
276 var writeWarned = false;
277 var writeMsg = '.write(string, encoding, offset, length) is deprecated.' +
278 ' Use write(string, offset, length, encoding) instead.';
279 Buffer.prototype.write = function(string, offset, length, encoding) {
280 // allow write(string, encoding)
281 if (util.isString(offset) && util.isUndefined(length)) {
285 // allow write(string, offset[, length], encoding)
286 } else if (isFinite(offset)) {
288 if (isFinite(length)) {
295 // XXX legacy write(string, encoding, offset, length) - remove in v0.13
298 if (process.throwDeprecation)
299 throw new Error(writeMsg);
300 else if (process.traceDeprecation)
301 console.trace(writeMsg);
303 console.error(writeMsg);
313 var remaining = this.length - offset;
314 if (util.isUndefined(length) || length > remaining)
317 encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
319 if (string.length > 0 && (length < 0 || offset < 0))
320 throw new RangeError('attempt to write beyond buffer bounds');
325 ret = this.hexWrite(string, offset, length);
330 ret = this.utf8Write(string, offset, length);
334 ret = this.asciiWrite(string, offset, length);
338 ret = this.binaryWrite(string, offset, length);
342 // Warning: maxLength not taken into account in base64Write
343 ret = this.base64Write(string, offset, length);
350 ret = this.ucs2Write(string, offset, length);
354 throw new TypeError('Unknown encoding: ' + encoding);
361 Buffer.prototype.toJSON = function() {
364 data: Array.prototype.slice.call(this, 0)
369 // TODO(trevnorris): currently works like Array.prototype.slice(), which
370 // doesn't follow the new standard for throwing on out of range indexes.
371 Buffer.prototype.slice = function(start, end) {
372 var len = this.length;
374 end = util.isUndefined(end) ? len : ~~end;
380 } else if (start > len) {
388 } else if (end > len) {
395 var buf = new NativeBuffer();
396 sliceOnto(this, buf, start, end);
397 buf.length = end - start;
399 buf.parent = util.isUndefined(this.parent) ? this : this.parent;
405 function checkOffset(offset, ext, length) {
406 if (offset < 0 || offset + ext > length)
407 throw new RangeError('index out of range');
411 Buffer.prototype.readUInt8 = function(offset, noAssert) {
414 checkOffset(offset, 1, this.length);
419 function readUInt16(buffer, offset, isBigEndian) {
422 val = buffer[offset] << 8;
423 val |= buffer[offset + 1];
425 val = buffer[offset];
426 val |= buffer[offset + 1] << 8;
432 Buffer.prototype.readUInt16LE = function(offset, noAssert) {
435 checkOffset(offset, 2, this.length);
436 return readUInt16(this, offset, false, noAssert);
440 Buffer.prototype.readUInt16BE = function(offset, noAssert) {
443 checkOffset(offset, 2, this.length);
444 return readUInt16(this, offset, true, noAssert);
448 function readUInt32(buffer, offset, isBigEndian) {
451 val = buffer[offset + 1] << 16;
452 val |= buffer[offset + 2] << 8;
453 val |= buffer[offset + 3];
454 val = val + (buffer[offset] << 24 >>> 0);
456 val = buffer[offset + 2] << 16;
457 val |= buffer[offset + 1] << 8;
458 val |= buffer[offset];
459 val = val + (buffer[offset + 3] << 24 >>> 0);
465 Buffer.prototype.readUInt32LE = function(offset, noAssert) {
468 checkOffset(offset, 4, this.length);
469 return readUInt32(this, offset, false);
473 Buffer.prototype.readUInt32BE = function(offset, noAssert) {
476 checkOffset(offset, 4, this.length);
477 return readUInt32(this, offset, true);
482 * Signed integer types, yay team! A reminder on how two's complement actually
483 * works. The first bit is the signed bit, i.e. tells us whether or not the
484 * number should be positive or negative. If the two's complement value is
485 * positive, then we're done, as it's equivalent to the unsigned representation.
487 * Now if the number is positive, you're pretty much done, you can just leverage
488 * the unsigned translations and return those. Unfortunately, negative numbers
489 * aren't quite that straightforward.
491 * At first glance, one might be inclined to use the traditional formula to
492 * translate binary numbers between the positive and negative values in two's
493 * complement. (Though it doesn't quite work for the most negative value)
495 * - invert all the bits
496 * - add one to the result
498 * Of course, this doesn't quite work in Javascript. Take for example the value
499 * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of
500 * course, Javascript will do the following:
505 * Whoh there, Javascript, that's not quite right. But wait, according to
506 * Javascript that's perfectly correct. When Javascript ends up seeing the
507 * constant 0xff80, it has no notion that it is actually a signed number. It
508 * assumes that we've input the unsigned value 0xff80. Thus, when it does the
509 * binary negation, it casts it into a signed value, (positive 0xff80). Then
510 * when you perform binary negation on that, it turns it into a negative number.
512 * Instead, we're going to have to use the following general formula, that works
513 * in a rather Javascript friendly way. I'm glad we don't support this kind of
514 * weird numbering scheme in the kernel.
516 * (BIT-MAX - (unsigned)val + 1) * -1
518 * The astute observer, may think that this doesn't make sense for 8-bit numbers
519 * (really it isn't necessary for them). However, when you get 16-bit numbers,
520 * you do. Let's go back to our prior example and see how this will look:
522 * (0xffff - 0xff80 + 1) * -1
527 Buffer.prototype.readInt8 = function(offset, noAssert) {
530 checkOffset(offset, 1, this.length);
531 if (!(this[offset] & 0x80))
532 return (this[offset]);
533 return ((0xff - this[offset] + 1) * -1);
537 function readInt16(buffer, offset, isBigEndian) {
538 var val = readUInt16(buffer, offset, isBigEndian);
541 return (0xffff - val + 1) * -1;
545 Buffer.prototype.readInt16LE = function(offset, noAssert) {
548 checkOffset(offset, 2, this.length);
549 return readInt16(this, offset, false);
553 Buffer.prototype.readInt16BE = function(offset, noAssert) {
556 checkOffset(offset, 2, this.length);
557 return readInt16(this, offset, true);
561 function readInt32(buffer, offset, isBigEndian) {
562 var val = readUInt32(buffer, offset, isBigEndian);
563 if (!(val & 0x80000000))
565 return (0xffffffff - val + 1) * -1;
569 Buffer.prototype.readInt32LE = function(offset, noAssert) {
572 checkOffset(offset, 4, this.length);
573 return readInt32(this, offset, false);
577 Buffer.prototype.readInt32BE = function(offset, noAssert) {
580 checkOffset(offset, 4, this.length);
581 return readInt32(this, offset, true);
585 function checkInt(buffer, value, offset, ext, max, min) {
586 if (value > max || value < min)
587 throw new TypeError('value is out of bounds');
588 if (offset < 0 || offset + ext > buffer.length || buffer.length + offset < 0)
589 throw new RangeError('index out of range');
593 Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
597 checkInt(this, value, offset, 1, 0xff, 0);
598 this[offset] = value;
603 function writeUInt16(buffer, value, offset, isBigEndian) {
605 buffer[offset] = (value & 0xff00) >>> 8;
606 buffer[offset + 1] = value & 0x00ff;
608 buffer[offset + 1] = (value & 0xff00) >>> 8;
609 buffer[offset] = value & 0x00ff;
615 Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
619 checkInt(this, value, offset, 2, 0xffff, 0);
620 return writeUInt16(this, value, offset, false);
624 Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
628 checkInt(this, value, offset, 2, 0xffff, 0);
629 return writeUInt16(this, value, offset, true);
633 function writeUInt32(buffer, value, offset, isBigEndian) {
635 buffer[offset] = (value >>> 24) & 0xff;
636 buffer[offset + 1] = (value >>> 16) & 0xff;
637 buffer[offset + 2] = (value >>> 8) & 0xff;
638 buffer[offset + 3] = value & 0xff;
640 buffer[offset + 3] = (value >>> 24) & 0xff;
641 buffer[offset + 2] = (value >>> 16) & 0xff;
642 buffer[offset + 1] = (value >>> 8) & 0xff;
643 buffer[offset] = value & 0xff;
649 Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
653 checkInt(this, value, offset, 4, 0xffffffff, 0);
654 return writeUInt32(this, value, offset, false);
658 Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
662 checkInt(this, value, offset, 4, 0xffffffff, 0);
663 return writeUInt32(this, value, offset, true);
668 * We now move onto our friends in the signed number category. Unlike unsigned
669 * numbers, we're going to have to worry a bit more about how we put values into
670 * arrays. Since we are only worrying about signed 32-bit values, we're in
671 * slightly better shape. Unfortunately, we really can't do our favorite binary
672 * & in this system. It really seems to do the wrong thing. For example:
677 * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of
678 * this aren't treated as a signed number. Ultimately a bad thing.
680 * What we're going to want to do is basically create the unsigned equivalent of
681 * our representation and pass that off to the wuint* functions. To do that
682 * we're going to do the following:
684 * - if the value is positive
685 * we can pass it directly off to the equivalent wuint
686 * - if the value is negative
687 * we do the following computation:
688 * mb + val + 1, where
689 * mb is the maximum unsigned value in that byte size
690 * val is the Javascript negative integer
693 * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If
694 * you do out the computations:
700 * You can then encode this value as the signed version. This is really rather
701 * hacky, but it should work and get the job done which is our goal here.
704 Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
708 checkInt(this, value, offset, 1, 0x7f, -0x80);
709 if (value < 0) value = 0xff + value + 1;
710 this[offset] = value;
715 Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
719 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
720 if (value < 0) value = 0xffff + value + 1;
721 return writeUInt16(this, value, offset, false);
725 Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
729 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
730 if (value < 0) value = 0xffff + value + 1;
731 return writeUInt16(this, value, offset, true);
735 Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
739 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
740 if (value < 0) value = 0xffffffff + value + 1;
741 return writeUInt32(this, value, offset, false);
745 Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
749 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
750 if (value < 0) value = 0xffffffff + value + 1;
751 return writeUInt32(this, value, offset, true);