3 // Copyright (c) 2012 Robert Kieffer
4 // MIT License - http://opensource.org/licenses/mit-license.php
7 * Support for handling 64-bit int numbers in Javascript (node.js)
9 * JS Numbers are IEEE-754 binary double-precision floats, which limits the
10 * range of values that can be represented with integer precision to:
14 * Int64 objects wrap a node Buffer that holds the 8-bytes of int64 data. These
15 * objects operate directly on the buffer which means that if they are created
16 * using an existing buffer then setting the value will modify the Buffer, and
19 * Internal Representation
21 * The internal buffer format is Big Endian. I.e. the most-significant byte is
22 * at buffer[0], the least-significant at buffer[7]. For the purposes of
23 * converting to/from JS native numbers, the value is assumed to be a signed
24 * integer stored in 2's complement form.
26 * For details about IEEE-754 see:
27 * http://en.wikipedia.org/wiki/Double_precision_floating-point_format
30 // Useful masks and values for bit twiddling
31 var MASK31 = 0x7fffffff, VAL31 = 0x80000000;
32 var MASK32 = 0xffffffff, VAL32 = 0x100000000;
34 // Map for converting hex octets to strings
36 for (var i = 0; i < 256; i++) {
37 _HEX[i] = (i > 0xF ? '' : '0') + i.toString(16);
45 * Constructor accepts any of the following argument types:
47 * new Int64(buffer[, offset=0]) - Existing Buffer with byte offset
48 * new Int64(Uint8Array[, offset=0]) - Existing Uint8Array with a byte offset
49 * new Int64(string) - Hex string (throws if n is outside int64 range)
50 * new Int64(number) - Number (throws if n is outside int64 range)
51 * new Int64(hi, lo) - Raw bits as two 32-bit values
53 var Int64 = module.exports = function(a1, a2) {
54 if (a1 instanceof Buffer) {
56 this.offset = a2 || 0;
57 } else if (Object.prototype.toString.call(a1) == '[object Uint8Array]') {
58 // Under Browserify, Buffers can extend Uint8Arrays rather than an
59 // instance of Buffer. We could assume the passed in Uint8Array is actually
60 // a buffer but that won't handle the case where a raw Uint8Array is passed
61 // in. We construct a new Buffer just in case.
62 this.buffer = new Buffer(a1);
63 this.offset = a2 || 0;
65 this.buffer = this.buffer || new Buffer(8);
67 this.setValue.apply(this, arguments);
72 // Max integer value that JS can accurately represent
73 Int64.MAX_INT = Math.pow(2, 53);
75 // Min integer value that JS can accurately represent
76 Int64.MIN_INT = -Math.pow(2, 53);
83 * Do in-place 2's compliment. See
84 * http://en.wikipedia.org/wiki/Two's_complement
87 var b = this.buffer, o = this.offset, carry = 1;
88 for (var i = o + 7; i >= o; i--) {
89 var v = (b[i] ^ 0xff) + carry;
96 * Set the value. Takes any of the following arguments:
98 * setValue(string) - A hexidecimal string
99 * setValue(number) - Number (throws if n is outside int64 range)
100 * setValue(hi, lo) - Raw bits as two 32-bit values
102 setValue: function(hi, lo) {
104 if (arguments.length == 1) {
105 if (typeof(hi) == 'number') {
106 // Simplify bitfield retrieval by using abs() value. We restore sign
112 if (hi > VAL32) throw new RangeError(hi + ' is outside Int64 range');
114 } else if (typeof(hi) == 'string') {
115 hi = (hi + '').replace(/^0x/, '');
117 hi = hi.length > 8 ? hi.substr(0, hi.length - 8) : '';
118 hi = parseInt(hi, 16);
119 lo = parseInt(lo, 16);
121 throw new Error(hi + ' must be a Number or String');
125 // Technically we should throw if hi or lo is outside int32 range here, but
126 // it's not worth the effort. Anything past the 32'nd bit is ignored.
128 // Copy bytes to buffer
129 var b = this.buffer, o = this.offset;
130 for (var i = 7; i >= 0; i--) {
132 lo = i == 4 ? hi : lo >>> 8;
135 // Restore sign of passed argument
136 if (negate) this._2scomp();
140 * Convert to a native JS number.
142 * WARNING: Do not expect this value to be accurate to integer precision for
143 * large (positive or negative) numbers!
145 * @param allowImprecise If true, no check is performed to verify the
146 * returned value is accurate to integer precision. If false, imprecise
147 * numbers (very large positive or negative numbers) will be forced to +/-
150 toNumber: function(allowImprecise) {
151 var b = this.buffer, o = this.offset;
153 // Running sum of octets, doing a 2's complement
154 var negate = b[o] & 0x80, x = 0, carry = 1;
155 for (var i = 7, m = 1; i >= 0; i--, m *= 256) {
158 // 2's complement for negative numbers
160 v = (v ^ 0xff) + carry;
168 // Return Infinity if we've lost integer precision
169 if (!allowImprecise && x >= Int64.MAX_INT) {
170 return negate ? -Infinity : Infinity;
173 return negate ? -x : x;
177 * Convert to a JS Number. Returns +/-Infinity for values that can't be
178 * represented to integer precision.
180 valueOf: function() {
181 return this.toNumber(false);
185 * Return string value
187 * @param radix Just like Number#toString()'s radix
189 toString: function(radix) {
190 return this.valueOf().toString(radix || 10);
194 * Return a string showing the buffer octets, with MSB on the left.
196 * @param sep separator string. default is '' (empty string)
198 toOctetString: function(sep) {
199 var out = new Array(8);
200 var b = this.buffer, o = this.offset;
201 for (var i = 0; i < 8; i++) {
202 out[i] = _HEX[b[o+i]];
204 return out.join(sep || '');
208 * Returns the int64's 8 bytes in a buffer.
210 * @param {bool} [rawBuffer=false] If no offset and this is true, return the internal buffer. Should only be used if
211 * you're discarding the Int64 afterwards, as it breaks encapsulation.
213 toBuffer: function(rawBuffer) {
214 if (rawBuffer && this.offset === 0) return this.buffer;
216 var out = new Buffer(8);
217 this.buffer.copy(out, 0, this.offset, this.offset + 8);
222 * Copy 8 bytes of int64 into target buffer at target offset.
224 * @param {Buffer} targetBuffer Buffer to copy into.
225 * @param {number} [targetOffset=0] Offset into target buffer.
227 copy: function(targetBuffer, targetOffset) {
228 this.buffer.copy(targetBuffer, targetOffset || 0, this.offset, this.offset + 8);
232 * Returns a number indicating whether this comes before or after or is the
233 * same as the other in sort order.
235 * @param {Int64} other Other Int64 to compare.
237 compare: function(other) {
239 // If sign bits differ ...
240 if ((this.buffer[this.offset] & 0x80) != (other.buffer[other.offset] & 0x80)) {
241 return other.buffer[other.offset] - this.buffer[this.offset];
244 // otherwise, compare bytes lexicographically
245 for (var i = 0; i < 8; i++) {
246 if (this.buffer[this.offset+i] !== other.buffer[other.offset+i]) {
247 return this.buffer[this.offset+i] - other.buffer[other.offset+i];
254 * Returns a boolean indicating if this integer is equal to other.
256 * @param {Int64} other Other Int64 to compare.
258 equals: function(other) {
259 return this.compare(other) === 0;
263 * Pretty output in console.log
265 inspect: function() {
266 return '[Int64 value:' + this + ' octets:' + this.toOctetString(' ') + ']';