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