buffer: Fix incorrect Buffer.compare behavior
[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 truncate = smalloc.truncate;
27 var sliceOnto = smalloc.sliceOnto;
28 var kMaxLength = smalloc.kMaxLength;
29 var internal = {};
30
31 exports.Buffer = Buffer;
32 exports.SlowBuffer = SlowBuffer;
33 exports.INSPECT_MAX_BYTES = 50;
34
35
36 Buffer.poolSize = 8 * 1024;
37 var poolSize, poolOffset, allocPool;
38
39
40 function createPool() {
41   poolSize = Buffer.poolSize;
42   allocPool = alloc({}, poolSize);
43   poolOffset = 0;
44 }
45 createPool();
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 ? subject >>> 0 : 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('Attempt to allocate Buffer larger than maximum ' +
63                          'size: 0x' + kMaxLength.toString(16) + ' bytes');
64   }
65
66   if (this.length <= (Buffer.poolSize >>> 1) && this.length > 0) {
67     if (this.length > poolSize - poolOffset)
68       createPool();
69     this.parent = sliceOnto(allocPool,
70                             this,
71                             poolOffset,
72                             poolOffset + this.length);
73     poolOffset += this.length;
74   } else {
75     alloc(this, this.length);
76   }
77
78   if (!util.isNumber(subject)) {
79     if (util.isString(subject)) {
80       // In the case of base64 it's possible that the size of the buffer
81       // allocated was slightly too large. In this case we need to rewrite
82       // the length to the actual length written.
83       var len = this.write(subject, encoding);
84
85       // Buffer was truncated after decode, realloc internal ExternalArray
86       if (len !== this.length) {
87         this.length = len;
88         truncate(this, this.length);
89       }
90     } else {
91       if (util.isBuffer(subject))
92         subject.copy(this, 0, 0, this.length);
93       else if (util.isNumber(subject.length) || util.isArray(subject))
94         for (var i = 0; i < this.length; i++)
95           this[i] = subject[i];
96     }
97   }
98 }
99
100
101 function SlowBuffer(length) {
102   length = length >>> 0;
103   if (length > kMaxLength) {
104     throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
105                          'size: 0x' + kMaxLength.toString(16) + ' bytes');
106   }
107   var b = new NativeBuffer(length);
108   alloc(b, length);
109   return b;
110 }
111
112
113 // Bypass all checks for instantiating unallocated Buffer required for
114 // Objects created in C++. Significantly faster than calling the Buffer
115 // function.
116 function NativeBuffer(length) {
117   this.length = length;
118 }
119 NativeBuffer.prototype = Buffer.prototype;
120
121
122 // add methods to Buffer prototype
123 buffer.setupBufferJS(NativeBuffer, internal);
124
125
126 // Static methods
127
128 Buffer.isBuffer = function isBuffer(b) {
129   return util.isBuffer(b);
130 };
131
132
133 Buffer.compare = function compare(a, b) {
134   if (!(a instanceof Buffer) ||
135       !(b instanceof Buffer))
136     throw new TypeError('Arguments must be Buffers');
137
138   return internal.compare(a, b);
139 };
140
141
142 Buffer.isEncoding = function(encoding) {
143   switch ((encoding + '').toLowerCase()) {
144     case 'hex':
145     case 'utf8':
146     case 'utf-8':
147     case 'ascii':
148     case 'binary':
149     case 'base64':
150     case 'ucs2':
151     case 'ucs-2':
152     case 'utf16le':
153     case 'utf-16le':
154     case 'raw':
155       return true;
156
157     default:
158       return false;
159   }
160 };
161
162
163 Buffer.concat = function(list, length) {
164   if (!util.isArray(list))
165     throw new TypeError('Usage: Buffer.concat(list[, length])');
166
167   if (util.isUndefined(length)) {
168     length = 0;
169     for (var i = 0; i < list.length; i++)
170       length += list[i].length;
171   } else {
172     length = length >>> 0;
173   }
174
175   if (list.length === 0)
176     return new Buffer(0);
177   else if (list.length === 1)
178     return list[0];
179
180   var buffer = new Buffer(length);
181   var pos = 0;
182   for (var i = 0; i < list.length; i++) {
183     var buf = list[i];
184     buf.copy(buffer, pos);
185     pos += buf.length;
186   }
187
188   return buffer;
189 };
190
191
192 Buffer.byteLength = function(str, enc) {
193   var ret;
194   str = str + '';
195   switch (enc) {
196     case 'ascii':
197     case 'binary':
198     case 'raw':
199       ret = str.length;
200       break;
201     case 'ucs2':
202     case 'ucs-2':
203     case 'utf16le':
204     case 'utf-16le':
205       ret = str.length * 2;
206       break;
207     case 'hex':
208       ret = str.length >>> 1;
209       break;
210     default:
211       ret = internal.byteLength(str, enc);
212   }
213   return ret;
214 };
215
216
217 // pre-set for values that may exist in the future
218 Buffer.prototype.length = undefined;
219 Buffer.prototype.parent = undefined;
220
221
222 // toString(encoding, start=0, end=buffer.length)
223 Buffer.prototype.toString = function(encoding, start, end) {
224   var loweredCase = false;
225
226   start = start >>> 0;
227   end = util.isUndefined(end) || end === Infinity ? this.length : end >>> 0;
228
229   if (!encoding) encoding = 'utf8';
230   if (start < 0) start = 0;
231   if (end > this.length) end = this.length;
232   if (end <= start) return '';
233
234   while (true) {
235     switch (encoding) {
236       case 'hex':
237         return this.hexSlice(start, end);
238
239       case 'utf8':
240       case 'utf-8':
241         return this.utf8Slice(start, end);
242
243       case 'ascii':
244         return this.asciiSlice(start, end);
245
246       case 'binary':
247         return this.binarySlice(start, end);
248
249       case 'base64':
250         return this.base64Slice(start, end);
251
252       case 'ucs2':
253       case 'ucs-2':
254       case 'utf16le':
255       case 'utf-16le':
256         return this.ucs2Slice(start, end);
257
258       default:
259         if (loweredCase)
260           throw new TypeError('Unknown encoding: ' + encoding);
261         encoding = (encoding + '').toLowerCase();
262         loweredCase = true;
263     }
264   }
265 };
266
267
268 Buffer.prototype.equals = function equals(b) {
269   if (!(b instanceof Buffer))
270     throw new TypeError('Argument must be a Buffer');
271
272   return internal.compare(this, b) === 0;
273 };
274
275
276 // Inspect
277 Buffer.prototype.inspect = function inspect() {
278   var str = '';
279   var max = exports.INSPECT_MAX_BYTES;
280   if (this.length > 0) {
281     str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
282     if (this.length > max)
283       str += ' ... ';
284   }
285   return '<' + this.constructor.name + ' ' + str + '>';
286 };
287
288
289 Buffer.prototype.compare = function compare(b) {
290   if (!(b instanceof Buffer))
291     throw new TypeError('Argument must be a Buffer');
292
293   return internal.compare(this, b);
294 };
295
296
297 // XXX remove in v0.13
298 Buffer.prototype.get = util.deprecate(function get(offset) {
299   offset = ~~offset;
300   if (offset < 0 || offset >= this.length)
301     throw new RangeError('index out of range');
302   return this[offset];
303 }, '.get() is deprecated. Access using array indexes instead.');
304
305
306 // XXX remove in v0.13
307 Buffer.prototype.set = util.deprecate(function set(offset, v) {
308   offset = ~~offset;
309   if (offset < 0 || offset >= this.length)
310     throw new RangeError('index out of range');
311   return this[offset] = v;
312 }, '.set() is deprecated. Set using array indexes instead.');
313
314
315 // TODO(trevnorris): fix these checks to follow new standard
316 // write(string, offset = 0, length = buffer.length, encoding = 'utf8')
317 var writeWarned = false;
318 var writeMsg = '.write(string, encoding, offset, length) is deprecated.' +
319                ' Use write(string[, offset[, length]][, encoding]) instead.';
320 Buffer.prototype.write = function(string, offset, length, encoding) {
321   // Buffer#write(string);
322   if (util.isUndefined(offset)) {
323     encoding = 'utf8';
324     length = this.length;
325     offset = 0;
326
327   // Buffer#write(string, encoding)
328   } else if (util.isUndefined(length) && util.isString(offset)) {
329     encoding = offset;
330     length = this.length;
331     offset = 0;
332
333   // Buffer#write(string, offset[, length][, encoding])
334   } else if (isFinite(offset)) {
335     offset = offset >>> 0;
336     if (isFinite(length)) {
337       length = length >>> 0;
338       if (util.isUndefined(encoding))
339         encoding = 'utf8';
340     } else {
341       encoding = length;
342       length = undefined;
343     }
344
345   // XXX legacy write(string, encoding, offset, length) - remove in v0.13
346   } else {
347     if (!writeWarned) {
348       if (process.throwDeprecation)
349         throw new Error(writeMsg);
350       else if (process.traceDeprecation)
351         console.trace(writeMsg);
352       else
353         console.error(writeMsg);
354       writeWarned = true;
355     }
356
357     var swap = encoding;
358     encoding = offset;
359     offset = length >>> 0;
360     length = swap;
361   }
362
363   var remaining = this.length - offset;
364   if (util.isUndefined(length) || length > remaining)
365     length = remaining;
366
367   encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
368
369   if (string.length > 0 && (length < 0 || offset < 0))
370     throw new RangeError('attempt to write outside buffer bounds');
371
372   var ret;
373   switch (encoding) {
374     case 'hex':
375       ret = this.hexWrite(string, offset, length);
376       break;
377
378     case 'utf8':
379     case 'utf-8':
380       ret = this.utf8Write(string, offset, length);
381       break;
382
383     case 'ascii':
384       ret = this.asciiWrite(string, offset, length);
385       break;
386
387     case 'binary':
388       ret = this.binaryWrite(string, offset, length);
389       break;
390
391     case 'base64':
392       // Warning: maxLength not taken into account in base64Write
393       ret = this.base64Write(string, offset, length);
394       break;
395
396     case 'ucs2':
397     case 'ucs-2':
398     case 'utf16le':
399     case 'utf-16le':
400       ret = this.ucs2Write(string, offset, length);
401       break;
402
403     default:
404       throw new TypeError('Unknown encoding: ' + encoding);
405   }
406
407   return ret;
408 };
409
410
411 Buffer.prototype.toJSON = function() {
412   return {
413     type: 'Buffer',
414     data: Array.prototype.slice.call(this, 0)
415   };
416 };
417
418
419 // TODO(trevnorris): currently works like Array.prototype.slice(), which
420 // doesn't follow the new standard for throwing on out of range indexes.
421 Buffer.prototype.slice = function(start, end) {
422   var len = this.length;
423   start = ~~start;
424   end = util.isUndefined(end) ? len : ~~end;
425
426   if (start < 0) {
427     start += len;
428     if (start < 0)
429       start = 0;
430   } else if (start > len) {
431     start = len;
432   }
433
434   if (end < 0) {
435     end += len;
436     if (end < 0)
437       end = 0;
438   } else if (end > len) {
439     end = len;
440   }
441
442   if (end < start)
443     end = start;
444
445   var buf = new NativeBuffer();
446   sliceOnto(this, buf, start, end);
447   buf.length = end - start;
448   if (buf.length > 0)
449     buf.parent = util.isUndefined(this.parent) ? this : this.parent;
450
451   return buf;
452 };
453
454
455 function checkOffset(offset, ext, length) {
456   if (offset + ext > length)
457     throw new RangeError('index out of range');
458 }
459
460
461 Buffer.prototype.readUInt8 = function(offset, noAssert) {
462   offset = offset >>> 0;
463   if (!noAssert)
464     checkOffset(offset, 1, this.length);
465   return this[offset];
466 };
467
468
469 Buffer.prototype.readUInt16LE = function(offset, noAssert) {
470   offset = offset >>> 0;
471   if (!noAssert)
472     checkOffset(offset, 2, this.length);
473   return this[offset] | (this[offset + 1] << 8);
474 };
475
476
477 Buffer.prototype.readUInt16BE = function(offset, noAssert) {
478   offset = offset >>> 0;
479   if (!noAssert)
480     checkOffset(offset, 2, this.length);
481   return (this[offset] << 8) | this[offset + 1];
482 };
483
484
485 Buffer.prototype.readUInt32LE = function(offset, noAssert) {
486   offset = offset >>> 0;
487   if (!noAssert)
488     checkOffset(offset, 4, this.length);
489
490   return ((this[offset]) |
491       (this[offset + 1] << 8) |
492       (this[offset + 2] << 16)) +
493       (this[offset + 3] * 0x1000000);
494 };
495
496
497 Buffer.prototype.readUInt32BE = function(offset, noAssert) {
498   offset = offset >>> 0;
499   if (!noAssert)
500     checkOffset(offset, 4, this.length);
501
502   return (this[offset] * 0x1000000) +
503       ((this[offset + 1] << 16) |
504       (this[offset + 2] << 8) |
505       (this[offset + 3]) >>> 0);
506 };
507
508
509 Buffer.prototype.readInt8 = function(offset, noAssert) {
510   offset = offset >>> 0;
511   if (!noAssert)
512     checkOffset(offset, 1, this.length);
513   var val = this[offset];
514   return !(val & 0x80) ? val : (0xff - val + 1) * -1;
515 };
516
517
518 Buffer.prototype.readInt16LE = function(offset, noAssert) {
519   offset = offset >>> 0;
520   if (!noAssert)
521     checkOffset(offset, 2, this.length);
522   var val = this[offset] | (this[offset + 1] << 8);
523   return (val & 0x8000) ? val | 0xFFFF0000 : val;
524 };
525
526
527 Buffer.prototype.readInt16BE = function(offset, noAssert) {
528   offset = offset >>> 0;
529   if (!noAssert)
530     checkOffset(offset, 2, this.length);
531   var val = this[offset + 1] | (this[offset] << 8);
532   return (val & 0x8000) ? val | 0xFFFF0000 : val;
533 };
534
535
536 Buffer.prototype.readInt32LE = function(offset, noAssert) {
537   offset = offset >>> 0;
538   if (!noAssert)
539     checkOffset(offset, 4, this.length);
540
541   return (this[offset]) |
542       (this[offset + 1] << 8) |
543       (this[offset + 2] << 16) |
544       (this[offset + 3] << 24);
545 };
546
547
548 Buffer.prototype.readInt32BE = function(offset, noAssert) {
549   offset = offset >>> 0;
550   if (!noAssert)
551     checkOffset(offset, 4, this.length);
552
553   return (this[offset] << 24) |
554       (this[offset + 1] << 16) |
555       (this[offset + 2] << 8) |
556       (this[offset + 3]);
557 };
558
559
560 function checkInt(buffer, value, offset, ext, max, min) {
561   if (!(buffer instanceof Buffer))
562     throw new TypeError('buffer must be a Buffer instance');
563   if (value > max || value < min)
564     throw new TypeError('value is out of bounds');
565   if (offset + ext > buffer.length)
566     throw new RangeError('index out of range');
567 }
568
569
570 Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
571   value = +value;
572   offset = offset >>> 0;
573   if (!noAssert)
574     checkInt(this, value, offset, 1, 0xff, 0);
575   this[offset] = value;
576   return offset + 1;
577 };
578
579
580 Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
581   value = +value;
582   offset = offset >>> 0;
583   if (!noAssert)
584     checkInt(this, value, offset, 2, 0xffff, 0);
585   this[offset] = value;
586   this[offset + 1] = (value >>> 8);
587   return offset + 2;
588 };
589
590
591 Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
592   value = +value;
593   offset = offset >>> 0;
594   if (!noAssert)
595     checkInt(this, value, offset, 2, 0xffff, 0);
596   this[offset] = (value >>> 8);
597   this[offset + 1] = value;
598   return offset + 2;
599 };
600
601
602 Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
603   value = +value;
604   offset = offset >>> 0;
605   if (!noAssert)
606     checkInt(this, value, offset, 4, 0xffffffff, 0);
607   this[offset + 3] = (value >>> 24);
608   this[offset + 2] = (value >>> 16);
609   this[offset + 1] = (value >>> 8);
610   this[offset] = value;
611   return offset + 4;
612 };
613
614
615 Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
616   value = +value;
617   offset = offset >>> 0;
618   if (!noAssert)
619     checkInt(this, value, offset, 4, 0xffffffff, 0);
620   this[offset] = (value >>> 24);
621   this[offset + 1] = (value >>> 16);
622   this[offset + 2] = (value >>> 8);
623   this[offset + 3] = value;
624   return offset + 4;
625 };
626
627
628 Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
629   value = +value;
630   offset = offset >>> 0;
631   if (!noAssert)
632     checkInt(this, value, offset, 1, 0x7f, -0x80);
633   this[offset] = value;
634   return offset + 1;
635 };
636
637
638 Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
639   value = +value;
640   offset = offset >>> 0;
641   if (!noAssert)
642     checkInt(this, value, offset, 2, 0x7fff, -0x8000);
643   this[offset] = value;
644   this[offset + 1] = (value >>> 8);
645   return offset + 2;
646 };
647
648
649 Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
650   value = +value;
651   offset = offset >>> 0;
652   if (!noAssert)
653     checkInt(this, value, offset, 2, 0x7fff, -0x8000);
654   this[offset] = (value >>> 8);
655   this[offset + 1] = value;
656   return offset + 2;
657 };
658
659
660 Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
661   value = +value;
662   offset = offset >>> 0;
663   if (!noAssert)
664     checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
665   this[offset] = value;
666   this[offset + 1] = (value >>> 8);
667   this[offset + 2] = (value >>> 16);
668   this[offset + 3] = (value >>> 24);
669   return offset + 4;
670 };
671
672
673 Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
674   value = +value;
675   offset = offset >>> 0;
676   if (!noAssert)
677     checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
678   this[offset] = (value >>> 24);
679   this[offset + 1] = (value >>> 16);
680   this[offset + 2] = (value >>> 8);
681   this[offset + 3] = value;
682   return offset + 4;
683 };