buffer: fix minimum values for writeInt*() 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 SlowBuffer = process.binding('buffer').SlowBuffer;
23 var assert = require('assert');
24
25 exports.INSPECT_MAX_BYTES = 50;
26
27
28 function toHex(n) {
29   if (n < 16) return '0' + n.toString(16);
30   return n.toString(16);
31 }
32
33
34 SlowBuffer.prototype.inspect = function() {
35   var out = [],
36       len = this.length;
37   for (var i = 0; i < len; i++) {
38     out[i] = toHex(this[i]);
39     if (i == exports.INSPECT_MAX_BYTES) {
40       out[i + 1] = '...';
41       break;
42     }
43   }
44   return '<SlowBuffer ' + out.join(' ') + '>';
45 };
46
47
48 SlowBuffer.prototype.hexSlice = function(start, end) {
49   var len = this.length;
50
51   if (!start || start < 0) start = 0;
52   if (!end || end < 0 || end > len) end = len;
53
54   var out = '';
55   for (var i = start; i < end; i++) {
56     out += toHex(this[i]);
57   }
58   return out;
59 };
60
61
62
63 SlowBuffer.prototype.toString = function(encoding, start, end) {
64   encoding = String(encoding || 'utf8').toLowerCase();
65   start = +start || 0;
66   if (typeof end == 'undefined') end = this.length;
67
68   // Fastpath empty strings
69   if (+end == start) {
70     return '';
71   }
72
73   switch (encoding) {
74     case 'hex':
75       return this.hexSlice(start, end);
76
77     case 'utf8':
78     case 'utf-8':
79       return this.utf8Slice(start, end);
80
81     case 'ascii':
82       return this.asciiSlice(start, end);
83
84     case 'binary':
85       return this.binarySlice(start, end);
86
87     case 'base64':
88       return this.base64Slice(start, end);
89
90     case 'ucs2':
91     case 'ucs-2':
92       return this.ucs2Slice(start, end);
93
94     default:
95       throw new Error('Unknown encoding');
96   }
97 };
98
99
100 SlowBuffer.prototype.hexWrite = function(string, offset, length) {
101   offset = +offset || 0;
102   var remaining = this.length - offset;
103   if (!length) {
104     length = remaining;
105   } else {
106     length = +length;
107     if (length > remaining) {
108       length = remaining;
109     }
110   }
111
112   // must be an even number of digits
113   var strLen = string.length;
114   if (strLen % 2) {
115     throw new Error('Invalid hex string');
116   }
117   if (length > strLen / 2) {
118     length = strLen / 2;
119   }
120   for (var i = 0; i < length; i++) {
121     var byte = parseInt(string.substr(i * 2, 2), 16);
122     if (isNaN(byte)) throw new Error('Invalid hex string');
123     this[offset + i] = byte;
124   }
125   SlowBuffer._charsWritten = i * 2;
126   return i;
127 };
128
129
130 SlowBuffer.prototype.write = function(string, offset, length, encoding) {
131   // Support both (string, offset, length, encoding)
132   // and the legacy (string, encoding, offset, length)
133   if (isFinite(offset)) {
134     if (!isFinite(length)) {
135       encoding = length;
136       length = undefined;
137     }
138   } else {  // legacy
139     var swap = encoding;
140     encoding = offset;
141     offset = length;
142     length = swap;
143   }
144
145   offset = +offset || 0;
146   var remaining = this.length - offset;
147   if (!length) {
148     length = remaining;
149   } else {
150     length = +length;
151     if (length > remaining) {
152       length = remaining;
153     }
154   }
155   encoding = String(encoding || 'utf8').toLowerCase();
156
157   switch (encoding) {
158     case 'hex':
159       return this.hexWrite(string, offset, length);
160
161     case 'utf8':
162     case 'utf-8':
163       return this.utf8Write(string, offset, length);
164
165     case 'ascii':
166       return this.asciiWrite(string, offset, length);
167
168     case 'binary':
169       return this.binaryWrite(string, offset, length);
170
171     case 'base64':
172       return this.base64Write(string, offset, length);
173
174     case 'ucs2':
175     case 'ucs-2':
176       return this.ucs2Write(string, offset, length);
177
178     default:
179       throw new Error('Unknown encoding');
180   }
181 };
182
183
184 // slice(start, end)
185 SlowBuffer.prototype.slice = function(start, end) {
186   if (end === undefined) end = this.length;
187
188   if (end > this.length) {
189     throw new Error('oob');
190   }
191   if (start > end) {
192     throw new Error('oob');
193   }
194
195   return new Buffer(this, end - start, +start);
196 };
197
198
199 function coerce(length) {
200   // Coerce length to a number (possibly NaN), round up
201   // in case it's fractional (e.g. 123.456) then do a
202   // double negate to coerce a NaN to 0. Easy, right?
203   length = ~~Math.ceil(+length);
204   return length < 0 ? 0 : length;
205 }
206
207
208 // Buffer
209
210 function Buffer(subject, encoding, offset) {
211   if (!(this instanceof Buffer)) {
212     return new Buffer(subject, encoding, offset);
213   }
214
215   var type;
216
217   // Are we slicing?
218   if (typeof offset === 'number') {
219     this.length = coerce(encoding);
220     this.parent = subject;
221     this.offset = offset;
222   } else {
223     // Find the length
224     switch (type = typeof subject) {
225       case 'number':
226         this.length = coerce(subject);
227         break;
228
229       case 'string':
230         this.length = Buffer.byteLength(subject, encoding);
231         break;
232
233       case 'object': // Assume object is an array
234         this.length = coerce(subject.length);
235         break;
236
237       default:
238         throw new Error('First argument needs to be a number, ' +
239                         'array or string.');
240     }
241
242     if (this.length > Buffer.poolSize) {
243       // Big buffer, just alloc one.
244       this.parent = new SlowBuffer(this.length);
245       this.offset = 0;
246
247     } else {
248       // Small buffer.
249       if (!pool || pool.length - pool.used < this.length) allocPool();
250       this.parent = pool;
251       this.offset = pool.used;
252       pool.used += this.length;
253     }
254
255     // Treat array-ish objects as a byte array.
256     if (isArrayIsh(subject)) {
257       for (var i = 0; i < this.length; i++) {
258         this.parent[i + this.offset] = subject[i];
259       }
260     } else if (type == 'string') {
261       // We are a string
262       this.length = this.write(subject, 0, encoding);
263     }
264   }
265
266   SlowBuffer.makeFastBuffer(this.parent, this, this.offset, this.length);
267 }
268
269 function isArrayIsh(subject) {
270   return Array.isArray(subject) || Buffer.isBuffer(subject) ||
271          subject && typeof subject === 'object' &&
272          typeof subject.length === 'number';
273 }
274
275 exports.SlowBuffer = SlowBuffer;
276 exports.Buffer = Buffer;
277
278 Buffer.poolSize = 8 * 1024;
279 var pool;
280
281 function allocPool() {
282   pool = new SlowBuffer(Buffer.poolSize);
283   pool.used = 0;
284 }
285
286
287 // Static methods
288 Buffer.isBuffer = function isBuffer(b) {
289   return b instanceof Buffer || b instanceof SlowBuffer;
290 };
291
292
293 // Inspect
294 Buffer.prototype.inspect = function inspect() {
295   var out = [],
296       len = this.length;
297
298   for (var i = 0; i < len; i++) {
299     out[i] = toHex(this.parent[i + this.offset]);
300     if (i == exports.INSPECT_MAX_BYTES) {
301       out[i + 1] = '...';
302       break;
303     }
304   }
305
306   return '<Buffer ' + out.join(' ') + '>';
307 };
308
309
310 Buffer.prototype.get = function get(i) {
311   if (i < 0 || i >= this.length) throw new Error('oob');
312   return this.parent[this.offset + i];
313 };
314
315
316 Buffer.prototype.set = function set(i, v) {
317   if (i < 0 || i >= this.length) throw new Error('oob');
318   return this.parent[this.offset + i] = v;
319 };
320
321
322 // write(string, offset = 0, length = buffer.length-offset, encoding = 'utf8')
323 Buffer.prototype.write = function(string, offset, length, encoding) {
324   // Support both (string, offset, length, encoding)
325   // and the legacy (string, encoding, offset, length)
326   if (isFinite(offset)) {
327     if (!isFinite(length)) {
328       encoding = length;
329       length = undefined;
330     }
331   } else {  // legacy
332     var swap = encoding;
333     encoding = offset;
334     offset = length;
335     length = swap;
336   }
337
338   offset = +offset || 0;
339   var remaining = this.length - offset;
340   if (!length) {
341     length = remaining;
342   } else {
343     length = +length;
344     if (length > remaining) {
345       length = remaining;
346     }
347   }
348   encoding = String(encoding || 'utf8').toLowerCase();
349
350   var ret;
351   switch (encoding) {
352     case 'hex':
353       ret = this.parent.hexWrite(string, this.offset + offset, length);
354       break;
355
356     case 'utf8':
357     case 'utf-8':
358       ret = this.parent.utf8Write(string, this.offset + offset, length);
359       break;
360
361     case 'ascii':
362       ret = this.parent.asciiWrite(string, this.offset + offset, length);
363       break;
364
365     case 'binary':
366       ret = this.parent.binaryWrite(string, this.offset + offset, length);
367       break;
368
369     case 'base64':
370       // Warning: maxLength not taken into account in base64Write
371       ret = this.parent.base64Write(string, this.offset + offset, length);
372       break;
373
374     case 'ucs2':
375     case 'ucs-2':
376       ret = this.parent.ucs2Write(string, this.offset + offset, length);
377       break;
378
379     default:
380       throw new Error('Unknown encoding');
381   }
382
383   Buffer._charsWritten = SlowBuffer._charsWritten;
384
385   return ret;
386 };
387
388
389 // toString(encoding, start=0, end=buffer.length)
390 Buffer.prototype.toString = function(encoding, start, end) {
391   encoding = String(encoding || 'utf8').toLowerCase();
392
393   if (typeof start == 'undefined' || start < 0) {
394     start = 0;
395   } else if (start > this.length) {
396     start = this.length;
397   }
398
399   if (typeof end == 'undefined' || end > this.length) {
400     end = this.length;
401   } else if (end < 0) {
402     end = 0;
403   }
404
405   start = start + this.offset;
406   end = end + this.offset;
407
408   switch (encoding) {
409     case 'hex':
410       return this.parent.hexSlice(start, end);
411
412     case 'utf8':
413     case 'utf-8':
414       return this.parent.utf8Slice(start, end);
415
416     case 'ascii':
417       return this.parent.asciiSlice(start, end);
418
419     case 'binary':
420       return this.parent.binarySlice(start, end);
421
422     case 'base64':
423       return this.parent.base64Slice(start, end);
424
425     case 'ucs2':
426     case 'ucs-2':
427       return this.parent.ucs2Slice(start, end);
428
429     default:
430       throw new Error('Unknown encoding');
431   }
432 };
433
434
435 // byteLength
436 Buffer.byteLength = SlowBuffer.byteLength;
437
438
439 // fill(value, start=0, end=buffer.length)
440 Buffer.prototype.fill = function fill(value, start, end) {
441   value || (value = 0);
442   start || (start = 0);
443   end || (end = this.length);
444
445   if (typeof value === 'string') {
446     value = value.charCodeAt(0);
447   }
448   if (!(typeof value === 'number') || isNaN(value)) {
449     throw new Error('value is not a number');
450   }
451
452   if (end < start) throw new Error('end < start');
453
454   // Fill 0 bytes; we're done
455   if (end === start) return 0;
456   if (this.length == 0) return 0;
457
458   if (start < 0 || start >= this.length) {
459     throw new Error('start out of bounds');
460   }
461
462   if (end < 0 || end > this.length) {
463     throw new Error('end out of bounds');
464   }
465
466   return this.parent.fill(value,
467                           start + this.offset,
468                           end + this.offset);
469 };
470
471
472 // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
473 Buffer.prototype.copy = function(target, target_start, start, end) {
474   var source = this;
475   start || (start = 0);
476   end || (end = this.length);
477   target_start || (target_start = 0);
478
479   if (end < start) throw new Error('sourceEnd < sourceStart');
480
481   // Copy 0 bytes; we're done
482   if (end === start) return 0;
483   if (target.length == 0 || source.length == 0) return 0;
484
485   if (target_start < 0 || target_start >= target.length) {
486     throw new Error('targetStart out of bounds');
487   }
488
489   if (start < 0 || start >= source.length) {
490     throw new Error('sourceStart out of bounds');
491   }
492
493   if (end < 0 || end > source.length) {
494     throw new Error('sourceEnd out of bounds');
495   }
496
497   // Are we oob?
498   if (end > this.length) {
499     end = this.length;
500   }
501
502   if (target.length - target_start < end - start) {
503     end = target.length - target_start + start;
504   }
505
506   return this.parent.copy(target.parent,
507                           target_start + target.offset,
508                           start + this.offset,
509                           end + this.offset);
510 };
511
512
513 // slice(start, end)
514 Buffer.prototype.slice = function(start, end) {
515   if (end === undefined) end = this.length;
516   if (end > this.length) throw new Error('oob');
517   if (start > end) throw new Error('oob');
518
519   return new Buffer(this.parent, end - start, +start + this.offset);
520 };
521
522
523 // Legacy methods for backwards compatibility.
524
525 Buffer.prototype.utf8Slice = function(start, end) {
526   return this.toString('utf8', start, end);
527 };
528
529 Buffer.prototype.binarySlice = function(start, end) {
530   return this.toString('binary', start, end);
531 };
532
533 Buffer.prototype.asciiSlice = function(start, end) {
534   return this.toString('ascii', start, end);
535 };
536
537 Buffer.prototype.utf8Write = function(string, offset) {
538   return this.write(string, offset, 'utf8');
539 };
540
541 Buffer.prototype.binaryWrite = function(string, offset) {
542   return this.write(string, offset, 'binary');
543 };
544
545 Buffer.prototype.asciiWrite = function(string, offset) {
546   return this.write(string, offset, 'ascii');
547 };
548
549 Buffer.prototype.readUInt8 = function(offset, noAssert) {
550   var buffer = this;
551
552   if (!noAssert) {
553     assert.ok(offset !== undefined && offset !== null,
554         'missing offset');
555
556     assert.ok(offset < buffer.length,
557         'Trying to read beyond buffer length');
558   }
559
560   return buffer[offset];
561 };
562
563 function readUInt16(buffer, offset, isBigEndian, noAssert) {
564   var val = 0;
565
566
567   if (!noAssert) {
568     assert.ok(typeof (isBigEndian) === 'boolean',
569         'missing or invalid endian');
570
571     assert.ok(offset !== undefined && offset !== null,
572         'missing offset');
573
574     assert.ok(offset + 1 < buffer.length,
575         'Trying to read beyond buffer length');
576   }
577
578   if (isBigEndian) {
579     val = buffer[offset] << 8;
580     val |= buffer[offset + 1];
581   } else {
582     val = buffer[offset];
583     val |= buffer[offset + 1] << 8;
584   }
585
586   return val;
587 }
588
589 Buffer.prototype.readUInt16LE = function(offset, noAssert) {
590   return readUInt16(this, offset, false, noAssert);
591 };
592
593 Buffer.prototype.readUInt16BE = function(offset, noAssert) {
594   return readUInt16(this, offset, true, noAssert);
595 };
596
597 function readUInt32(buffer, offset, isBigEndian, noAssert) {
598   var val = 0;
599
600   if (!noAssert) {
601     assert.ok(typeof (isBigEndian) === 'boolean',
602         'missing or invalid endian');
603
604     assert.ok(offset !== undefined && offset !== null,
605         'missing offset');
606
607     assert.ok(offset + 3 < buffer.length,
608         'Trying to read beyond buffer length');
609   }
610
611   if (isBigEndian) {
612     val = buffer[offset + 1] << 16;
613     val |= buffer[offset + 2] << 8;
614     val |= buffer[offset + 3];
615     val = val + (buffer[offset] << 24 >>> 0);
616   } else {
617     val = buffer[offset + 2] << 16;
618     val |= buffer[offset + 1] << 8;
619     val |= buffer[offset];
620     val = val + (buffer[offset + 3] << 24 >>> 0);
621   }
622
623   return val;
624 }
625
626 Buffer.prototype.readUInt32LE = function(offset, noAssert) {
627   return readUInt32(this, offset, false, noAssert);
628 };
629
630 Buffer.prototype.readUInt32BE = function(offset, noAssert) {
631   return readUInt32(this, offset, true, noAssert);
632 };
633
634
635 /*
636  * Signed integer types, yay team! A reminder on how two's complement actually
637  * works. The first bit is the signed bit, i.e. tells us whether or not the
638  * number should be positive or negative. If the two's complement value is
639  * positive, then we're done, as it's equivalent to the unsigned representation.
640  *
641  * Now if the number is positive, you're pretty much done, you can just leverage
642  * the unsigned translations and return those. Unfortunately, negative numbers
643  * aren't quite that straightforward.
644  *
645  * At first glance, one might be inclined to use the traditional formula to
646  * translate binary numbers between the positive and negative values in two's
647  * complement. (Though it doesn't quite work for the most negative value)
648  * Mainly:
649  *  - invert all the bits
650  *  - add one to the result
651  *
652  * Of course, this doesn't quite work in Javascript. Take for example the value
653  * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of
654  * course, Javascript will do the following:
655  *
656  * > ~0xff80
657  * -65409
658  *
659  * Whoh there, Javascript, that's not quite right. But wait, according to
660  * Javascript that's perfectly correct. When Javascript ends up seeing the
661  * constant 0xff80, it has no notion that it is actually a signed number. It
662  * assumes that we've input the unsigned value 0xff80. Thus, when it does the
663  * binary negation, it casts it into a signed value, (positive 0xff80). Then
664  * when you perform binary negation on that, it turns it into a negative number.
665  *
666  * Instead, we're going to have to use the following general formula, that works
667  * in a rather Javascript friendly way. I'm glad we don't support this kind of
668  * weird numbering scheme in the kernel.
669  *
670  * (BIT-MAX - (unsigned)val + 1) * -1
671  *
672  * The astute observer, may think that this doesn't make sense for 8-bit numbers
673  * (really it isn't necessary for them). However, when you get 16-bit numbers,
674  * you do. Let's go back to our prior example and see how this will look:
675  *
676  * (0xffff - 0xff80 + 1) * -1
677  * (0x007f + 1) * -1
678  * (0x0080) * -1
679  */
680 Buffer.prototype.readInt8 = function(offset, noAssert) {
681   var buffer = this;
682   var neg;
683
684   if (!noAssert) {
685     assert.ok(offset !== undefined && offset !== null,
686         'missing offset');
687
688     assert.ok(offset < buffer.length,
689         'Trying to read beyond buffer length');
690   }
691
692   neg = buffer[offset] & 0x80;
693   if (!neg) {
694     return (buffer[offset]);
695   }
696
697   return ((0xff - buffer[offset] + 1) * -1);
698 };
699
700 function readInt16(buffer, offset, isBigEndian, noAssert) {
701   var neg;
702
703   if (!noAssert) {
704     assert.ok(typeof (isBigEndian) === 'boolean',
705         'missing or invalid endian');
706
707     assert.ok(offset !== undefined && offset !== null,
708         'missing offset');
709
710     assert.ok(offset + 1 < buffer.length,
711         'Trying to read beyond buffer length');
712   }
713
714   val = readUInt16(buffer, offset, isBigEndian, noAssert);
715   neg = val & 0x8000;
716   if (!neg) {
717     return val;
718   }
719
720   return (0xffff - val + 1) * -1;
721 }
722
723 Buffer.prototype.readInt16LE = function(offset, noAssert) {
724   return readInt16(this, offset, false, noAssert);
725 };
726
727 Buffer.prototype.readInt16BE = function(offset, noAssert) {
728   return readInt16(this, offset, true, noAssert);
729 };
730
731 function readInt32(buffer, offset, isBigEndian, noAssert) {
732   var neg;
733
734   if (!noAssert) {
735     assert.ok(typeof (isBigEndian) === 'boolean',
736         'missing or invalid endian');
737
738     assert.ok(offset !== undefined && offset !== null,
739         'missing offset');
740
741     assert.ok(offset + 3 < buffer.length,
742         'Trying to read beyond buffer length');
743   }
744
745   val = readUInt32(buffer, offset, isBigEndian, noAssert);
746   neg = val & 0x80000000;
747   if (!neg) {
748     return (val);
749   }
750
751   return (0xffffffff - val + 1) * -1;
752 }
753
754 Buffer.prototype.readInt32LE = function(offset, noAssert) {
755   return readInt32(this, offset, false, noAssert);
756 };
757
758 Buffer.prototype.readInt32BE = function(offset, noAssert) {
759   return readInt32(this, offset, true, noAssert);
760 };
761
762 function readFloat(buffer, offset, isBigEndian, noAssert) {
763   if (!noAssert) {
764     assert.ok(typeof (isBigEndian) === 'boolean',
765         'missing or invalid endian');
766
767     assert.ok(offset + 3 < buffer.length,
768         'Trying to read beyond buffer length');
769   }
770
771   return require('buffer_ieee754').readIEEE754(buffer, offset, isBigEndian,
772       23, 4);
773 }
774
775 Buffer.prototype.readFloatLE = function(offset, noAssert) {
776   return readFloat(this, offset, false, noAssert);
777 };
778
779 Buffer.prototype.readFloatBE = function(offset, noAssert) {
780   return readFloat(this, offset, true, noAssert);
781 };
782
783 function readDouble(buffer, offset, isBigEndian, noAssert) {
784   if (!noAssert) {
785     assert.ok(typeof (isBigEndian) === 'boolean',
786         'missing or invalid endian');
787
788     assert.ok(offset + 7 < buffer.length,
789         'Trying to read beyond buffer length');
790   }
791
792   return require('buffer_ieee754').readIEEE754(buffer, offset, isBigEndian,
793       52, 8);
794 }
795
796 Buffer.prototype.readDoubleLE = function(offset, noAssert) {
797   return readDouble(this, offset, false, noAssert);
798 };
799
800 Buffer.prototype.readDoubleBE = function(offset, noAssert) {
801   return readDouble(this, offset, true, noAssert);
802 };
803
804
805 /*
806  * We have to make sure that the value is a valid integer. This means that it is
807  * non-negative. It has no fractional component and that it does not exceed the
808  * maximum allowed value.
809  *
810  *      value           The number to check for validity
811  *
812  *      max             The maximum value
813  */
814 function verifuint(value, max) {
815   assert.ok(typeof (value) == 'number',
816       'cannot write a non-number as a number');
817
818   assert.ok(value >= 0,
819       'specified a negative value for writing an unsigned value');
820
821   assert.ok(value <= max, 'value is larger than maximum value for type');
822
823   assert.ok(Math.floor(value) === value, 'value has a fractional component');
824 }
825
826 Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
827   var buffer = this;
828
829   if (!noAssert) {
830     assert.ok(value !== undefined && value !== null,
831         'missing value');
832
833     assert.ok(offset !== undefined && offset !== null,
834         'missing offset');
835
836     assert.ok(offset < buffer.length,
837         'trying to write beyond buffer length');
838
839     verifuint(value, 0xff);
840   }
841
842   buffer[offset] = value;
843 };
844
845 function writeUInt16(buffer, value, offset, isBigEndian, noAssert) {
846   if (!noAssert) {
847     assert.ok(value !== undefined && value !== null,
848         'missing value');
849
850     assert.ok(typeof (isBigEndian) === 'boolean',
851         'missing or invalid endian');
852
853     assert.ok(offset !== undefined && offset !== null,
854         'missing offset');
855
856     assert.ok(offset + 1 < buffer.length,
857         'trying to write beyond buffer length');
858
859     verifuint(value, 0xffff);
860   }
861
862   if (isBigEndian) {
863     buffer[offset] = (value & 0xff00) >>> 8;
864     buffer[offset + 1] = value & 0x00ff;
865   } else {
866     buffer[offset + 1] = (value & 0xff00) >>> 8;
867     buffer[offset] = value & 0x00ff;
868   }
869 }
870
871 Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
872   writeUInt16(this, value, offset, false, noAssert);
873 };
874
875 Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
876   writeUInt16(this, value, offset, true, noAssert);
877 };
878
879 function writeUInt32(buffer, value, offset, isBigEndian, noAssert) {
880   if (!noAssert) {
881     assert.ok(value !== undefined && value !== null,
882         'missing value');
883
884     assert.ok(typeof (isBigEndian) === 'boolean',
885         'missing or invalid endian');
886
887     assert.ok(offset !== undefined && offset !== null,
888         'missing offset');
889
890     assert.ok(offset + 3 < buffer.length,
891         'trying to write beyond buffer length');
892
893     verifuint(value, 0xffffffff);
894   }
895
896   if (isBigEndian) {
897     buffer[offset] = (value >>> 24) & 0xff;
898     buffer[offset + 1] = (value >>> 16) & 0xff;
899     buffer[offset + 2] = (value >>> 8) & 0xff;
900     buffer[offset + 3] = value & 0xff;
901   } else {
902     buffer[offset + 3] = (value >>> 24) & 0xff;
903     buffer[offset + 2] = (value >>> 16) & 0xff;
904     buffer[offset + 1] = (value >>> 8) & 0xff;
905     buffer[offset] = value & 0xff;
906   }
907 }
908
909 Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
910   writeUInt32(this, value, offset, false, noAssert);
911 };
912
913 Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
914   writeUInt32(this, value, offset, true, noAssert);
915 };
916
917
918 /*
919  * We now move onto our friends in the signed number category. Unlike unsigned
920  * numbers, we're going to have to worry a bit more about how we put values into
921  * arrays. Since we are only worrying about signed 32-bit values, we're in
922  * slightly better shape. Unfortunately, we really can't do our favorite binary
923  * & in this system. It really seems to do the wrong thing. For example:
924  *
925  * > -32 & 0xff
926  * 224
927  *
928  * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of
929  * this aren't treated as a signed number. Ultimately a bad thing.
930  *
931  * What we're going to want to do is basically create the unsigned equivalent of
932  * our representation and pass that off to the wuint* functions. To do that
933  * we're going to do the following:
934  *
935  *  - if the value is positive
936  *      we can pass it directly off to the equivalent wuint
937  *  - if the value is negative
938  *      we do the following computation:
939  *         mb + val + 1, where
940  *         mb   is the maximum unsigned value in that byte size
941  *         val  is the Javascript negative integer
942  *
943  *
944  * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If
945  * you do out the computations:
946  *
947  * 0xffff - 128 + 1
948  * 0xffff - 127
949  * 0xff80
950  *
951  * You can then encode this value as the signed version. This is really rather
952  * hacky, but it should work and get the job done which is our goal here.
953  */
954
955 /*
956  * A series of checks to make sure we actually have a signed 32-bit number
957  */
958 function verifsint(value, max, min) {
959   assert.ok(typeof (value) == 'number',
960       'cannot write a non-number as a number');
961
962   assert.ok(value <= max, 'value larger than maximum allowed value');
963
964   assert.ok(value >= min, 'value smaller than minimum allowed value');
965
966   assert.ok(Math.floor(value) === value, 'value has a fractional component');
967 }
968
969 function verifIEEE754(value, max, min) {
970   assert.ok(typeof (value) == 'number',
971       'cannot write a non-number as a number');
972
973   assert.ok(value <= max, 'value larger than maximum allowed value');
974
975   assert.ok(value >= min, 'value smaller than minimum allowed value');
976 }
977
978 Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
979   var buffer = this;
980
981   if (!noAssert) {
982     assert.ok(value !== undefined && value !== null,
983         'missing value');
984
985     assert.ok(offset !== undefined && offset !== null,
986         'missing offset');
987
988     assert.ok(offset < buffer.length,
989         'Trying to write beyond buffer length');
990
991     verifsint(value, 0x7f, -0x80);
992   }
993
994   if (value >= 0) {
995     buffer.writeUInt8(value, offset, noAssert);
996   } else {
997     buffer.writeUInt8(0xff + value + 1, offset, noAssert);
998   }
999 };
1000
1001 function writeInt16(buffer, value, offset, isBigEndian, noAssert) {
1002   if (!noAssert) {
1003     assert.ok(value !== undefined && value !== null,
1004         'missing value');
1005
1006     assert.ok(typeof (isBigEndian) === 'boolean',
1007         'missing or invalid endian');
1008
1009     assert.ok(offset !== undefined && offset !== null,
1010         'missing offset');
1011
1012     assert.ok(offset + 1 < buffer.length,
1013         'Trying to write beyond buffer length');
1014
1015     verifsint(value, 0x7fff, -0x8000);
1016   }
1017
1018   if (value >= 0) {
1019     writeUInt16(buffer, value, offset, isBigEndian, noAssert);
1020   } else {
1021     writeUInt16(buffer, 0xffff + value + 1, offset, isBigEndian, noAssert);
1022   }
1023 }
1024
1025 Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
1026   writeInt16(this, value, offset, false, noAssert);
1027 };
1028
1029 Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
1030   writeInt16(this, value, offset, true, noAssert);
1031 };
1032
1033 function writeInt32(buffer, value, offset, isBigEndian, noAssert) {
1034   if (!noAssert) {
1035     assert.ok(value !== undefined && value !== null,
1036         'missing value');
1037
1038     assert.ok(typeof (isBigEndian) === 'boolean',
1039         'missing or invalid endian');
1040
1041     assert.ok(offset !== undefined && offset !== null,
1042         'missing offset');
1043
1044     assert.ok(offset + 3 < buffer.length,
1045         'Trying to write beyond buffer length');
1046
1047     verifsint(value, 0x7fffffff, -0x80000000);
1048   }
1049
1050   if (value >= 0) {
1051     writeUInt32(buffer, value, offset, isBigEndian, noAssert);
1052   } else {
1053     writeUInt32(buffer, 0xffffffff + value + 1, offset, isBigEndian, noAssert);
1054   }
1055 }
1056
1057 Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
1058   writeInt32(this, value, offset, false, noAssert);
1059 };
1060
1061 Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
1062   writeInt32(this, value, offset, true, noAssert);
1063 };
1064
1065 function writeFloat(buffer, value, offset, isBigEndian, noAssert) {
1066   if (!noAssert) {
1067     assert.ok(value !== undefined && value !== null,
1068         'missing value');
1069
1070     assert.ok(typeof (isBigEndian) === 'boolean',
1071         'missing or invalid endian');
1072
1073     assert.ok(offset !== undefined && offset !== null,
1074         'missing offset');
1075
1076     assert.ok(offset + 3 < buffer.length,
1077         'Trying to write beyond buffer length');
1078
1079     verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38);
1080   }
1081
1082   require('buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian,
1083       23, 4);
1084 }
1085
1086 Buffer.prototype.writeFloatLE = function(value, offset, noAssert) {
1087   writeFloat(this, value, offset, false, noAssert);
1088 };
1089
1090 Buffer.prototype.writeFloatBE = function(value, offset, noAssert) {
1091   writeFloat(this, value, offset, true, noAssert);
1092 };
1093
1094 function writeDouble(buffer, value, offset, isBigEndian, noAssert) {
1095   if (!noAssert) {
1096     assert.ok(value !== undefined && value !== null,
1097         'missing value');
1098
1099     assert.ok(typeof (isBigEndian) === 'boolean',
1100         'missing or invalid endian');
1101
1102     assert.ok(offset !== undefined && offset !== null,
1103         'missing offset');
1104
1105     assert.ok(offset + 7 < buffer.length,
1106         'Trying to write beyond buffer length');
1107
1108     verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308);
1109   }
1110
1111   require('buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian,
1112       52, 8);
1113 }
1114
1115 Buffer.prototype.writeDoubleLE = function(value, offset, noAssert) {
1116   writeDouble(this, value, offset, false, noAssert);
1117 };
1118
1119 Buffer.prototype.writeDoubleBE = function(value, offset, noAssert) {
1120   writeDouble(this, value, offset, true, noAssert);
1121 };