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;
34 // add methods to Buffer prototype
35 buffer.setupBufferJS(Buffer, internal);
37 Buffer.poolSize = 8 * 1024;
38 var poolSize = Buffer.poolSize;
40 var allocPool = alloc({}, poolSize);
43 function createPool() {
44 poolSize = Buffer.poolSize;
45 allocPool = alloc({}, poolSize);
50 function Buffer(subject, encoding) {
51 if (!util.isBuffer(this))
52 return new Buffer(subject, encoding);
54 if (util.isNumber(subject))
55 this.length = subject > 0 ? Math.floor(subject) : 0;
56 else if (util.isString(subject))
57 this.length = Buffer.byteLength(subject, encoding = encoding || 'utf8');
58 else if (util.isObject(subject))
59 this.length = +subject.length > 0 ? Math.floor(+subject.length) : 0;
60 else if (util.isUndefined(subject)) {
61 // undef first arg returns unallocated buffer, also assumes length passed.
62 // this is a stop-gap for now while look for better architecture.
63 // for internal use only.
64 this.length = encoding;
68 throw new TypeError('must start with number, buffer, array or string');
70 if (this.length > kMaxLength)
71 throw new RangeError('length > kMaxLength');
73 if (this.length < Buffer.poolSize / 2 && this.length > 0) {
74 if (this.length > poolSize - poolOffset)
76 this.parent = sliceOnto(allocPool,
79 poolOffset + this.length);
80 poolOffset += this.length;
82 alloc(this, this.length);
85 if (!util.isNumber(subject)) {
86 if (util.isString(subject)) {
87 // FIXME: the number of bytes hasn't changed, so why change the length?
88 this.length = this.write(subject, 0, encoding);
90 if (util.isBuffer(subject))
91 subject.copy(this, 0, 0, this.length);
92 else if (util.isNumber(subject.length) || util.isArray(subject))
93 for (var i = 0; i < this.length; i++)
100 function SlowBuffer(length) {
102 var b = new Buffer(undefined, length);
110 Buffer.isBuffer = function isBuffer(b) {
111 return util.isBuffer(b);
115 Buffer.isEncoding = function(encoding) {
116 switch ((encoding + '').toLowerCase()) {
136 Buffer.concat = function(list, length) {
137 if (!util.isArray(list))
138 throw new TypeError('Usage: Buffer.concat(list[, length])');
140 if (util.isUndefined(length)) {
142 for (var i = 0; i < list.length; i++)
143 length += list[i].length;
148 if (length < 0) length = 0;
150 if (list.length === 0)
151 return new Buffer(0);
152 else if (list.length === 1)
155 var buffer = new Buffer(length);
157 for (var i = 0; i < list.length; i++) {
159 buf.copy(buffer, pos);
167 Buffer.byteLength = function(str, enc) {
180 ret = str.length * 2;
183 ret = str.length >>> 1;
186 ret = internal.byteLength(str, enc);
192 // pre-set for values that may exist in the future
193 Buffer.prototype.length = undefined;
194 Buffer.prototype.parent = undefined;
197 // toString(encoding, start=0, end=buffer.length)
198 Buffer.prototype.toString = function(encoding, start, end) {
199 encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
202 end = util.isUndefined(end) ? this.length : ~~end;
204 if (start < 0) start = 0;
205 if (end > this.length) end = this.length;
206 if (end <= start) return '';
210 return this.hexSlice(start, end);
214 return this.utf8Slice(start, end);
217 return this.asciiSlice(start, end);
220 return this.binarySlice(start, end);
223 return this.base64Slice(start, end);
229 return this.ucs2Slice(start, end);
232 throw new TypeError('Unknown encoding: ' + encoding);
238 Buffer.prototype.inspect = function inspect() {
240 var max = exports.INSPECT_MAX_BYTES;
241 if (this.length > 0) {
242 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
243 if (this.length > max)
246 return '<' + this.constructor.name + ' ' + str + '>';
250 // XXX remove in v0.13
251 Buffer.prototype.get = util.deprecate(function get(offset) {
253 if (offset < 0 || offset >= this.length)
254 throw new RangeError('index out of range');
256 }, '.get() is deprecated. Access using array indexes instead.');
259 // XXX remove in v0.13
260 Buffer.prototype.set = util.deprecate(function set(offset, v) {
262 if (offset < 0 || offset >= this.length)
263 throw new RangeError('index out of range');
264 return this[offset] = v;
265 }, '.set() is deprecated. Set using array indexes instead.');
268 // TODO(trevnorris): fix these checks to follow new standard
269 // write(string, offset = 0, length = buffer.length, encoding = 'utf8')
270 var writeWarned = false;
271 var writeMsg = '.write(string, encoding, offset, length) is deprecated.' +
272 ' Use write(string, offset, length, encoding) instead.';
273 Buffer.prototype.write = function(string, offset, length, encoding) {
274 // allow write(string, encoding)
275 if (util.isString(offset) && util.isUndefined(length)) {
279 // allow write(string, offset[, length], encoding)
280 } else if (isFinite(offset)) {
282 if (isFinite(length)) {
289 // XXX legacy write(string, encoding, offset, length) - remove in v0.13
292 if (process.throwDeprecation)
293 throw new Error(writeMsg);
294 else if (process.traceDeprecation)
295 console.trace(writeMsg);
297 console.error(writeMsg);
307 var remaining = this.length - offset;
308 if (util.isUndefined(length) || length > remaining)
311 encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
313 if (string.length > 0 && (length < 0 || offset < 0))
314 throw new RangeError('attempt to write beyond buffer bounds');
319 ret = this.hexWrite(string, offset, length);
324 ret = this.utf8Write(string, offset, length);
328 ret = this.asciiWrite(string, offset, length);
332 ret = this.binaryWrite(string, offset, length);
336 // Warning: maxLength not taken into account in base64Write
337 ret = this.base64Write(string, offset, length);
344 ret = this.ucs2Write(string, offset, length);
348 throw new TypeError('Unknown encoding: ' + encoding);
355 Buffer.prototype.toJSON = function() {
358 data: Array.prototype.slice.call(this, 0)
363 // TODO(trevnorris): currently works like Array.prototype.slice(), which
364 // doesn't follow the new standard for throwing on out of range indexes.
365 Buffer.prototype.slice = function(start, end) {
366 var len = this.length;
368 end = util.isUndefined(end) ? len : ~~end;
374 } else if (start > len) {
382 } else if (end > len) {
389 var buf = new Buffer();
390 sliceOnto(this, buf, start, end);
391 buf.length = end - start;
393 buf.parent = util.isUndefined(this.parent) ? this : this.parent;
399 function checkOffset(offset, ext, length) {
400 if (offset < 0 || offset + ext > length)
401 throw new RangeError('index out of range');
405 Buffer.prototype.readUInt8 = function(offset, noAssert) {
408 checkOffset(offset, 1, this.length);
413 function readUInt16(buffer, offset, isBigEndian) {
416 val = buffer[offset] << 8;
417 val |= buffer[offset + 1];
419 val = buffer[offset];
420 val |= buffer[offset + 1] << 8;
426 Buffer.prototype.readUInt16LE = function(offset, noAssert) {
429 checkOffset(offset, 2, this.length);
430 return readUInt16(this, offset, false, noAssert);
434 Buffer.prototype.readUInt16BE = function(offset, noAssert) {
437 checkOffset(offset, 2, this.length);
438 return readUInt16(this, offset, true, noAssert);
442 function readUInt32(buffer, offset, isBigEndian) {
445 val = buffer[offset + 1] << 16;
446 val |= buffer[offset + 2] << 8;
447 val |= buffer[offset + 3];
448 val = val + (buffer[offset] << 24 >>> 0);
450 val = buffer[offset + 2] << 16;
451 val |= buffer[offset + 1] << 8;
452 val |= buffer[offset];
453 val = val + (buffer[offset + 3] << 24 >>> 0);
459 Buffer.prototype.readUInt32LE = function(offset, noAssert) {
462 checkOffset(offset, 4, this.length);
463 return readUInt32(this, offset, false);
467 Buffer.prototype.readUInt32BE = function(offset, noAssert) {
470 checkOffset(offset, 4, this.length);
471 return readUInt32(this, offset, true);
476 * Signed integer types, yay team! A reminder on how two's complement actually
477 * works. The first bit is the signed bit, i.e. tells us whether or not the
478 * number should be positive or negative. If the two's complement value is
479 * positive, then we're done, as it's equivalent to the unsigned representation.
481 * Now if the number is positive, you're pretty much done, you can just leverage
482 * the unsigned translations and return those. Unfortunately, negative numbers
483 * aren't quite that straightforward.
485 * At first glance, one might be inclined to use the traditional formula to
486 * translate binary numbers between the positive and negative values in two's
487 * complement. (Though it doesn't quite work for the most negative value)
489 * - invert all the bits
490 * - add one to the result
492 * Of course, this doesn't quite work in Javascript. Take for example the value
493 * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of
494 * course, Javascript will do the following:
499 * Whoh there, Javascript, that's not quite right. But wait, according to
500 * Javascript that's perfectly correct. When Javascript ends up seeing the
501 * constant 0xff80, it has no notion that it is actually a signed number. It
502 * assumes that we've input the unsigned value 0xff80. Thus, when it does the
503 * binary negation, it casts it into a signed value, (positive 0xff80). Then
504 * when you perform binary negation on that, it turns it into a negative number.
506 * Instead, we're going to have to use the following general formula, that works
507 * in a rather Javascript friendly way. I'm glad we don't support this kind of
508 * weird numbering scheme in the kernel.
510 * (BIT-MAX - (unsigned)val + 1) * -1
512 * The astute observer, may think that this doesn't make sense for 8-bit numbers
513 * (really it isn't necessary for them). However, when you get 16-bit numbers,
514 * you do. Let's go back to our prior example and see how this will look:
516 * (0xffff - 0xff80 + 1) * -1
521 Buffer.prototype.readInt8 = function(offset, noAssert) {
524 checkOffset(offset, 1, this.length);
525 if (!(this[offset] & 0x80))
526 return (this[offset]);
527 return ((0xff - this[offset] + 1) * -1);
531 function readInt16(buffer, offset, isBigEndian) {
532 var val = readUInt16(buffer, offset, isBigEndian);
535 return (0xffff - val + 1) * -1;
539 Buffer.prototype.readInt16LE = function(offset, noAssert) {
542 checkOffset(offset, 2, this.length);
543 return readInt16(this, offset, false);
547 Buffer.prototype.readInt16BE = function(offset, noAssert) {
550 checkOffset(offset, 2, this.length);
551 return readInt16(this, offset, true);
555 function readInt32(buffer, offset, isBigEndian) {
556 var val = readUInt32(buffer, offset, isBigEndian);
557 if (!(val & 0x80000000))
559 return (0xffffffff - val + 1) * -1;
563 Buffer.prototype.readInt32LE = function(offset, noAssert) {
566 checkOffset(offset, 4, this.length);
567 return readInt32(this, offset, false);
571 Buffer.prototype.readInt32BE = function(offset, noAssert) {
574 checkOffset(offset, 4, this.length);
575 return readInt32(this, offset, true);
579 function checkInt(buffer, value, offset, ext, max, min) {
580 if (value > max || value < min)
581 throw new TypeError('value is out of bounds');
582 if (offset < 0 || offset + ext > buffer.length || buffer.length + offset < 0)
583 throw new RangeError('index out of range');
587 Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
591 checkInt(this, value, offset, 1, 0xff, 0);
592 this[offset] = value;
597 function writeUInt16(buffer, value, offset, isBigEndian) {
599 buffer[offset] = (value & 0xff00) >>> 8;
600 buffer[offset + 1] = value & 0x00ff;
602 buffer[offset + 1] = (value & 0xff00) >>> 8;
603 buffer[offset] = value & 0x00ff;
609 Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
613 checkInt(this, value, offset, 2, 0xffff, 0);
614 return writeUInt16(this, value, offset, false);
618 Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
622 checkInt(this, value, offset, 2, 0xffff, 0);
623 return writeUInt16(this, value, offset, true);
627 function writeUInt32(buffer, value, offset, isBigEndian) {
629 buffer[offset] = (value >>> 24) & 0xff;
630 buffer[offset + 1] = (value >>> 16) & 0xff;
631 buffer[offset + 2] = (value >>> 8) & 0xff;
632 buffer[offset + 3] = value & 0xff;
634 buffer[offset + 3] = (value >>> 24) & 0xff;
635 buffer[offset + 2] = (value >>> 16) & 0xff;
636 buffer[offset + 1] = (value >>> 8) & 0xff;
637 buffer[offset] = value & 0xff;
643 Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
647 checkInt(this, value, offset, 4, 0xffffffff, 0);
648 return writeUInt32(this, value, offset, false);
652 Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
656 checkInt(this, value, offset, 4, 0xffffffff, 0);
657 return writeUInt32(this, value, offset, true);
662 * We now move onto our friends in the signed number category. Unlike unsigned
663 * numbers, we're going to have to worry a bit more about how we put values into
664 * arrays. Since we are only worrying about signed 32-bit values, we're in
665 * slightly better shape. Unfortunately, we really can't do our favorite binary
666 * & in this system. It really seems to do the wrong thing. For example:
671 * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of
672 * this aren't treated as a signed number. Ultimately a bad thing.
674 * What we're going to want to do is basically create the unsigned equivalent of
675 * our representation and pass that off to the wuint* functions. To do that
676 * we're going to do the following:
678 * - if the value is positive
679 * we can pass it directly off to the equivalent wuint
680 * - if the value is negative
681 * we do the following computation:
682 * mb + val + 1, where
683 * mb is the maximum unsigned value in that byte size
684 * val is the Javascript negative integer
687 * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If
688 * you do out the computations:
694 * You can then encode this value as the signed version. This is really rather
695 * hacky, but it should work and get the job done which is our goal here.
698 Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
702 checkInt(this, value, offset, 1, 0x7f, -0x80);
703 if (value < 0) value = 0xff + value + 1;
704 this[offset] = value;
709 Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
713 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
714 if (value < 0) value = 0xffff + value + 1;
715 return writeUInt16(this, value, offset, false);
719 Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
723 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
724 if (value < 0) value = 0xffff + value + 1;
725 return writeUInt16(this, value, offset, true);
729 Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
733 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
734 if (value < 0) value = 0xffffffff + value + 1;
735 return writeUInt32(this, value, offset, false);
739 Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
743 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
744 if (value < 0) value = 0xffffffff + value + 1;
745 return writeUInt32(this, value, offset, true);