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