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