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 truncate = smalloc.truncate;
27 var sliceOnto = smalloc.sliceOnto;
28 var kMaxLength = smalloc.kMaxLength;
31 exports.Buffer = Buffer;
32 exports.SlowBuffer = SlowBuffer;
33 exports.INSPECT_MAX_BYTES = 50;
36 Buffer.poolSize = 8 * 1024;
37 var poolSize, poolOffset, allocPool;
40 function createPool() {
41 poolSize = Buffer.poolSize;
42 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 ? subject >>> 0 : 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('Attempt to allocate Buffer larger than maximum ' +
63 'size: 0x' + kMaxLength.toString(16) + ' bytes');
66 if (this.length <= (Buffer.poolSize >>> 1) && this.length > 0) {
67 if (this.length > poolSize - poolOffset)
69 this.parent = sliceOnto(allocPool,
72 poolOffset + this.length);
73 poolOffset += this.length;
75 alloc(this, this.length);
78 if (!util.isNumber(subject)) {
79 if (util.isString(subject)) {
80 // In the case of base64 it's possible that the size of the buffer
81 // allocated was slightly too large. In this case we need to rewrite
82 // the length to the actual length written.
83 var len = this.write(subject, encoding);
85 // Buffer was truncated after decode, realloc internal ExternalArray
86 if (len !== this.length) {
88 truncate(this, this.length);
91 if (util.isBuffer(subject))
92 subject.copy(this, 0, 0, this.length);
93 else if (util.isNumber(subject.length) || util.isArray(subject))
94 for (var i = 0; i < this.length; i++)
101 function SlowBuffer(length) {
102 length = length >>> 0;
103 if (length > kMaxLength) {
104 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
105 'size: 0x' + kMaxLength.toString(16) + ' bytes');
107 var b = new NativeBuffer(length);
113 // Bypass all checks for instantiating unallocated Buffer required for
114 // Objects created in C++. Significantly faster than calling the Buffer
116 function NativeBuffer(length) {
117 this.length = length;
119 NativeBuffer.prototype = Buffer.prototype;
122 // add methods to Buffer prototype
123 buffer.setupBufferJS(NativeBuffer, internal);
128 Buffer.isBuffer = function isBuffer(b) {
129 return util.isBuffer(b);
133 Buffer.compare = function compare(a, b) {
134 if (!(a instanceof Buffer) ||
135 !(b instanceof Buffer))
136 throw new TypeError('Arguments must be Buffers');
138 return internal.compare(a, b);
142 Buffer.isEncoding = function(encoding) {
143 switch ((encoding + '').toLowerCase()) {
163 Buffer.concat = function(list, length) {
164 if (!util.isArray(list))
165 throw new TypeError('Usage: Buffer.concat(list[, length])');
167 if (util.isUndefined(length)) {
169 for (var i = 0; i < list.length; i++)
170 length += list[i].length;
172 length = length >>> 0;
175 if (list.length === 0)
176 return new Buffer(0);
177 else if (list.length === 1)
180 var buffer = new Buffer(length);
182 for (var i = 0; i < list.length; i++) {
184 buf.copy(buffer, pos);
192 Buffer.byteLength = function(str, enc) {
205 ret = str.length * 2;
208 ret = str.length >>> 1;
211 ret = internal.byteLength(str, enc);
217 // pre-set for values that may exist in the future
218 Buffer.prototype.length = undefined;
219 Buffer.prototype.parent = undefined;
222 // toString(encoding, start=0, end=buffer.length)
223 Buffer.prototype.toString = function(encoding, start, end) {
224 var loweredCase = false;
227 end = util.isUndefined(end) || end === Infinity ? this.length : end >>> 0;
229 if (!encoding) encoding = 'utf8';
230 if (start < 0) start = 0;
231 if (end > this.length) end = this.length;
232 if (end <= start) return '';
237 return this.hexSlice(start, end);
241 return this.utf8Slice(start, end);
244 return this.asciiSlice(start, end);
247 return this.binarySlice(start, end);
250 return this.base64Slice(start, end);
256 return this.ucs2Slice(start, end);
260 throw new TypeError('Unknown encoding: ' + encoding);
261 encoding = (encoding + '').toLowerCase();
268 Buffer.prototype.equals = function equals(b) {
269 if (!(b instanceof Buffer))
270 throw new TypeError('Argument must be a Buffer');
272 return internal.compare(this, b) === 0;
277 Buffer.prototype.inspect = function inspect() {
279 var max = exports.INSPECT_MAX_BYTES;
280 if (this.length > 0) {
281 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
282 if (this.length > max)
285 return '<' + this.constructor.name + ' ' + str + '>';
289 Buffer.prototype.compare = function compare(b) {
290 if (!(b instanceof Buffer))
291 throw new TypeError('Argument must be a Buffer');
293 return internal.compare(this, b);
297 // XXX remove in v0.13
298 Buffer.prototype.get = util.deprecate(function get(offset) {
300 if (offset < 0 || offset >= this.length)
301 throw new RangeError('index out of range');
303 }, '.get() is deprecated. Access using array indexes instead.');
306 // XXX remove in v0.13
307 Buffer.prototype.set = util.deprecate(function set(offset, v) {
309 if (offset < 0 || offset >= this.length)
310 throw new RangeError('index out of range');
311 return this[offset] = v;
312 }, '.set() is deprecated. Set using array indexes instead.');
315 // TODO(trevnorris): fix these checks to follow new standard
316 // write(string, offset = 0, length = buffer.length, encoding = 'utf8')
317 var writeWarned = false;
318 var writeMsg = '.write(string, encoding, offset, length) is deprecated.' +
319 ' Use write(string[, offset[, length]][, encoding]) instead.';
320 Buffer.prototype.write = function(string, offset, length, encoding) {
321 // Buffer#write(string);
322 if (util.isUndefined(offset)) {
324 length = this.length;
327 // Buffer#write(string, encoding)
328 } else if (util.isUndefined(length) && util.isString(offset)) {
330 length = this.length;
333 // Buffer#write(string, offset[, length][, encoding])
334 } else if (isFinite(offset)) {
335 offset = offset >>> 0;
336 if (isFinite(length)) {
337 length = length >>> 0;
338 if (util.isUndefined(encoding))
345 // XXX legacy write(string, encoding, offset, length) - remove in v0.13
348 if (process.throwDeprecation)
349 throw new Error(writeMsg);
350 else if (process.traceDeprecation)
351 console.trace(writeMsg);
353 console.error(writeMsg);
359 offset = length >>> 0;
363 var remaining = this.length - offset;
364 if (util.isUndefined(length) || length > remaining)
367 encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
369 if (string.length > 0 && (length < 0 || offset < 0))
370 throw new RangeError('attempt to write outside buffer bounds');
375 ret = this.hexWrite(string, offset, length);
380 ret = this.utf8Write(string, offset, length);
384 ret = this.asciiWrite(string, offset, length);
388 ret = this.binaryWrite(string, offset, length);
392 // Warning: maxLength not taken into account in base64Write
393 ret = this.base64Write(string, offset, length);
400 ret = this.ucs2Write(string, offset, length);
404 throw new TypeError('Unknown encoding: ' + encoding);
411 Buffer.prototype.toJSON = function() {
414 data: Array.prototype.slice.call(this, 0)
419 // TODO(trevnorris): currently works like Array.prototype.slice(), which
420 // doesn't follow the new standard for throwing on out of range indexes.
421 Buffer.prototype.slice = function(start, end) {
422 var len = this.length;
424 end = util.isUndefined(end) ? len : ~~end;
430 } else if (start > len) {
438 } else if (end > len) {
445 var buf = new NativeBuffer();
446 sliceOnto(this, buf, start, end);
447 buf.length = end - start;
449 buf.parent = util.isUndefined(this.parent) ? this : this.parent;
455 function checkOffset(offset, ext, length) {
456 if (offset + ext > length)
457 throw new RangeError('index out of range');
461 Buffer.prototype.readUInt8 = function(offset, noAssert) {
462 offset = offset >>> 0;
464 checkOffset(offset, 1, this.length);
469 Buffer.prototype.readUInt16LE = function(offset, noAssert) {
470 offset = offset >>> 0;
472 checkOffset(offset, 2, this.length);
473 return this[offset] | (this[offset + 1] << 8);
477 Buffer.prototype.readUInt16BE = function(offset, noAssert) {
478 offset = offset >>> 0;
480 checkOffset(offset, 2, this.length);
481 return (this[offset] << 8) | this[offset + 1];
485 Buffer.prototype.readUInt32LE = function(offset, noAssert) {
486 offset = offset >>> 0;
488 checkOffset(offset, 4, this.length);
490 return ((this[offset]) |
491 (this[offset + 1] << 8) |
492 (this[offset + 2] << 16)) +
493 (this[offset + 3] * 0x1000000);
497 Buffer.prototype.readUInt32BE = function(offset, noAssert) {
498 offset = offset >>> 0;
500 checkOffset(offset, 4, this.length);
502 return (this[offset] * 0x1000000) +
503 ((this[offset + 1] << 16) |
504 (this[offset + 2] << 8) |
505 (this[offset + 3]) >>> 0);
509 Buffer.prototype.readInt8 = function(offset, noAssert) {
510 offset = offset >>> 0;
512 checkOffset(offset, 1, this.length);
513 var val = this[offset];
514 return !(val & 0x80) ? val : (0xff - val + 1) * -1;
518 Buffer.prototype.readInt16LE = function(offset, noAssert) {
519 offset = offset >>> 0;
521 checkOffset(offset, 2, this.length);
522 var val = this[offset] | (this[offset + 1] << 8);
523 return (val & 0x8000) ? val | 0xFFFF0000 : val;
527 Buffer.prototype.readInt16BE = function(offset, noAssert) {
528 offset = offset >>> 0;
530 checkOffset(offset, 2, this.length);
531 var val = this[offset + 1] | (this[offset] << 8);
532 return (val & 0x8000) ? val | 0xFFFF0000 : val;
536 Buffer.prototype.readInt32LE = function(offset, noAssert) {
537 offset = offset >>> 0;
539 checkOffset(offset, 4, this.length);
541 return (this[offset]) |
542 (this[offset + 1] << 8) |
543 (this[offset + 2] << 16) |
544 (this[offset + 3] << 24);
548 Buffer.prototype.readInt32BE = function(offset, noAssert) {
549 offset = offset >>> 0;
551 checkOffset(offset, 4, this.length);
553 return (this[offset] << 24) |
554 (this[offset + 1] << 16) |
555 (this[offset + 2] << 8) |
560 function checkInt(buffer, value, offset, ext, max, min) {
561 if (!(buffer instanceof Buffer))
562 throw new TypeError('buffer must be a Buffer instance');
563 if (value > max || value < min)
564 throw new TypeError('value is out of bounds');
565 if (offset + ext > buffer.length)
566 throw new RangeError('index out of range');
570 Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
572 offset = offset >>> 0;
574 checkInt(this, value, offset, 1, 0xff, 0);
575 this[offset] = value;
580 Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
582 offset = offset >>> 0;
584 checkInt(this, value, offset, 2, 0xffff, 0);
585 this[offset] = value;
586 this[offset + 1] = (value >>> 8);
591 Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
593 offset = offset >>> 0;
595 checkInt(this, value, offset, 2, 0xffff, 0);
596 this[offset] = (value >>> 8);
597 this[offset + 1] = value;
602 Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
604 offset = offset >>> 0;
606 checkInt(this, value, offset, 4, 0xffffffff, 0);
607 this[offset + 3] = (value >>> 24);
608 this[offset + 2] = (value >>> 16);
609 this[offset + 1] = (value >>> 8);
610 this[offset] = value;
615 Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
617 offset = offset >>> 0;
619 checkInt(this, value, offset, 4, 0xffffffff, 0);
620 this[offset] = (value >>> 24);
621 this[offset + 1] = (value >>> 16);
622 this[offset + 2] = (value >>> 8);
623 this[offset + 3] = value;
628 Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
630 offset = offset >>> 0;
632 checkInt(this, value, offset, 1, 0x7f, -0x80);
633 this[offset] = value;
638 Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
640 offset = offset >>> 0;
642 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
643 this[offset] = value;
644 this[offset + 1] = (value >>> 8);
649 Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
651 offset = offset >>> 0;
653 checkInt(this, value, offset, 2, 0x7fff, -0x8000);
654 this[offset] = (value >>> 8);
655 this[offset + 1] = value;
660 Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
662 offset = offset >>> 0;
664 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
665 this[offset] = value;
666 this[offset + 1] = (value >>> 8);
667 this[offset + 2] = (value >>> 16);
668 this[offset + 3] = (value >>> 24);
673 Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
675 offset = offset >>> 0;
677 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
678 this[offset] = (value >>> 24);
679 this[offset + 1] = (value >>> 16);
680 this[offset + 2] = (value >>> 8);
681 this[offset + 3] = value;