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;
29 exports.Buffer = Buffer;
30 exports.SlowBuffer = SlowBuffer;
31 exports.INSPECT_MAX_BYTES = 50;
33 // add methods to Buffer prototype
34 buffer.setupBufferJS(Buffer);
36 Buffer.poolSize = 8 * 1024;
37 var poolSize = Buffer.poolSize;
39 var allocPool = alloc({}, poolSize);
42 function createPool() {
43 poolSize = Buffer.poolSize;
44 allocPool = alloc({}, poolSize);
49 function Buffer(subject, encoding) {
50 if (!util.isBuffer(this))
51 return new Buffer(subject, encoding);
53 if (util.isNumber(subject))
54 this.length = subject > 0 ? Math.floor(subject) : 0;
55 else if (util.isString(subject))
56 this.length = Buffer.byteLength(subject, encoding = encoding || 'utf8');
57 else if (util.isObject(subject))
58 this.length = +subject.length > 0 ? Math.floor(+subject.length) : 0;
59 else if (util.isUndefined(subject)) {
60 // undef first arg returns unallocated buffer, also assumes length passed.
61 // this is a stop-gap for now while look for better architecture.
62 // for internal use only.
63 this.length = encoding;
67 throw new TypeError('must start with number, buffer, array or string');
69 if (this.length > kMaxLength)
70 throw new RangeError('length > kMaxLength');
72 if (this.length < Buffer.poolSize / 2 && this.length > 0) {
73 if (this.length > poolSize - poolOffset)
75 this.parent = sliceOnto(allocPool,
78 poolOffset + this.length);
79 poolOffset += this.length;
81 alloc(this, this.length);
84 if (!util.isNumber(subject)) {
85 if (util.isString(subject)) {
86 // FIXME: the number of bytes hasn't changed, so why change the length?
87 this.length = this.write(subject, 0, encoding);
89 if (util.isBuffer(subject))
90 this.copy(subject, 0, 0, this.length);
91 else if (util.isNumber(subject.length) || util.isArray(subject))
92 for (var i = 0; i < this.length; i++)
99 function SlowBuffer(length) {
101 var b = new Buffer(undefined, length);
109 Buffer.isBuffer = function isBuffer(b) {
110 return util.isBuffer(b);
114 Buffer.isEncoding = function(encoding) {
115 switch ((encoding + '').toLowerCase()) {
135 Buffer.concat = function(list, length) {
136 if (!util.isArray(list))
137 throw new TypeError('Usage: Buffer.concat(list[, length])');
139 if (util.isUndefined(length)) {
141 for (var i = 0; i < list.length; i++)
142 length += list[i].length;
147 if (length < 0) length = 0;
149 if (list.length === 0)
150 return new Buffer(0);
151 else if (list.length === 1)
154 var buffer = new Buffer(length);
156 for (var i = 0; i < list.length; i++) {
158 buf.copy(buffer, pos);
166 // pre-set for values that may exist in the future
167 Buffer.prototype.length = undefined;
168 Buffer.prototype.parent = undefined;
171 // toString(encoding, start=0, end=buffer.length)
172 Buffer.prototype.toString = function(encoding, start, end) {
173 encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
176 end = util.isUndefined(end) ? this.length : ~~end;
178 if (start < 0) start = 0;
179 if (end > this.length) end = this.length;
180 if (end <= start) return '';
184 return this.hexSlice(start, end);
188 return this.utf8Slice(start, end);
191 return this.asciiSlice(start, end);
194 return this.binarySlice(start, end);
197 return this.base64Slice(start, end);
203 return this.ucs2Slice(start, end);
206 throw new TypeError('Unknown encoding: ' + encoding);
212 Buffer.prototype.inspect = function inspect() {
215 str = this.hexSlice(0, this.length).match(/.{2}/g).join(' ');
216 return '<' + this.constructor.name + ' ' + str + '>';
220 // XXX remove in v0.13
221 Buffer.prototype.get = util.deprecate(function get(offset) {
223 if (offset < 0 || offset >= this.length)
224 throw new RangeError('index out of range');
226 }, '.get() is deprecated. Access using array indexes instead.');
229 // XXX remove in v0.13
230 Buffer.prototype.set = util.deprecate(function set(offset, v) {
232 if (offset < 0 || offset >= this.length)
233 throw new RangeError('index out of range');
234 return this[offset] = v;
235 }, '.set() is deprecated. Set using array indexes instead.');
238 // TODO(trevnorris): fix these checks to follow new standard
239 // write(string, offset = 0, length = buffer.length, encoding = 'utf8')
240 var writeWarned = false;
241 var writeMsg = '.write(string, encoding, offset, length) is deprecated.' +
242 ' Use write(string, offset, length, encoding) instead.';
243 Buffer.prototype.write = function(string, offset, length, encoding) {
244 // allow write(string, encoding)
245 if (util.isString(offset) && util.isUndefined(length)) {
249 // allow write(string, offset[, length], encoding)
250 } else if (isFinite(offset)) {
252 if (isFinite(length)) {
259 // XXX legacy write(string, encoding, offset, length) - remove in v0.13
262 if (process.throwDeprecation)
263 throw new Error(writeMsg);
264 else if (process.traceDeprecation)
265 console.trace(writeMsg);
267 console.error(writeMsg);
277 var remaining = this.length - offset;
278 if (util.isUndefined(length) || length > remaining)
281 encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
283 if (string.length > 0 && (length < 0 || offset < 0))
284 throw new RangeError('attempt to write beyond buffer bounds');
289 ret = this.hexWrite(string, offset, length);
294 ret = this.utf8Write(string, offset, length);
298 ret = this.asciiWrite(string, offset, length);
302 ret = this.binaryWrite(string, offset, length);
306 // Warning: maxLength not taken into account in base64Write
307 ret = this.base64Write(string, offset, length);
314 ret = this.ucs2Write(string, offset, length);
318 throw new TypeError('Unknown encoding: ' + encoding);
325 Buffer.prototype.toJSON = function() {
328 data: Array.prototype.slice.call(this, 0)
333 // TODO(trevnorris): currently works like Array.prototype.slice(), which
334 // doesn't follow the new standard for throwing on out of range indexes.
335 Buffer.prototype.slice = function(start, end) {
336 var len = this.length;
338 end = util.isUndefined(end) ? len : ~~end;
344 } else if (start > len) {
352 } else if (end > len) {
359 var buf = new Buffer();
360 sliceOnto(this, buf, start, end);
361 buf.length = end - start;
363 buf.parent = util.isUndefined(this.parent) ? this : this.parent;
369 function checkOffset(offset, ext, length) {
370 if (offset < 0 || offset + ext > length)
371 throw new RangeError('index out of range');
375 Buffer.prototype.readUInt8 = function(offset, noAssert) {
378 checkOffset(offset, 1, this.length);
383 function readUInt16(buffer, offset, isBigEndian) {
386 val = buffer[offset] << 8;
387 val |= buffer[offset + 1];
389 val = buffer[offset];
390 val |= buffer[offset + 1] << 8;
396 Buffer.prototype.readUInt16LE = function(offset, noAssert) {
399 checkOffset(offset, 2, this.length);
400 return readUInt16(this, offset, false, noAssert);
404 Buffer.prototype.readUInt16BE = function(offset, noAssert) {
407 checkOffset(offset, 2, this.length);
408 return readUInt16(this, offset, true, noAssert);
412 function readUInt32(buffer, offset, isBigEndian, noAssert) {
415 val = buffer[offset + 1] << 16;
416 val |= buffer[offset + 2] << 8;
417 val |= buffer[offset + 3];
418 val = val + (buffer[offset] << 24 >>> 0);
420 val = buffer[offset + 2] << 16;
421 val |= buffer[offset + 1] << 8;
422 val |= buffer[offset];
423 val = val + (buffer[offset + 3] << 24 >>> 0);
429 Buffer.prototype.readUInt32LE = function(offset, noAssert) {
432 checkOffset(offset, 4, this.length);
433 return readUInt32(this, offset, false, noAssert);
437 Buffer.prototype.readUInt32BE = function(offset, noAssert) {
440 checkOffset(offset, 4, this.length);
441 return readUInt32(this, offset, true, noAssert);
446 * Signed integer types, yay team! A reminder on how two's complement actually
447 * works. The first bit is the signed bit, i.e. tells us whether or not the
448 * number should be positive or negative. If the two's complement value is
449 * positive, then we're done, as it's equivalent to the unsigned representation.
451 * Now if the number is positive, you're pretty much done, you can just leverage
452 * the unsigned translations and return those. Unfortunately, negative numbers
453 * aren't quite that straightforward.
455 * At first glance, one might be inclined to use the traditional formula to
456 * translate binary numbers between the positive and negative values in two's
457 * complement. (Though it doesn't quite work for the most negative value)
459 * - invert all the bits
460 * - add one to the result
462 * Of course, this doesn't quite work in Javascript. Take for example the value
463 * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of
464 * course, Javascript will do the following:
469 * Whoh there, Javascript, that's not quite right. But wait, according to
470 * Javascript that's perfectly correct. When Javascript ends up seeing the
471 * constant 0xff80, it has no notion that it is actually a signed number. It
472 * assumes that we've input the unsigned value 0xff80. Thus, when it does the
473 * binary negation, it casts it into a signed value, (positive 0xff80). Then
474 * when you perform binary negation on that, it turns it into a negative number.
476 * Instead, we're going to have to use the following general formula, that works
477 * in a rather Javascript friendly way. I'm glad we don't support this kind of
478 * weird numbering scheme in the kernel.
480 * (BIT-MAX - (unsigned)val + 1) * -1
482 * The astute observer, may think that this doesn't make sense for 8-bit numbers
483 * (really it isn't necessary for them). However, when you get 16-bit numbers,
484 * you do. Let's go back to our prior example and see how this will look:
486 * (0xffff - 0xff80 + 1) * -1
491 Buffer.prototype.readInt8 = function(offset, noAssert) {
494 checkOffset(offset, 1, this.length);
495 if (!(this[offset] & 0x80))
496 return (this[offset]);
497 return ((0xff - this[offset] + 1) * -1);
501 function readInt16(buffer, offset, isBigEndian) {
502 var val = readUInt16(buffer, offset, isBigEndian);
505 return (0xffff - val + 1) * -1;
509 Buffer.prototype.readInt16LE = function(offset, noAssert) {
512 checkOffset(offset, 2, this.length);
513 return readInt16(this, offset, false);
517 Buffer.prototype.readInt16BE = function(offset, noAssert) {
520 checkOffset(offset, 2, this.length);
521 return readInt16(this, offset, true);
525 function readInt32(buffer, offset, isBigEndian) {
526 var val = readUInt32(buffer, offset, isBigEndian);
527 if (!(val & 0x80000000))
529 return (0xffffffff - val + 1) * -1;
533 Buffer.prototype.readInt32LE = function(offset, noAssert) {
536 checkOffset(offset, 4, this.length);
537 return readInt32(this, offset, false);
541 Buffer.prototype.readInt32BE = function(offset, noAssert) {
544 checkOffset(offset, 4, this.length);
545 return readInt32(this, offset, true);
549 function checkInt(buffer, value, offset, ext, max, min) {
550 if (value > max || value < min)
551 throw new TypeError('value is out of bounds');
552 if (offset < 0 || offset + ext > buffer.length || buffer.length + offset < 0)
553 throw new RangeError('index out of range');
557 Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
561 checkInt(this, value, offset, 1, 0xff, 0);
562 this[offset] = value;
567 function writeUInt16(buffer, value, offset, isBigEndian) {
569 buffer[offset] = (value & 0xff00) >>> 8;
570 buffer[offset + 1] = value & 0x00ff;
572 buffer[offset + 1] = (value & 0xff00) >>> 8;
573 buffer[offset] = value & 0x00ff;
579 Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
583 checkInt(this, value, offset, 2, 0xffff, 0);
584 return writeUInt16(this, value, offset, false);
588 Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
592 checkInt(this, value, offset, 2, 0xffff, 0);
593 return writeUInt16(this, value, offset, true);
597 function writeUInt32(buffer, value, offset, isBigEndian) {
599 buffer[offset] = (value >>> 24) & 0xff;
600 buffer[offset + 1] = (value >>> 16) & 0xff;
601 buffer[offset + 2] = (value >>> 8) & 0xff;
602 buffer[offset + 3] = value & 0xff;
604 buffer[offset + 3] = (value >>> 24) & 0xff;
605 buffer[offset + 2] = (value >>> 16) & 0xff;
606 buffer[offset + 1] = (value >>> 8) & 0xff;
607 buffer[offset] = value & 0xff;
613 Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
617 checkInt(this, value, offset, 4, 0xffffffff, 0);
618 return writeUInt32(this, value, offset, false);
622 Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
626 checkInt(this, value, offset, 4, 0xffffffff, 0);
627 return writeUInt32(this, value, offset, true);
632 * We now move onto our friends in the signed number category. Unlike unsigned
633 * numbers, we're going to have to worry a bit more about how we put values into
634 * arrays. Since we are only worrying about signed 32-bit values, we're in
635 * slightly better shape. Unfortunately, we really can't do our favorite binary
636 * & in this system. It really seems to do the wrong thing. For example:
641 * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of
642 * this aren't treated as a signed number. Ultimately a bad thing.
644 * What we're going to want to do is basically create the unsigned equivalent of
645 * our representation and pass that off to the wuint* functions. To do that
646 * we're going to do the following:
648 * - if the value is positive
649 * we can pass it directly off to the equivalent wuint
650 * - if the value is negative
651 * we do the following computation:
652 * mb + val + 1, where
653 * mb is the maximum unsigned value in that byte size
654 * val is the Javascript negative integer
657 * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If
658 * you do out the computations:
664 * You can then encode this value as the signed version. This is really rather
665 * hacky, but it should work and get the job done which is our goal here.
668 Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
672 checkInt(this, value, offset, 1, 0x7f, -0x80);
673 if (value < 0) value = 0xff + value + 1;
674 this[offset] = value;
679 Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
683 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
684 if (value < 0) value = 0xffff + value + 1;
685 return writeUInt16(this, value, offset, false);
689 Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
693 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
694 if (value < 0) value = 0xffff + value + 1;
695 return writeUInt16(this, value, offset, true);
699 Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
703 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
704 if (value < 0) value = 0xffffffff + value + 1;
705 return writeUInt32(this, value, offset, false);
709 Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
713 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
714 if (value < 0) value = 0xffffffff + value + 1;
715 return writeUInt32(this, value, offset, true);