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