Merge remote-tracking branch 'upstream/v0.10'
[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
35 Buffer.poolSize = 8 * 1024;
36 var poolSize = Buffer.poolSize;
37 var poolOffset = 0;
38 var allocPool = alloc({}, poolSize);
39
40
41 function createPool() {
42   poolSize = Buffer.poolSize;
43   allocPool = alloc({}, poolSize);
44   poolOffset = 0;
45 }
46
47
48 function Buffer(subject, encoding) {
49   if (!util.isBuffer(this))
50     return new Buffer(subject, encoding);
51
52   if (util.isNumber(subject))
53     this.length = subject > 0 ? Math.floor(subject) : 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;
58   else
59     throw new TypeError('must start with number, buffer, array or string');
60
61   if (this.length > kMaxLength)
62     throw new RangeError('length > kMaxLength');
63
64   if (this.length < Buffer.poolSize / 2 && this.length > 0) {
65     if (this.length > poolSize - poolOffset)
66       createPool();
67     this.parent = sliceOnto(allocPool,
68                             this,
69                             poolOffset,
70                             poolOffset + this.length);
71     poolOffset += this.length;
72   } else {
73     alloc(this, this.length);
74   }
75
76   if (!util.isNumber(subject)) {
77     if (util.isString(subject)) {
78       // FIXME: the number of bytes hasn't changed, so why change the length?
79       this.length = this.write(subject, 0, encoding);
80     } else {
81       if (util.isBuffer(subject))
82         subject.copy(this, 0, 0, this.length);
83       else if (util.isNumber(subject.length) || util.isArray(subject))
84         for (var i = 0; i < this.length; i++)
85           this[i] = subject[i];
86     }
87   }
88 }
89
90
91 function SlowBuffer(length) {
92   length = length >>> 0;
93   if (length > kMaxLength)
94     throw new RangeError('length > kMaxLength');
95   var b = new NativeBuffer(length);
96   alloc(b, length);
97   return b;
98 }
99
100
101 // Bypass all checks for instantiating unallocated Buffer required for
102 // Objects created in C++. Significantly faster than calling the Buffer
103 // function.
104 function NativeBuffer(length) {
105   this.length = length;
106 }
107 NativeBuffer.prototype = Buffer.prototype;
108
109
110 // add methods to Buffer prototype
111 buffer.setupBufferJS(NativeBuffer, internal);
112
113
114 // Static methods
115
116 Buffer.isBuffer = function isBuffer(b) {
117   return util.isBuffer(b);
118 };
119
120
121 Buffer.isEncoding = function(encoding) {
122   switch ((encoding + '').toLowerCase()) {
123     case 'hex':
124     case 'utf8':
125     case 'utf-8':
126     case 'ascii':
127     case 'binary':
128     case 'base64':
129     case 'ucs2':
130     case 'ucs-2':
131     case 'utf16le':
132     case 'utf-16le':
133     case 'raw':
134       return true;
135
136     default:
137       return false;
138   }
139 };
140
141
142 Buffer.concat = function(list, length) {
143   if (!util.isArray(list))
144     throw new TypeError('Usage: Buffer.concat(list[, length])');
145
146   if (util.isUndefined(length)) {
147     length = 0;
148     for (var i = 0; i < list.length; i++)
149       length += list[i].length;
150   } else {
151     length = ~~length;
152   }
153
154   if (length < 0) length = 0;
155
156   if (list.length === 0)
157     return new Buffer(0);
158   else if (list.length === 1)
159     return list[0];
160
161   var buffer = new Buffer(length);
162   var pos = 0;
163   for (var i = 0; i < list.length; i++) {
164     var buf = list[i];
165     buf.copy(buffer, pos);
166     pos += buf.length;
167   }
168
169   return buffer;
170 };
171
172
173 Buffer.byteLength = function(str, enc) {
174   var ret;
175   str = str + '';
176   switch (enc) {
177     case 'ascii':
178     case 'binary':
179     case 'raw':
180       ret = str.length;
181       break;
182     case 'ucs2':
183     case 'ucs-2':
184     case 'utf16le':
185     case 'utf-16le':
186       ret = str.length * 2;
187       break;
188     case 'hex':
189       ret = str.length >>> 1;
190       break;
191     default:
192       ret = internal.byteLength(str, enc);
193   }
194   return ret;
195 };
196
197
198 // pre-set for values that may exist in the future
199 Buffer.prototype.length = undefined;
200 Buffer.prototype.parent = undefined;
201
202
203 // toString(encoding, start=0, end=buffer.length)
204 Buffer.prototype.toString = function(encoding, start, end) {
205   var loweredCase = false;
206
207   start = start >>> 0;
208   end = util.isUndefined(end) ? this.length : end >>> 0;
209
210   if (!encoding) encoding = 'utf8';
211   if (start < 0) start = 0;
212   if (end > this.length) end = this.length;
213   if (end <= start) return '';
214
215   while (true) {
216     switch (encoding) {
217       case 'hex':
218         return this.hexSlice(start, end);
219
220       case 'utf8':
221       case 'utf-8':
222         return this.utf8Slice(start, end);
223
224       case 'ascii':
225         return this.asciiSlice(start, end);
226
227       case 'binary':
228         return this.binarySlice(start, end);
229
230       case 'base64':
231         return this.base64Slice(start, end);
232
233       case 'ucs2':
234       case 'ucs-2':
235       case 'utf16le':
236       case 'utf-16le':
237         return this.ucs2Slice(start, end);
238
239       default:
240         if (loweredCase)
241           throw new TypeError('Unknown encoding: ' + encoding);
242         encoding = (encoding + '').toLowerCase();
243         loweredCase = true;
244     }
245   }
246 };
247
248
249 // Inspect
250 Buffer.prototype.inspect = function inspect() {
251   var str = '';
252   var max = exports.INSPECT_MAX_BYTES;
253   if (this.length > 0) {
254     str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
255     if (this.length > max)
256       str += ' ... ';
257   }
258   return '<' + this.constructor.name + ' ' + str + '>';
259 };
260
261
262 // XXX remove in v0.13
263 Buffer.prototype.get = util.deprecate(function get(offset) {
264   offset = ~~offset;
265   if (offset < 0 || offset >= this.length)
266     throw new RangeError('index out of range');
267   return this[offset];
268 }, '.get() is deprecated. Access using array indexes instead.');
269
270
271 // XXX remove in v0.13
272 Buffer.prototype.set = util.deprecate(function set(offset, v) {
273   offset = ~~offset;
274   if (offset < 0 || offset >= this.length)
275     throw new RangeError('index out of range');
276   return this[offset] = v;
277 }, '.set() is deprecated. Set using array indexes instead.');
278
279
280 // TODO(trevnorris): fix these checks to follow new standard
281 // write(string, offset = 0, length = buffer.length, encoding = 'utf8')
282 var writeWarned = false;
283 var writeMsg = '.write(string, encoding, offset, length) is deprecated.' +
284                ' Use write(string, offset, length, encoding) instead.';
285 Buffer.prototype.write = function(string, offset, length, encoding) {
286   // allow write(string, encoding)
287   if (util.isString(offset) && util.isUndefined(length)) {
288     encoding = offset;
289     offset = 0;
290
291   // allow write(string, offset[, length], encoding)
292   } else if (isFinite(offset)) {
293     offset = ~~offset;
294     if (isFinite(length)) {
295       length = ~~length;
296     } else {
297       encoding = length;
298       length = undefined;
299     }
300
301   // XXX legacy write(string, encoding, offset, length) - remove in v0.13
302   } else {
303     if (!writeWarned) {
304       if (process.throwDeprecation)
305         throw new Error(writeMsg);
306       else if (process.traceDeprecation)
307         console.trace(writeMsg);
308       else
309         console.error(writeMsg);
310       writeWarned = true;
311     }
312
313     var swap = encoding;
314     encoding = offset;
315     offset = ~~length;
316     length = swap;
317   }
318
319   var remaining = this.length - offset;
320   if (util.isUndefined(length) || length > remaining)
321     length = remaining;
322
323   encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
324
325   if (string.length > 0 && (length < 0 || offset < 0))
326     throw new RangeError('attempt to write beyond buffer bounds');
327
328   var ret;
329   switch (encoding) {
330     case 'hex':
331       ret = this.hexWrite(string, offset, length);
332       break;
333
334     case 'utf8':
335     case 'utf-8':
336       ret = this.utf8Write(string, offset, length);
337       break;
338
339     case 'ascii':
340       ret = this.asciiWrite(string, offset, length);
341       break;
342
343     case 'binary':
344       ret = this.binaryWrite(string, offset, length);
345       break;
346
347     case 'base64':
348       // Warning: maxLength not taken into account in base64Write
349       ret = this.base64Write(string, offset, length);
350       break;
351
352     case 'ucs2':
353     case 'ucs-2':
354     case 'utf16le':
355     case 'utf-16le':
356       ret = this.ucs2Write(string, offset, length);
357       break;
358
359     default:
360       throw new TypeError('Unknown encoding: ' + encoding);
361   }
362
363   return ret;
364 };
365
366
367 Buffer.prototype.toJSON = function() {
368   return {
369     type: 'Buffer',
370     data: Array.prototype.slice.call(this, 0)
371   };
372 };
373
374
375 // TODO(trevnorris): currently works like Array.prototype.slice(), which
376 // doesn't follow the new standard for throwing on out of range indexes.
377 Buffer.prototype.slice = function(start, end) {
378   var len = this.length;
379   start = ~~start;
380   end = util.isUndefined(end) ? len : ~~end;
381
382   if (start < 0) {
383     start += len;
384     if (start < 0)
385       start = 0;
386   } else if (start > len) {
387     start = len;
388   }
389
390   if (end < 0) {
391     end += len;
392     if (end < 0)
393       end = 0;
394   } else if (end > len) {
395     end = len;
396   }
397
398   if (end < start)
399     end = start;
400
401   var buf = new NativeBuffer();
402   sliceOnto(this, buf, start, end);
403   buf.length = end - start;
404   if (buf.length > 0)
405     buf.parent = util.isUndefined(this.parent) ? this : this.parent;
406
407   return buf;
408 };
409
410
411 function checkOffset(offset, ext, length) {
412   if (offset < 0 || offset + ext > length)
413     throw new RangeError('index out of range');
414 }
415
416
417 Buffer.prototype.readUInt8 = function(offset, noAssert) {
418   offset = ~~offset;
419   if (!noAssert)
420     checkOffset(offset, 1, this.length);
421   return this[offset];
422 };
423
424
425 function readUInt16(buffer, offset, isBigEndian) {
426   var val = 0;
427   if (isBigEndian) {
428     val = buffer[offset] << 8;
429     val |= buffer[offset + 1];
430   } else {
431     val = buffer[offset];
432     val |= buffer[offset + 1] << 8;
433   }
434   return val;
435 }
436
437
438 Buffer.prototype.readUInt16LE = function(offset, noAssert) {
439   offset = ~~offset;
440   if (!noAssert)
441     checkOffset(offset, 2, this.length);
442   return readUInt16(this, offset, false, noAssert);
443 };
444
445
446 Buffer.prototype.readUInt16BE = function(offset, noAssert) {
447   offset = ~~offset;
448   if (!noAssert)
449     checkOffset(offset, 2, this.length);
450   return readUInt16(this, offset, true, noAssert);
451 };
452
453
454 function readUInt32(buffer, offset, isBigEndian) {
455   var val = 0;
456   if (isBigEndian) {
457     val = buffer[offset + 1] << 16;
458     val |= buffer[offset + 2] << 8;
459     val |= buffer[offset + 3];
460     val = val + (buffer[offset] << 24 >>> 0);
461   } else {
462     val = buffer[offset + 2] << 16;
463     val |= buffer[offset + 1] << 8;
464     val |= buffer[offset];
465     val = val + (buffer[offset + 3] << 24 >>> 0);
466   }
467   return val;
468 }
469
470
471 Buffer.prototype.readUInt32LE = function(offset, noAssert) {
472   offset = ~~offset;
473   if (!noAssert)
474     checkOffset(offset, 4, this.length);
475   return readUInt32(this, offset, false);
476 };
477
478
479 Buffer.prototype.readUInt32BE = function(offset, noAssert) {
480   offset = ~~offset;
481   if (!noAssert)
482     checkOffset(offset, 4, this.length);
483   return readUInt32(this, offset, true);
484 };
485
486
487 /*
488  * Signed integer types, yay team! A reminder on how two's complement actually
489  * works. The first bit is the signed bit, i.e. tells us whether or not the
490  * number should be positive or negative. If the two's complement value is
491  * positive, then we're done, as it's equivalent to the unsigned representation.
492  *
493  * Now if the number is positive, you're pretty much done, you can just leverage
494  * the unsigned translations and return those. Unfortunately, negative numbers
495  * aren't quite that straightforward.
496  *
497  * At first glance, one might be inclined to use the traditional formula to
498  * translate binary numbers between the positive and negative values in two's
499  * complement. (Though it doesn't quite work for the most negative value)
500  * Mainly:
501  *  - invert all the bits
502  *  - add one to the result
503  *
504  * Of course, this doesn't quite work in Javascript. Take for example the value
505  * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of
506  * course, Javascript will do the following:
507  *
508  * > ~0xff80
509  * -65409
510  *
511  * Whoh there, Javascript, that's not quite right. But wait, according to
512  * Javascript that's perfectly correct. When Javascript ends up seeing the
513  * constant 0xff80, it has no notion that it is actually a signed number. It
514  * assumes that we've input the unsigned value 0xff80. Thus, when it does the
515  * binary negation, it casts it into a signed value, (positive 0xff80). Then
516  * when you perform binary negation on that, it turns it into a negative number.
517  *
518  * Instead, we're going to have to use the following general formula, that works
519  * in a rather Javascript friendly way. I'm glad we don't support this kind of
520  * weird numbering scheme in the kernel.
521  *
522  * (BIT-MAX - (unsigned)val + 1) * -1
523  *
524  * The astute observer, may think that this doesn't make sense for 8-bit numbers
525  * (really it isn't necessary for them). However, when you get 16-bit numbers,
526  * you do. Let's go back to our prior example and see how this will look:
527  *
528  * (0xffff - 0xff80 + 1) * -1
529  * (0x007f + 1) * -1
530  * (0x0080) * -1
531  */
532
533 Buffer.prototype.readInt8 = function(offset, noAssert) {
534   offset = ~~offset;
535   if (!noAssert)
536     checkOffset(offset, 1, this.length);
537   if (!(this[offset] & 0x80))
538     return (this[offset]);
539   return ((0xff - this[offset] + 1) * -1);
540 };
541
542
543 function readInt16(buffer, offset, isBigEndian) {
544   var val = readUInt16(buffer, offset, isBigEndian);
545   if (!(val & 0x8000))
546     return val;
547   return (0xffff - val + 1) * -1;
548 }
549
550
551 Buffer.prototype.readInt16LE = function(offset, noAssert) {
552   offset = ~~offset;
553   if (!noAssert)
554     checkOffset(offset, 2, this.length);
555   return readInt16(this, offset, false);
556 };
557
558
559 Buffer.prototype.readInt16BE = function(offset, noAssert) {
560   offset = ~~offset;
561   if (!noAssert)
562     checkOffset(offset, 2, this.length);
563   return readInt16(this, offset, true);
564 };
565
566
567 function readInt32(buffer, offset, isBigEndian) {
568   var val = readUInt32(buffer, offset, isBigEndian);
569   if (!(val & 0x80000000))
570     return (val);
571   return (0xffffffff - val + 1) * -1;
572 }
573
574
575 Buffer.prototype.readInt32LE = function(offset, noAssert) {
576   offset = ~~offset;
577   if (!noAssert)
578     checkOffset(offset, 4, this.length);
579   return readInt32(this, offset, false);
580 };
581
582
583 Buffer.prototype.readInt32BE = function(offset, noAssert) {
584   offset = ~~offset;
585   if (!noAssert)
586     checkOffset(offset, 4, this.length);
587   return readInt32(this, offset, true);
588 };
589
590
591 function checkInt(buffer, value, offset, ext, max, min) {
592   if (value > max || value < min)
593     throw new TypeError('value is out of bounds');
594   if (offset < 0 || offset + ext > buffer.length || buffer.length + offset < 0)
595     throw new RangeError('index out of range');
596 }
597
598
599 Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
600   value = +value;
601   offset = ~~offset;
602   if (!noAssert)
603     checkInt(this, value, offset, 1, 0xff, 0);
604   this[offset] = value;
605   return offset + 1;
606 };
607
608
609 function writeUInt16(buffer, value, offset, isBigEndian) {
610   if (isBigEndian) {
611     buffer[offset] = (value & 0xff00) >>> 8;
612     buffer[offset + 1] = value & 0x00ff;
613   } else {
614     buffer[offset + 1] = (value & 0xff00) >>> 8;
615     buffer[offset] = value & 0x00ff;
616   }
617   return offset + 2;
618 }
619
620
621 Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
622   value = +value;
623   offset = ~~offset;
624   if (!noAssert)
625     checkInt(this, value, offset, 2, 0xffff, 0);
626   return writeUInt16(this, value, offset, false);
627 };
628
629
630 Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
631   value = +value;
632   offset = ~~offset;
633   if (!noAssert)
634     checkInt(this, value, offset, 2, 0xffff, 0);
635   return writeUInt16(this, value, offset, true);
636 };
637
638
639 function writeUInt32(buffer, value, offset, isBigEndian) {
640   if (isBigEndian) {
641     buffer[offset] = (value >>> 24) & 0xff;
642     buffer[offset + 1] = (value >>> 16) & 0xff;
643     buffer[offset + 2] = (value >>> 8) & 0xff;
644     buffer[offset + 3] = value & 0xff;
645   } else {
646     buffer[offset + 3] = (value >>> 24) & 0xff;
647     buffer[offset + 2] = (value >>> 16) & 0xff;
648     buffer[offset + 1] = (value >>> 8) & 0xff;
649     buffer[offset] = value & 0xff;
650   }
651   return offset + 4;
652 }
653
654
655 Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
656   value = +value;
657   offset = ~~offset;
658   if (!noAssert)
659     checkInt(this, value, offset, 4, 0xffffffff, 0);
660   return writeUInt32(this, value, offset, false);
661 };
662
663
664 Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
665   value = +value;
666   offset = ~~offset;
667   if (!noAssert)
668     checkInt(this, value, offset, 4, 0xffffffff, 0);
669   return writeUInt32(this, value, offset, true);
670 };
671
672
673 /*
674  * We now move onto our friends in the signed number category. Unlike unsigned
675  * numbers, we're going to have to worry a bit more about how we put values into
676  * arrays. Since we are only worrying about signed 32-bit values, we're in
677  * slightly better shape. Unfortunately, we really can't do our favorite binary
678  * & in this system. It really seems to do the wrong thing. For example:
679  *
680  * > -32 & 0xff
681  * 224
682  *
683  * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of
684  * this aren't treated as a signed number. Ultimately a bad thing.
685  *
686  * What we're going to want to do is basically create the unsigned equivalent of
687  * our representation and pass that off to the wuint* functions. To do that
688  * we're going to do the following:
689  *
690  *  - if the value is positive
691  *      we can pass it directly off to the equivalent wuint
692  *  - if the value is negative
693  *      we do the following computation:
694  *         mb + val + 1, where
695  *         mb   is the maximum unsigned value in that byte size
696  *         val  is the Javascript negative integer
697  *
698  *
699  * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If
700  * you do out the computations:
701  *
702  * 0xffff - 128 + 1
703  * 0xffff - 127
704  * 0xff80
705  *
706  * You can then encode this value as the signed version. This is really rather
707  * hacky, but it should work and get the job done which is our goal here.
708  */
709
710 Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
711   value = +value;
712   offset = ~~offset;
713   if (!noAssert)
714     checkInt(this, value, offset, 1, 0x7f, -0x80);
715   if (value < 0) value = 0xff + value + 1;
716   this[offset] = value;
717   return offset + 1;
718 };
719
720
721 Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
722   value = +value;
723   offset = ~~offset;
724   if (!noAssert)
725     checkInt(this, value, offset, 2, 0x7fff, -0x8000);
726   if (value < 0) value = 0xffff + value + 1;
727   return writeUInt16(this, value, offset, false);
728 };
729
730
731 Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
732   value = +value;
733   offset = ~~offset;
734   if (!noAssert)
735     checkInt(this, value, offset, 2, 0x7fff, -0x8000);
736   if (value < 0) value = 0xffff + value + 1;
737   return writeUInt16(this, value, offset, true);
738 };
739
740
741 Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
742   value = +value;
743   offset = ~~offset;
744   if (!noAssert)
745     checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
746   if (value < 0) value = 0xffffffff + value + 1;
747   return writeUInt32(this, value, offset, false);
748 };
749
750
751 Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
752   value = +value;
753   offset = ~~offset;
754   if (!noAssert)
755     checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
756   if (value < 0) value = 0xffffffff + value + 1;
757   return writeUInt32(this, value, offset, true);
758 };