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 this.copy(subject, 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() {
241 str = this.hexSlice(0, this.length).match(/.{2}/g).join(' ');
242 return '<' + this.constructor.name + ' ' + str + '>';
246 // XXX remove in v0.13
247 Buffer.prototype.get = util.deprecate(function get(offset) {
249 if (offset < 0 || offset >= this.length)
250 throw new RangeError('index out of range');
252 }, '.get() is deprecated. Access using array indexes instead.');
255 // XXX remove in v0.13
256 Buffer.prototype.set = util.deprecate(function set(offset, v) {
258 if (offset < 0 || offset >= this.length)
259 throw new RangeError('index out of range');
260 return this[offset] = v;
261 }, '.set() is deprecated. Set using array indexes instead.');
264 // TODO(trevnorris): fix these checks to follow new standard
265 // write(string, offset = 0, length = buffer.length, encoding = 'utf8')
266 var writeWarned = false;
267 var writeMsg = '.write(string, encoding, offset, length) is deprecated.' +
268 ' Use write(string, offset, length, encoding) instead.';
269 Buffer.prototype.write = function(string, offset, length, encoding) {
270 // allow write(string, encoding)
271 if (util.isString(offset) && util.isUndefined(length)) {
275 // allow write(string, offset[, length], encoding)
276 } else if (isFinite(offset)) {
278 if (isFinite(length)) {
285 // XXX legacy write(string, encoding, offset, length) - remove in v0.13
288 if (process.throwDeprecation)
289 throw new Error(writeMsg);
290 else if (process.traceDeprecation)
291 console.trace(writeMsg);
293 console.error(writeMsg);
303 var remaining = this.length - offset;
304 if (util.isUndefined(length) || length > remaining)
307 encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
309 if (string.length > 0 && (length < 0 || offset < 0))
310 throw new RangeError('attempt to write beyond buffer bounds');
315 ret = this.hexWrite(string, offset, length);
320 ret = this.utf8Write(string, offset, length);
324 ret = this.asciiWrite(string, offset, length);
328 ret = this.binaryWrite(string, offset, length);
332 // Warning: maxLength not taken into account in base64Write
333 ret = this.base64Write(string, offset, length);
340 ret = this.ucs2Write(string, offset, length);
344 throw new TypeError('Unknown encoding: ' + encoding);
351 Buffer.prototype.toJSON = function() {
354 data: Array.prototype.slice.call(this, 0)
359 // TODO(trevnorris): currently works like Array.prototype.slice(), which
360 // doesn't follow the new standard for throwing on out of range indexes.
361 Buffer.prototype.slice = function(start, end) {
362 var len = this.length;
364 end = util.isUndefined(end) ? len : ~~end;
370 } else if (start > len) {
378 } else if (end > len) {
385 var buf = new Buffer();
386 sliceOnto(this, buf, start, end);
387 buf.length = end - start;
389 buf.parent = util.isUndefined(this.parent) ? this : this.parent;
395 function checkOffset(offset, ext, length) {
396 if (offset < 0 || offset + ext > length)
397 throw new RangeError('index out of range');
401 Buffer.prototype.readUInt8 = function(offset, noAssert) {
404 checkOffset(offset, 1, this.length);
409 function readUInt16(buffer, offset, isBigEndian) {
412 val = buffer[offset] << 8;
413 val |= buffer[offset + 1];
415 val = buffer[offset];
416 val |= buffer[offset + 1] << 8;
422 Buffer.prototype.readUInt16LE = function(offset, noAssert) {
425 checkOffset(offset, 2, this.length);
426 return readUInt16(this, offset, false, noAssert);
430 Buffer.prototype.readUInt16BE = function(offset, noAssert) {
433 checkOffset(offset, 2, this.length);
434 return readUInt16(this, offset, true, noAssert);
438 function readUInt32(buffer, offset, isBigEndian) {
441 val = buffer[offset + 1] << 16;
442 val |= buffer[offset + 2] << 8;
443 val |= buffer[offset + 3];
444 val = val + (buffer[offset] << 24 >>> 0);
446 val = buffer[offset + 2] << 16;
447 val |= buffer[offset + 1] << 8;
448 val |= buffer[offset];
449 val = val + (buffer[offset + 3] << 24 >>> 0);
455 Buffer.prototype.readUInt32LE = function(offset, noAssert) {
458 checkOffset(offset, 4, this.length);
459 return readUInt32(this, offset, false);
463 Buffer.prototype.readUInt32BE = function(offset, noAssert) {
466 checkOffset(offset, 4, this.length);
467 return readUInt32(this, offset, true);
472 * Signed integer types, yay team! A reminder on how two's complement actually
473 * works. The first bit is the signed bit, i.e. tells us whether or not the
474 * number should be positive or negative. If the two's complement value is
475 * positive, then we're done, as it's equivalent to the unsigned representation.
477 * Now if the number is positive, you're pretty much done, you can just leverage
478 * the unsigned translations and return those. Unfortunately, negative numbers
479 * aren't quite that straightforward.
481 * At first glance, one might be inclined to use the traditional formula to
482 * translate binary numbers between the positive and negative values in two's
483 * complement. (Though it doesn't quite work for the most negative value)
485 * - invert all the bits
486 * - add one to the result
488 * Of course, this doesn't quite work in Javascript. Take for example the value
489 * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of
490 * course, Javascript will do the following:
495 * Whoh there, Javascript, that's not quite right. But wait, according to
496 * Javascript that's perfectly correct. When Javascript ends up seeing the
497 * constant 0xff80, it has no notion that it is actually a signed number. It
498 * assumes that we've input the unsigned value 0xff80. Thus, when it does the
499 * binary negation, it casts it into a signed value, (positive 0xff80). Then
500 * when you perform binary negation on that, it turns it into a negative number.
502 * Instead, we're going to have to use the following general formula, that works
503 * in a rather Javascript friendly way. I'm glad we don't support this kind of
504 * weird numbering scheme in the kernel.
506 * (BIT-MAX - (unsigned)val + 1) * -1
508 * The astute observer, may think that this doesn't make sense for 8-bit numbers
509 * (really it isn't necessary for them). However, when you get 16-bit numbers,
510 * you do. Let's go back to our prior example and see how this will look:
512 * (0xffff - 0xff80 + 1) * -1
517 Buffer.prototype.readInt8 = function(offset, noAssert) {
520 checkOffset(offset, 1, this.length);
521 if (!(this[offset] & 0x80))
522 return (this[offset]);
523 return ((0xff - this[offset] + 1) * -1);
527 function readInt16(buffer, offset, isBigEndian) {
528 var val = readUInt16(buffer, offset, isBigEndian);
531 return (0xffff - val + 1) * -1;
535 Buffer.prototype.readInt16LE = function(offset, noAssert) {
538 checkOffset(offset, 2, this.length);
539 return readInt16(this, offset, false);
543 Buffer.prototype.readInt16BE = function(offset, noAssert) {
546 checkOffset(offset, 2, this.length);
547 return readInt16(this, offset, true);
551 function readInt32(buffer, offset, isBigEndian) {
552 var val = readUInt32(buffer, offset, isBigEndian);
553 if (!(val & 0x80000000))
555 return (0xffffffff - val + 1) * -1;
559 Buffer.prototype.readInt32LE = function(offset, noAssert) {
562 checkOffset(offset, 4, this.length);
563 return readInt32(this, offset, false);
567 Buffer.prototype.readInt32BE = function(offset, noAssert) {
570 checkOffset(offset, 4, this.length);
571 return readInt32(this, offset, true);
575 function checkInt(buffer, value, offset, ext, max, min) {
576 if (value > max || value < min)
577 throw new TypeError('value is out of bounds');
578 if (offset < 0 || offset + ext > buffer.length || buffer.length + offset < 0)
579 throw new RangeError('index out of range');
583 Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
587 checkInt(this, value, offset, 1, 0xff, 0);
588 this[offset] = value;
593 function writeUInt16(buffer, value, offset, isBigEndian) {
595 buffer[offset] = (value & 0xff00) >>> 8;
596 buffer[offset + 1] = value & 0x00ff;
598 buffer[offset + 1] = (value & 0xff00) >>> 8;
599 buffer[offset] = value & 0x00ff;
605 Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
609 checkInt(this, value, offset, 2, 0xffff, 0);
610 return writeUInt16(this, value, offset, false);
614 Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
618 checkInt(this, value, offset, 2, 0xffff, 0);
619 return writeUInt16(this, value, offset, true);
623 function writeUInt32(buffer, value, offset, isBigEndian) {
625 buffer[offset] = (value >>> 24) & 0xff;
626 buffer[offset + 1] = (value >>> 16) & 0xff;
627 buffer[offset + 2] = (value >>> 8) & 0xff;
628 buffer[offset + 3] = value & 0xff;
630 buffer[offset + 3] = (value >>> 24) & 0xff;
631 buffer[offset + 2] = (value >>> 16) & 0xff;
632 buffer[offset + 1] = (value >>> 8) & 0xff;
633 buffer[offset] = value & 0xff;
639 Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
643 checkInt(this, value, offset, 4, 0xffffffff, 0);
644 return writeUInt32(this, value, offset, false);
648 Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
652 checkInt(this, value, offset, 4, 0xffffffff, 0);
653 return writeUInt32(this, value, offset, true);
658 * We now move onto our friends in the signed number category. Unlike unsigned
659 * numbers, we're going to have to worry a bit more about how we put values into
660 * arrays. Since we are only worrying about signed 32-bit values, we're in
661 * slightly better shape. Unfortunately, we really can't do our favorite binary
662 * & in this system. It really seems to do the wrong thing. For example:
667 * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of
668 * this aren't treated as a signed number. Ultimately a bad thing.
670 * What we're going to want to do is basically create the unsigned equivalent of
671 * our representation and pass that off to the wuint* functions. To do that
672 * we're going to do the following:
674 * - if the value is positive
675 * we can pass it directly off to the equivalent wuint
676 * - if the value is negative
677 * we do the following computation:
678 * mb + val + 1, where
679 * mb is the maximum unsigned value in that byte size
680 * val is the Javascript negative integer
683 * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If
684 * you do out the computations:
690 * You can then encode this value as the signed version. This is really rather
691 * hacky, but it should work and get the job done which is our goal here.
694 Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
698 checkInt(this, value, offset, 1, 0x7f, -0x80);
699 if (value < 0) value = 0xff + value + 1;
700 this[offset] = value;
705 Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
709 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
710 if (value < 0) value = 0xffff + value + 1;
711 return writeUInt16(this, value, offset, false);
715 Buffer.prototype.writeInt16BE = 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, true);
725 Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
729 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
730 if (value < 0) value = 0xffffffff + value + 1;
731 return writeUInt32(this, value, offset, false);
735 Buffer.prototype.writeInt32BE = 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, true);