buffer: fix regression in Buffer(buf) constructor
[platform/upstream/nodejs.git] / lib / buffer.js
1 // Copyright Joyent, Inc. and other Node contributors.
2 //
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:
10 //
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
13 //
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.
21
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;
28 var internal = {};
29
30 exports.Buffer = Buffer;
31 exports.SlowBuffer = SlowBuffer;
32 exports.INSPECT_MAX_BYTES = 50;
33
34 // add methods to Buffer prototype
35 buffer.setupBufferJS(Buffer, internal);
36
37 Buffer.poolSize = 8 * 1024;
38 var poolSize = Buffer.poolSize;
39 var poolOffset = 0;
40 var allocPool = alloc({}, poolSize);
41
42
43 function createPool() {
44   poolSize = Buffer.poolSize;
45   allocPool = alloc({}, poolSize);
46   poolOffset = 0;
47 }
48
49
50 function Buffer(subject, encoding) {
51   if (!util.isBuffer(this))
52     return new Buffer(subject, encoding);
53
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;
65     return;
66   }
67   else
68     throw new TypeError('must start with number, buffer, array or string');
69
70   if (this.length > kMaxLength)
71     throw new RangeError('length > kMaxLength');
72
73   if (this.length < Buffer.poolSize / 2 && this.length > 0) {
74     if (this.length > poolSize - poolOffset)
75       createPool();
76     this.parent = sliceOnto(allocPool,
77                             this,
78                             poolOffset,
79                             poolOffset + this.length);
80     poolOffset += this.length;
81   } else {
82     alloc(this, this.length);
83   }
84
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);
89     } else {
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++)
94           this[i] = subject[i];
95     }
96   }
97 }
98
99
100 function SlowBuffer(length) {
101   length = ~~length;
102   var b = new Buffer(undefined, length);
103   alloc(b, length);
104   return b;
105 }
106
107
108 // Static methods
109
110 Buffer.isBuffer = function isBuffer(b) {
111   return util.isBuffer(b);
112 };
113
114
115 Buffer.isEncoding = function(encoding) {
116   switch ((encoding + '').toLowerCase()) {
117     case 'hex':
118     case 'utf8':
119     case 'utf-8':
120     case 'ascii':
121     case 'binary':
122     case 'base64':
123     case 'ucs2':
124     case 'ucs-2':
125     case 'utf16le':
126     case 'utf-16le':
127     case 'raw':
128       return true;
129
130     default:
131       return false;
132   }
133 };
134
135
136 Buffer.concat = function(list, length) {
137   if (!util.isArray(list))
138     throw new TypeError('Usage: Buffer.concat(list[, length])');
139
140   if (util.isUndefined(length)) {
141     length = 0;
142     for (var i = 0; i < list.length; i++)
143       length += list[i].length;
144   } else {
145     length = ~~length;
146   }
147
148   if (length < 0) length = 0;
149
150   if (list.length === 0)
151     return new Buffer(0);
152   else if (list.length === 1)
153     return list[0];
154
155   var buffer = new Buffer(length);
156   var pos = 0;
157   for (var i = 0; i < list.length; i++) {
158     var buf = list[i];
159     buf.copy(buffer, pos);
160     pos += buf.length;
161   }
162
163   return buffer;
164 };
165
166
167 Buffer.byteLength = function(str, enc) {
168   var ret;
169   str = str + '';
170   switch (enc) {
171     case 'ascii':
172     case 'binary':
173     case 'raw':
174       ret = str.length;
175       break;
176     case 'ucs2':
177     case 'ucs-2':
178     case 'utf16le':
179     case 'utf-16le':
180       ret = str.length * 2;
181       break;
182     case 'hex':
183       ret = str.length >>> 1;
184       break;
185     default:
186       ret = internal.byteLength(str, enc);
187   }
188   return ret;
189 };
190
191
192 // pre-set for values that may exist in the future
193 Buffer.prototype.length = undefined;
194 Buffer.prototype.parent = undefined;
195
196
197 // toString(encoding, start=0, end=buffer.length)
198 Buffer.prototype.toString = function(encoding, start, end) {
199   encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
200
201   start = ~~start;
202   end = util.isUndefined(end) ? this.length : ~~end;
203
204   if (start < 0) start = 0;
205   if (end > this.length) end = this.length;
206   if (end <= start) return '';
207
208   switch (encoding) {
209     case 'hex':
210       return this.hexSlice(start, end);
211
212     case 'utf8':
213     case 'utf-8':
214       return this.utf8Slice(start, end);
215
216     case 'ascii':
217       return this.asciiSlice(start, end);
218
219     case 'binary':
220       return this.binarySlice(start, end);
221
222     case 'base64':
223       return this.base64Slice(start, end);
224
225     case 'ucs2':
226     case 'ucs-2':
227     case 'utf16le':
228     case 'utf-16le':
229       return this.ucs2Slice(start, end);
230
231     default:
232       throw new TypeError('Unknown encoding: ' + encoding);
233   }
234 };
235
236
237 // Inspect
238 Buffer.prototype.inspect = function inspect() {
239   var str = '';
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)
244       str += ' ... ';
245   }
246   return '<' + this.constructor.name + ' ' + str + '>';
247 };
248
249
250 // XXX remove in v0.13
251 Buffer.prototype.get = util.deprecate(function get(offset) {
252   offset = ~~offset;
253   if (offset < 0 || offset >= this.length)
254     throw new RangeError('index out of range');
255   return this[offset];
256 }, '.get() is deprecated. Access using array indexes instead.');
257
258
259 // XXX remove in v0.13
260 Buffer.prototype.set = util.deprecate(function set(offset, v) {
261   offset = ~~offset;
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.');
266
267
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)) {
276     encoding = offset;
277     offset = 0;
278
279   // allow write(string, offset[, length], encoding)
280   } else if (isFinite(offset)) {
281     offset = ~~offset;
282     if (isFinite(length)) {
283       length = ~~length;
284     } else {
285       encoding = length;
286       length = undefined;
287     }
288
289   // XXX legacy write(string, encoding, offset, length) - remove in v0.13
290   } else {
291     if (!writeWarned) {
292       if (process.throwDeprecation)
293         throw new Error(writeMsg);
294       else if (process.traceDeprecation)
295         console.trace(writeMsg);
296       else
297         console.error(writeMsg);
298       writeWarned = true;
299     }
300
301     var swap = encoding;
302     encoding = offset;
303     offset = ~~length;
304     length = swap;
305   }
306
307   var remaining = this.length - offset;
308   if (util.isUndefined(length) || length > remaining)
309     length = remaining;
310
311   encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
312
313   if (string.length > 0 && (length < 0 || offset < 0))
314     throw new RangeError('attempt to write beyond buffer bounds');
315
316   var ret;
317   switch (encoding) {
318     case 'hex':
319       ret = this.hexWrite(string, offset, length);
320       break;
321
322     case 'utf8':
323     case 'utf-8':
324       ret = this.utf8Write(string, offset, length);
325       break;
326
327     case 'ascii':
328       ret = this.asciiWrite(string, offset, length);
329       break;
330
331     case 'binary':
332       ret = this.binaryWrite(string, offset, length);
333       break;
334
335     case 'base64':
336       // Warning: maxLength not taken into account in base64Write
337       ret = this.base64Write(string, offset, length);
338       break;
339
340     case 'ucs2':
341     case 'ucs-2':
342     case 'utf16le':
343     case 'utf-16le':
344       ret = this.ucs2Write(string, offset, length);
345       break;
346
347     default:
348       throw new TypeError('Unknown encoding: ' + encoding);
349   }
350
351   return ret;
352 };
353
354
355 Buffer.prototype.toJSON = function() {
356   return {
357     type: 'Buffer',
358     data: Array.prototype.slice.call(this, 0)
359   };
360 };
361
362
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;
367   start = ~~start;
368   end = util.isUndefined(end) ? len : ~~end;
369
370   if (start < 0) {
371     start += len;
372     if (start < 0)
373       start = 0;
374   } else if (start > len) {
375     start = len;
376   }
377
378   if (end < 0) {
379     end += len;
380     if (end < 0)
381       end = 0;
382   } else if (end > len) {
383     end = len;
384   }
385
386   if (end < start)
387     end = start;
388
389   var buf = new Buffer();
390   sliceOnto(this, buf, start, end);
391   buf.length = end - start;
392   if (buf.length > 0)
393     buf.parent = util.isUndefined(this.parent) ? this : this.parent;
394
395   return buf;
396 };
397
398
399 function checkOffset(offset, ext, length) {
400   if (offset < 0 || offset + ext > length)
401     throw new RangeError('index out of range');
402 }
403
404
405 Buffer.prototype.readUInt8 = function(offset, noAssert) {
406   offset = ~~offset;
407   if (!noAssert)
408     checkOffset(offset, 1, this.length);
409   return this[offset];
410 };
411
412
413 function readUInt16(buffer, offset, isBigEndian) {
414   var val = 0;
415   if (isBigEndian) {
416     val = buffer[offset] << 8;
417     val |= buffer[offset + 1];
418   } else {
419     val = buffer[offset];
420     val |= buffer[offset + 1] << 8;
421   }
422   return val;
423 }
424
425
426 Buffer.prototype.readUInt16LE = function(offset, noAssert) {
427   offset = ~~offset;
428   if (!noAssert)
429     checkOffset(offset, 2, this.length);
430   return readUInt16(this, offset, false, noAssert);
431 };
432
433
434 Buffer.prototype.readUInt16BE = function(offset, noAssert) {
435   offset = ~~offset;
436   if (!noAssert)
437     checkOffset(offset, 2, this.length);
438   return readUInt16(this, offset, true, noAssert);
439 };
440
441
442 function readUInt32(buffer, offset, isBigEndian) {
443   var val = 0;
444   if (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);
449   } else {
450     val = buffer[offset + 2] << 16;
451     val |= buffer[offset + 1] << 8;
452     val |= buffer[offset];
453     val = val + (buffer[offset + 3] << 24 >>> 0);
454   }
455   return val;
456 }
457
458
459 Buffer.prototype.readUInt32LE = function(offset, noAssert) {
460   offset = ~~offset;
461   if (!noAssert)
462     checkOffset(offset, 4, this.length);
463   return readUInt32(this, offset, false);
464 };
465
466
467 Buffer.prototype.readUInt32BE = function(offset, noAssert) {
468   offset = ~~offset;
469   if (!noAssert)
470     checkOffset(offset, 4, this.length);
471   return readUInt32(this, offset, true);
472 };
473
474
475 /*
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.
480  *
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.
484  *
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)
488  * Mainly:
489  *  - invert all the bits
490  *  - add one to the result
491  *
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:
495  *
496  * > ~0xff80
497  * -65409
498  *
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.
505  *
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.
509  *
510  * (BIT-MAX - (unsigned)val + 1) * -1
511  *
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:
515  *
516  * (0xffff - 0xff80 + 1) * -1
517  * (0x007f + 1) * -1
518  * (0x0080) * -1
519  */
520
521 Buffer.prototype.readInt8 = function(offset, noAssert) {
522   offset = ~~offset;
523   if (!noAssert)
524     checkOffset(offset, 1, this.length);
525   if (!(this[offset] & 0x80))
526     return (this[offset]);
527   return ((0xff - this[offset] + 1) * -1);
528 };
529
530
531 function readInt16(buffer, offset, isBigEndian) {
532   var val = readUInt16(buffer, offset, isBigEndian);
533   if (!(val & 0x8000))
534     return val;
535   return (0xffff - val + 1) * -1;
536 }
537
538
539 Buffer.prototype.readInt16LE = function(offset, noAssert) {
540   offset = ~~offset;
541   if (!noAssert)
542     checkOffset(offset, 2, this.length);
543   return readInt16(this, offset, false);
544 };
545
546
547 Buffer.prototype.readInt16BE = function(offset, noAssert) {
548   offset = ~~offset;
549   if (!noAssert)
550     checkOffset(offset, 2, this.length);
551   return readInt16(this, offset, true);
552 };
553
554
555 function readInt32(buffer, offset, isBigEndian) {
556   var val = readUInt32(buffer, offset, isBigEndian);
557   if (!(val & 0x80000000))
558     return (val);
559   return (0xffffffff - val + 1) * -1;
560 }
561
562
563 Buffer.prototype.readInt32LE = function(offset, noAssert) {
564   offset = ~~offset;
565   if (!noAssert)
566     checkOffset(offset, 4, this.length);
567   return readInt32(this, offset, false);
568 };
569
570
571 Buffer.prototype.readInt32BE = function(offset, noAssert) {
572   offset = ~~offset;
573   if (!noAssert)
574     checkOffset(offset, 4, this.length);
575   return readInt32(this, offset, true);
576 };
577
578
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');
584 }
585
586
587 Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
588   value = +value;
589   offset = ~~offset;
590   if (!noAssert)
591     checkInt(this, value, offset, 1, 0xff, 0);
592   this[offset] = value;
593   return offset + 1;
594 };
595
596
597 function writeUInt16(buffer, value, offset, isBigEndian) {
598   if (isBigEndian) {
599     buffer[offset] = (value & 0xff00) >>> 8;
600     buffer[offset + 1] = value & 0x00ff;
601   } else {
602     buffer[offset + 1] = (value & 0xff00) >>> 8;
603     buffer[offset] = value & 0x00ff;
604   }
605   return offset + 2;
606 }
607
608
609 Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
610   value = +value;
611   offset = ~~offset;
612   if (!noAssert)
613     checkInt(this, value, offset, 2, 0xffff, 0);
614   return writeUInt16(this, value, offset, false);
615 };
616
617
618 Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
619   value = +value;
620   offset = ~~offset;
621   if (!noAssert)
622     checkInt(this, value, offset, 2, 0xffff, 0);
623   return writeUInt16(this, value, offset, true);
624 };
625
626
627 function writeUInt32(buffer, value, offset, isBigEndian) {
628   if (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;
633   } else {
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;
638   }
639   return offset + 4;
640 }
641
642
643 Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
644   value = +value;
645   offset = ~~offset;
646   if (!noAssert)
647     checkInt(this, value, offset, 4, 0xffffffff, 0);
648   return writeUInt32(this, value, offset, false);
649 };
650
651
652 Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
653   value = +value;
654   offset = ~~offset;
655   if (!noAssert)
656     checkInt(this, value, offset, 4, 0xffffffff, 0);
657   return writeUInt32(this, value, offset, true);
658 };
659
660
661 /*
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:
667  *
668  * > -32 & 0xff
669  * 224
670  *
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.
673  *
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:
677  *
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
685  *
686  *
687  * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If
688  * you do out the computations:
689  *
690  * 0xffff - 128 + 1
691  * 0xffff - 127
692  * 0xff80
693  *
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.
696  */
697
698 Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
699   value = +value;
700   offset = ~~offset;
701   if (!noAssert)
702     checkInt(this, value, offset, 1, 0x7f, -0x80);
703   if (value < 0) value = 0xff + value + 1;
704   this[offset] = value;
705   return offset + 1;
706 };
707
708
709 Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
710   value = +value;
711   offset = ~~offset;
712   if (!noAssert)
713     checkInt(this, value, offset, 2, 0x7fff, -0x8000);
714   if (value < 0) value = 0xffff + value + 1;
715   return writeUInt16(this, value, offset, false);
716 };
717
718
719 Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
720   value = +value;
721   offset = ~~offset;
722   if (!noAssert)
723     checkInt(this, value, offset, 2, 0x7fff, -0x8000);
724   if (value < 0) value = 0xffff + value + 1;
725   return writeUInt16(this, value, offset, true);
726 };
727
728
729 Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
730   value = +value;
731   offset = ~~offset;
732   if (!noAssert)
733     checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
734   if (value < 0) value = 0xffffffff + value + 1;
735   return writeUInt32(this, value, offset, false);
736 };
737
738
739 Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
740   value = +value;
741   offset = ~~offset;
742   if (!noAssert)
743     checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
744   if (value < 0) value = 0xffffffff + value + 1;
745   return writeUInt32(this, value, offset, true);
746 };