1 // Licensed under the Apache License, Version 2.0 (the "License");
2 // you may not use this file except in compliance with the License.
3 // You may obtain a copy of the License at
5 // http://www.apache.org/licenses/LICENSE-2.0
7 // Unless required by applicable law or agreed to in writing, software
8 // distributed under the License is distributed on an "AS IS" BASIS,
9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 // See the License for the specific language governing permissions and
11 // limitations under the License.
13 // Copyright 2009 Google Inc. All Rights Reserved
16 * Defines a Long class for representing a 64-bit two's-complement
17 * integer value, which faithfully simulates the behavior of a Java "Long". This
18 * implementation is derived from LongLib in GWT.
20 * Constructs a 64-bit two's-complement integer, given its low and high 32-bit
21 * values as *signed* integers. See the from* functions below for more
22 * convenient ways of constructing Longs.
24 * The internal representation of a Long is the two given signed, 32-bit values.
25 * We use 32-bit pieces because these are the size of integers on which
26 * Javascript performs bit-operations. For operations like addition and
27 * multiplication, we split each number into 16-bit pieces, which can easily be
28 * multiplied within Javascript's floating-point representation without overflow
31 * In the algorithms below, we frequently reduce the negative case to the
32 * positive case by negating the input(s) and then post-processing the result.
33 * Note that we must ALWAYS check specially whether those values are MIN_VALUE
34 * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
35 * a positive number, it overflows back into a negative). Not handling this
36 * case would often result in infinite recursion.
39 * @param {number} low the low (signed) 32 bits of the Long.
40 * @param {number} high the high (signed) 32 bits of the Long.
43 function Long(low, high) {
44 if(!(this instanceof Long)) return new Long(low, high);
46 this._bsontype = 'Long';
51 this.low_ = low | 0; // force into 32 signed bits.
57 this.high_ = high | 0; // force into 32 signed bits.
61 * Return the int value.
64 * @return {number} the value, assuming it is a 32-bit integer.
66 Long.prototype.toInt = function() {
71 * Return the Number value.
74 * @return {number} the closest floating-point representation to this value.
76 Long.prototype.toNumber = function() {
77 return this.high_ * Long.TWO_PWR_32_DBL_ +
78 this.getLowBitsUnsigned();
82 * Return the JSON value.
85 * @return {string} the JSON representation.
87 Long.prototype.toJSON = function() {
88 return this.toString();
92 * Return the String value.
95 * @param {number} [opt_radix] the radix in which the text should be written.
96 * @return {string} the textual representation of this value.
98 Long.prototype.toString = function(opt_radix) {
99 var radix = opt_radix || 10;
100 if (radix < 2 || 36 < radix) {
101 throw Error('radix out of range: ' + radix);
108 if (this.isNegative()) {
109 if (this.equals(Long.MIN_VALUE)) {
110 // We need to change the Long value before it can be negated, so we remove
111 // the bottom-most digit in this base and then recurse to do the rest.
112 var radixLong = Long.fromNumber(radix);
113 var div = this.div(radixLong);
114 var rem = div.multiply(radixLong).subtract(this);
115 return div.toString(radix) + rem.toInt().toString(radix);
117 return '-' + this.negate().toString(radix);
121 // Do several (6) digits each time through the loop, so as to
122 // minimize the calls to the very expensive emulated div.
123 var radixToPower = Long.fromNumber(Math.pow(radix, 6));
128 var remDiv = rem.div(radixToPower);
129 var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt();
130 var digits = intval.toString(radix);
134 return digits + result;
136 while (digits.length < 6) {
137 digits = '0' + digits;
139 result = '' + digits + result;
145 * Return the high 32-bits value.
148 * @return {number} the high 32-bits as a signed value.
150 Long.prototype.getHighBits = function() {
155 * Return the low 32-bits value.
158 * @return {number} the low 32-bits as a signed value.
160 Long.prototype.getLowBits = function() {
165 * Return the low unsigned 32-bits value.
168 * @return {number} the low 32-bits as an unsigned value.
170 Long.prototype.getLowBitsUnsigned = function() {
171 return (this.low_ >= 0) ?
172 this.low_ : Long.TWO_PWR_32_DBL_ + this.low_;
176 * Returns the number of bits needed to represent the absolute value of this Long.
179 * @return {number} Returns the number of bits needed to represent the absolute value of this Long.
181 Long.prototype.getNumBitsAbs = function() {
182 if (this.isNegative()) {
183 if (this.equals(Long.MIN_VALUE)) {
186 return this.negate().getNumBitsAbs();
189 var val = this.high_ != 0 ? this.high_ : this.low_;
190 for (var bit = 31; bit > 0; bit--) {
191 if ((val & (1 << bit)) != 0) {
195 return this.high_ != 0 ? bit + 33 : bit + 1;
200 * Return whether this value is zero.
203 * @return {boolean} whether this value is zero.
205 Long.prototype.isZero = function() {
206 return this.high_ == 0 && this.low_ == 0;
210 * Return whether this value is negative.
213 * @return {boolean} whether this value is negative.
215 Long.prototype.isNegative = function() {
216 return this.high_ < 0;
220 * Return whether this value is odd.
223 * @return {boolean} whether this value is odd.
225 Long.prototype.isOdd = function() {
226 return (this.low_ & 1) == 1;
230 * Return whether this Long equals the other
233 * @param {Long} other Long to compare against.
234 * @return {boolean} whether this Long equals the other
236 Long.prototype.equals = function(other) {
237 return (this.high_ == other.high_) && (this.low_ == other.low_);
241 * Return whether this Long does not equal the other.
244 * @param {Long} other Long to compare against.
245 * @return {boolean} whether this Long does not equal the other.
247 Long.prototype.notEquals = function(other) {
248 return (this.high_ != other.high_) || (this.low_ != other.low_);
252 * Return whether this Long is less than the other.
255 * @param {Long} other Long to compare against.
256 * @return {boolean} whether this Long is less than the other.
258 Long.prototype.lessThan = function(other) {
259 return this.compare(other) < 0;
263 * Return whether this Long is less than or equal to the other.
266 * @param {Long} other Long to compare against.
267 * @return {boolean} whether this Long is less than or equal to the other.
269 Long.prototype.lessThanOrEqual = function(other) {
270 return this.compare(other) <= 0;
274 * Return whether this Long is greater than the other.
277 * @param {Long} other Long to compare against.
278 * @return {boolean} whether this Long is greater than the other.
280 Long.prototype.greaterThan = function(other) {
281 return this.compare(other) > 0;
285 * Return whether this Long is greater than or equal to the other.
288 * @param {Long} other Long to compare against.
289 * @return {boolean} whether this Long is greater than or equal to the other.
291 Long.prototype.greaterThanOrEqual = function(other) {
292 return this.compare(other) >= 0;
296 * Compares this Long with the given one.
299 * @param {Long} other Long to compare against.
300 * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater.
302 Long.prototype.compare = function(other) {
303 if (this.equals(other)) {
307 var thisNeg = this.isNegative();
308 var otherNeg = other.isNegative();
309 if (thisNeg && !otherNeg) {
312 if (!thisNeg && otherNeg) {
316 // at this point, the signs are the same, so subtraction will not overflow
317 if (this.subtract(other).isNegative()) {
325 * The negation of this value.
328 * @return {Long} the negation of this value.
330 Long.prototype.negate = function() {
331 if (this.equals(Long.MIN_VALUE)) {
332 return Long.MIN_VALUE;
334 return this.not().add(Long.ONE);
339 * Returns the sum of this and the given Long.
342 * @param {Long} other Long to add to this one.
343 * @return {Long} the sum of this and the given Long.
345 Long.prototype.add = function(other) {
346 // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
348 var a48 = this.high_ >>> 16;
349 var a32 = this.high_ & 0xFFFF;
350 var a16 = this.low_ >>> 16;
351 var a00 = this.low_ & 0xFFFF;
353 var b48 = other.high_ >>> 16;
354 var b32 = other.high_ & 0xFFFF;
355 var b16 = other.low_ >>> 16;
356 var b00 = other.low_ & 0xFFFF;
358 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
370 return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
374 * Returns the difference of this and the given Long.
377 * @param {Long} other Long to subtract from this.
378 * @return {Long} the difference of this and the given Long.
380 Long.prototype.subtract = function(other) {
381 return this.add(other.negate());
385 * Returns the product of this and the given Long.
388 * @param {Long} other Long to multiply with this.
389 * @return {Long} the product of this and the other.
391 Long.prototype.multiply = function(other) {
394 } else if (other.isZero()) {
398 if (this.equals(Long.MIN_VALUE)) {
399 return other.isOdd() ? Long.MIN_VALUE : Long.ZERO;
400 } else if (other.equals(Long.MIN_VALUE)) {
401 return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
404 if (this.isNegative()) {
405 if (other.isNegative()) {
406 return this.negate().multiply(other.negate());
408 return this.negate().multiply(other).negate();
410 } else if (other.isNegative()) {
411 return this.multiply(other.negate()).negate();
414 // If both Longs are small, use float multiplication
415 if (this.lessThan(Long.TWO_PWR_24_) &&
416 other.lessThan(Long.TWO_PWR_24_)) {
417 return Long.fromNumber(this.toNumber() * other.toNumber());
420 // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products.
421 // We can skip products that would overflow.
423 var a48 = this.high_ >>> 16;
424 var a32 = this.high_ & 0xFFFF;
425 var a16 = this.low_ >>> 16;
426 var a00 = this.low_ & 0xFFFF;
428 var b48 = other.high_ >>> 16;
429 var b32 = other.high_ & 0xFFFF;
430 var b16 = other.low_ >>> 16;
431 var b00 = other.low_ & 0xFFFF;
433 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
452 c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
454 return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
458 * Returns this Long divided by the given one.
461 * @param {Long} other Long by which to divide.
462 * @return {Long} this Long divided by the given one.
464 Long.prototype.div = function(other) {
465 if (other.isZero()) {
466 throw Error('division by zero');
467 } else if (this.isZero()) {
471 if (this.equals(Long.MIN_VALUE)) {
472 if (other.equals(Long.ONE) ||
473 other.equals(Long.NEG_ONE)) {
474 return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
475 } else if (other.equals(Long.MIN_VALUE)) {
478 // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
479 var halfThis = this.shiftRight(1);
480 var approx = halfThis.div(other).shiftLeft(1);
481 if (approx.equals(Long.ZERO)) {
482 return other.isNegative() ? Long.ONE : Long.NEG_ONE;
484 var rem = this.subtract(other.multiply(approx));
485 var result = approx.add(rem.div(other));
489 } else if (other.equals(Long.MIN_VALUE)) {
493 if (this.isNegative()) {
494 if (other.isNegative()) {
495 return this.negate().div(other.negate());
497 return this.negate().div(other).negate();
499 } else if (other.isNegative()) {
500 return this.div(other.negate()).negate();
503 // Repeat the following until the remainder is less than other: find a
504 // floating-point that approximates remainder / other *from below*, add this
505 // into the result, and subtract it from the remainder. It is critical that
506 // the approximate value is less than or equal to the real value so that the
507 // remainder never becomes negative.
510 while (rem.greaterThanOrEqual(other)) {
511 // Approximate the result of division. This may be a little greater or
512 // smaller than the actual value.
513 var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));
515 // We will tweak the approximate result by changing it in the 48-th digit or
516 // the smallest non-fractional digit, whichever is larger.
517 var log2 = Math.ceil(Math.log(approx) / Math.LN2);
518 var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48);
520 // Decrease the approximation until it is smaller than the remainder. Note
521 // that if it is too large, the product overflows and is negative.
522 var approxRes = Long.fromNumber(approx);
523 var approxRem = approxRes.multiply(other);
524 while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
526 approxRes = Long.fromNumber(approx);
527 approxRem = approxRes.multiply(other);
530 // We know the answer can't be zero... and actually, zero would cause
531 // infinite recursion since we would make no progress.
532 if (approxRes.isZero()) {
533 approxRes = Long.ONE;
536 res = res.add(approxRes);
537 rem = rem.subtract(approxRem);
543 * Returns this Long modulo the given one.
546 * @param {Long} other Long by which to mod.
547 * @return {Long} this Long modulo the given one.
549 Long.prototype.modulo = function(other) {
550 return this.subtract(this.div(other).multiply(other));
554 * The bitwise-NOT of this value.
557 * @return {Long} the bitwise-NOT of this value.
559 Long.prototype.not = function() {
560 return Long.fromBits(~this.low_, ~this.high_);
564 * Returns the bitwise-AND of this Long and the given one.
567 * @param {Long} other the Long with which to AND.
568 * @return {Long} the bitwise-AND of this and the other.
570 Long.prototype.and = function(other) {
571 return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_);
575 * Returns the bitwise-OR of this Long and the given one.
578 * @param {Long} other the Long with which to OR.
579 * @return {Long} the bitwise-OR of this and the other.
581 Long.prototype.or = function(other) {
582 return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_);
586 * Returns the bitwise-XOR of this Long and the given one.
589 * @param {Long} other the Long with which to XOR.
590 * @return {Long} the bitwise-XOR of this and the other.
592 Long.prototype.xor = function(other) {
593 return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_);
597 * Returns this Long with bits shifted to the left by the given amount.
600 * @param {number} numBits the number of bits by which to shift.
601 * @return {Long} this shifted to the left by the given amount.
603 Long.prototype.shiftLeft = function(numBits) {
610 var high = this.high_;
611 return Long.fromBits(
613 (high << numBits) | (low >>> (32 - numBits)));
615 return Long.fromBits(0, low << (numBits - 32));
621 * Returns this Long with bits shifted to the right by the given amount.
624 * @param {number} numBits the number of bits by which to shift.
625 * @return {Long} this shifted to the right by the given amount.
627 Long.prototype.shiftRight = function(numBits) {
632 var high = this.high_;
635 return Long.fromBits(
636 (low >>> numBits) | (high << (32 - numBits)),
639 return Long.fromBits(
640 high >> (numBits - 32),
647 * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit.
650 * @param {number} numBits the number of bits by which to shift.
651 * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits.
653 Long.prototype.shiftRightUnsigned = function(numBits) {
658 var high = this.high_;
661 return Long.fromBits(
662 (low >>> numBits) | (high << (32 - numBits)),
664 } else if (numBits == 32) {
665 return Long.fromBits(high, 0);
667 return Long.fromBits(high >>> (numBits - 32), 0);
673 * Returns a Long representing the given (32-bit) integer value.
676 * @param {number} value the 32-bit integer in question.
677 * @return {Long} the corresponding Long value.
679 Long.fromInt = function(value) {
680 if (-128 <= value && value < 128) {
681 var cachedObj = Long.INT_CACHE_[value];
687 var obj = new Long(value | 0, value < 0 ? -1 : 0);
688 if (-128 <= value && value < 128) {
689 Long.INT_CACHE_[value] = obj;
695 * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
698 * @param {number} value the number in question.
699 * @return {Long} the corresponding Long value.
701 Long.fromNumber = function(value) {
702 if (isNaN(value) || !isFinite(value)) {
704 } else if (value <= -Long.TWO_PWR_63_DBL_) {
705 return Long.MIN_VALUE;
706 } else if (value + 1 >= Long.TWO_PWR_63_DBL_) {
707 return Long.MAX_VALUE;
708 } else if (value < 0) {
709 return Long.fromNumber(-value).negate();
712 (value % Long.TWO_PWR_32_DBL_) | 0,
713 (value / Long.TWO_PWR_32_DBL_) | 0);
718 * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits.
721 * @param {number} lowBits the low 32-bits.
722 * @param {number} highBits the high 32-bits.
723 * @return {Long} the corresponding Long value.
725 Long.fromBits = function(lowBits, highBits) {
726 return new Long(lowBits, highBits);
730 * Returns a Long representation of the given string, written using the given radix.
733 * @param {string} str the textual representation of the Long.
734 * @param {number} opt_radix the radix in which the text is written.
735 * @return {Long} the corresponding Long value.
737 Long.fromString = function(str, opt_radix) {
738 if (str.length == 0) {
739 throw Error('number format error: empty string');
742 var radix = opt_radix || 10;
743 if (radix < 2 || 36 < radix) {
744 throw Error('radix out of range: ' + radix);
747 if (str.charAt(0) == '-') {
748 return Long.fromString(str.substring(1), radix).negate();
749 } else if (str.indexOf('-') >= 0) {
750 throw Error('number format error: interior "-" character: ' + str);
753 // Do several (8) digits each time through the loop, so as to
754 // minimize the calls to the very expensive emulated div.
755 var radixToPower = Long.fromNumber(Math.pow(radix, 8));
757 var result = Long.ZERO;
758 for (var i = 0; i < str.length; i += 8) {
759 var size = Math.min(8, str.length - i);
760 var value = parseInt(str.substring(i, i + size), radix);
762 var power = Long.fromNumber(Math.pow(radix, size));
763 result = result.multiply(power).add(Long.fromNumber(value));
765 result = result.multiply(radixToPower);
766 result = result.add(Long.fromNumber(value));
772 // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the
773 // from* methods on which they depend.
777 * A cache of the Long representations of small integer values.
781 Long.INT_CACHE_ = {};
783 // NOTE: the compiler should inline these constant values below and then remove
784 // these variables, so there should be no runtime penalty for these.
787 * Number used repeated below in calculations. This must appear before the
788 * first call to any from* function below.
792 Long.TWO_PWR_16_DBL_ = 1 << 16;
798 Long.TWO_PWR_24_DBL_ = 1 << 24;
804 Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_;
810 Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2;
816 Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_;
822 Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_;
828 Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2;
831 Long.ZERO = Long.fromInt(0);
834 Long.ONE = Long.fromInt(1);
837 Long.NEG_ONE = Long.fromInt(-1);
841 Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0);
844 Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0);
850 Long.TWO_PWR_24_ = Long.fromInt(1 << 24);
855 module.exports = Long;
856 module.exports.Long = Long;