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 * This type is for INTERNAL use in MongoDB only and should not be used in applications.
17 * The appropriate corresponding type is the JavaScript Date type.
19 * Defines a Timestamp class for representing a 64-bit two's-complement
20 * integer value, which faithfully simulates the behavior of a Java "Timestamp". This
21 * implementation is derived from TimestampLib in GWT.
23 * Constructs a 64-bit two's-complement integer, given its low and high 32-bit
24 * values as *signed* integers. See the from* functions below for more
25 * convenient ways of constructing Timestamps.
27 * The internal representation of a Timestamp is the two given signed, 32-bit values.
28 * We use 32-bit pieces because these are the size of integers on which
29 * Javascript performs bit-operations. For operations like addition and
30 * multiplication, we split each number into 16-bit pieces, which can easily be
31 * multiplied within Javascript's floating-point representation without overflow
34 * In the algorithms below, we frequently reduce the negative case to the
35 * positive case by negating the input(s) and then post-processing the result.
36 * Note that we must ALWAYS check specially whether those values are MIN_VALUE
37 * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
38 * a positive number, it overflows back into a negative). Not handling this
39 * case would often result in infinite recursion.
42 * @param {number} low the low (signed) 32 bits of the Timestamp.
43 * @param {number} high the high (signed) 32 bits of the Timestamp.
45 function Timestamp(low, high) {
46 if(!(this instanceof Timestamp)) return new Timestamp(low, high);
47 this._bsontype = 'Timestamp';
52 this.low_ = low | 0; // force into 32 signed bits.
58 this.high_ = high | 0; // force into 32 signed bits.
62 * Return the int value.
64 * @return {number} the value, assuming it is a 32-bit integer.
66 Timestamp.prototype.toInt = function() {
71 * Return the Number value.
74 * @return {number} the closest floating-point representation to this value.
76 Timestamp.prototype.toNumber = function() {
77 return this.high_ * Timestamp.TWO_PWR_32_DBL_ +
78 this.getLowBitsUnsigned();
82 * Return the JSON value.
85 * @return {string} the JSON representation.
87 Timestamp.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 Timestamp.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(Timestamp.MIN_VALUE)) {
110 // We need to change the Timestamp 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 radixTimestamp = Timestamp.fromNumber(radix);
113 var div = this.div(radixTimestamp);
114 var rem = div.multiply(radixTimestamp).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 = Timestamp.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 Timestamp.prototype.getHighBits = function() {
155 * Return the low 32-bits value.
158 * @return {number} the low 32-bits as a signed value.
160 Timestamp.prototype.getLowBits = function() {
165 * Return the low unsigned 32-bits value.
168 * @return {number} the low 32-bits as an unsigned value.
170 Timestamp.prototype.getLowBitsUnsigned = function() {
171 return (this.low_ >= 0) ?
172 this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_;
176 * Returns the number of bits needed to represent the absolute value of this Timestamp.
179 * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp.
181 Timestamp.prototype.getNumBitsAbs = function() {
182 if (this.isNegative()) {
183 if (this.equals(Timestamp.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 Timestamp.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 Timestamp.prototype.isNegative = function() {
216 return this.high_ < 0;
220 * Return whether this value is odd.
223 * @return {boolean} whether this value is odd.
225 Timestamp.prototype.isOdd = function() {
226 return (this.low_ & 1) == 1;
230 * Return whether this Timestamp equals the other
233 * @param {Timestamp} other Timestamp to compare against.
234 * @return {boolean} whether this Timestamp equals the other
236 Timestamp.prototype.equals = function(other) {
237 return (this.high_ == other.high_) && (this.low_ == other.low_);
241 * Return whether this Timestamp does not equal the other.
244 * @param {Timestamp} other Timestamp to compare against.
245 * @return {boolean} whether this Timestamp does not equal the other.
247 Timestamp.prototype.notEquals = function(other) {
248 return (this.high_ != other.high_) || (this.low_ != other.low_);
252 * Return whether this Timestamp is less than the other.
255 * @param {Timestamp} other Timestamp to compare against.
256 * @return {boolean} whether this Timestamp is less than the other.
258 Timestamp.prototype.lessThan = function(other) {
259 return this.compare(other) < 0;
263 * Return whether this Timestamp is less than or equal to the other.
266 * @param {Timestamp} other Timestamp to compare against.
267 * @return {boolean} whether this Timestamp is less than or equal to the other.
269 Timestamp.prototype.lessThanOrEqual = function(other) {
270 return this.compare(other) <= 0;
274 * Return whether this Timestamp is greater than the other.
277 * @param {Timestamp} other Timestamp to compare against.
278 * @return {boolean} whether this Timestamp is greater than the other.
280 Timestamp.prototype.greaterThan = function(other) {
281 return this.compare(other) > 0;
285 * Return whether this Timestamp is greater than or equal to the other.
288 * @param {Timestamp} other Timestamp to compare against.
289 * @return {boolean} whether this Timestamp is greater than or equal to the other.
291 Timestamp.prototype.greaterThanOrEqual = function(other) {
292 return this.compare(other) >= 0;
296 * Compares this Timestamp with the given one.
299 * @param {Timestamp} other Timestamp 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 Timestamp.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 {Timestamp} the negation of this value.
330 Timestamp.prototype.negate = function() {
331 if (this.equals(Timestamp.MIN_VALUE)) {
332 return Timestamp.MIN_VALUE;
334 return this.not().add(Timestamp.ONE);
339 * Returns the sum of this and the given Timestamp.
342 * @param {Timestamp} other Timestamp to add to this one.
343 * @return {Timestamp} the sum of this and the given Timestamp.
345 Timestamp.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 Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
374 * Returns the difference of this and the given Timestamp.
377 * @param {Timestamp} other Timestamp to subtract from this.
378 * @return {Timestamp} the difference of this and the given Timestamp.
380 Timestamp.prototype.subtract = function(other) {
381 return this.add(other.negate());
385 * Returns the product of this and the given Timestamp.
388 * @param {Timestamp} other Timestamp to multiply with this.
389 * @return {Timestamp} the product of this and the other.
391 Timestamp.prototype.multiply = function(other) {
393 return Timestamp.ZERO;
394 } else if (other.isZero()) {
395 return Timestamp.ZERO;
398 if (this.equals(Timestamp.MIN_VALUE)) {
399 return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO;
400 } else if (other.equals(Timestamp.MIN_VALUE)) {
401 return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.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 Timestamps are small, use float multiplication
415 if (this.lessThan(Timestamp.TWO_PWR_24_) &&
416 other.lessThan(Timestamp.TWO_PWR_24_)) {
417 return Timestamp.fromNumber(this.toNumber() * other.toNumber());
420 // Divide each Timestamp 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 Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
458 * Returns this Timestamp divided by the given one.
461 * @param {Timestamp} other Timestamp by which to divide.
462 * @return {Timestamp} this Timestamp divided by the given one.
464 Timestamp.prototype.div = function(other) {
465 if (other.isZero()) {
466 throw Error('division by zero');
467 } else if (this.isZero()) {
468 return Timestamp.ZERO;
471 if (this.equals(Timestamp.MIN_VALUE)) {
472 if (other.equals(Timestamp.ONE) ||
473 other.equals(Timestamp.NEG_ONE)) {
474 return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
475 } else if (other.equals(Timestamp.MIN_VALUE)) {
476 return Timestamp.ONE;
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(Timestamp.ZERO)) {
482 return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE;
484 var rem = this.subtract(other.multiply(approx));
485 var result = approx.add(rem.div(other));
489 } else if (other.equals(Timestamp.MIN_VALUE)) {
490 return Timestamp.ZERO;
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.
508 var res = Timestamp.ZERO;
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 = Timestamp.fromNumber(approx);
523 var approxRem = approxRes.multiply(other);
524 while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
526 approxRes = Timestamp.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 = Timestamp.ONE;
536 res = res.add(approxRes);
537 rem = rem.subtract(approxRem);
543 * Returns this Timestamp modulo the given one.
546 * @param {Timestamp} other Timestamp by which to mod.
547 * @return {Timestamp} this Timestamp modulo the given one.
549 Timestamp.prototype.modulo = function(other) {
550 return this.subtract(this.div(other).multiply(other));
554 * The bitwise-NOT of this value.
557 * @return {Timestamp} the bitwise-NOT of this value.
559 Timestamp.prototype.not = function() {
560 return Timestamp.fromBits(~this.low_, ~this.high_);
564 * Returns the bitwise-AND of this Timestamp and the given one.
567 * @param {Timestamp} other the Timestamp with which to AND.
568 * @return {Timestamp} the bitwise-AND of this and the other.
570 Timestamp.prototype.and = function(other) {
571 return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_);
575 * Returns the bitwise-OR of this Timestamp and the given one.
578 * @param {Timestamp} other the Timestamp with which to OR.
579 * @return {Timestamp} the bitwise-OR of this and the other.
581 Timestamp.prototype.or = function(other) {
582 return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_);
586 * Returns the bitwise-XOR of this Timestamp and the given one.
589 * @param {Timestamp} other the Timestamp with which to XOR.
590 * @return {Timestamp} the bitwise-XOR of this and the other.
592 Timestamp.prototype.xor = function(other) {
593 return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_);
597 * Returns this Timestamp with bits shifted to the left by the given amount.
600 * @param {number} numBits the number of bits by which to shift.
601 * @return {Timestamp} this shifted to the left by the given amount.
603 Timestamp.prototype.shiftLeft = function(numBits) {
610 var high = this.high_;
611 return Timestamp.fromBits(
613 (high << numBits) | (low >>> (32 - numBits)));
615 return Timestamp.fromBits(0, low << (numBits - 32));
621 * Returns this Timestamp with bits shifted to the right by the given amount.
624 * @param {number} numBits the number of bits by which to shift.
625 * @return {Timestamp} this shifted to the right by the given amount.
627 Timestamp.prototype.shiftRight = function(numBits) {
632 var high = this.high_;
635 return Timestamp.fromBits(
636 (low >>> numBits) | (high << (32 - numBits)),
639 return Timestamp.fromBits(
640 high >> (numBits - 32),
647 * Returns this Timestamp 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 {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits.
653 Timestamp.prototype.shiftRightUnsigned = function(numBits) {
658 var high = this.high_;
661 return Timestamp.fromBits(
662 (low >>> numBits) | (high << (32 - numBits)),
664 } else if (numBits == 32) {
665 return Timestamp.fromBits(high, 0);
667 return Timestamp.fromBits(high >>> (numBits - 32), 0);
673 * Returns a Timestamp representing the given (32-bit) integer value.
676 * @param {number} value the 32-bit integer in question.
677 * @return {Timestamp} the corresponding Timestamp value.
679 Timestamp.fromInt = function(value) {
680 if (-128 <= value && value < 128) {
681 var cachedObj = Timestamp.INT_CACHE_[value];
687 var obj = new Timestamp(value | 0, value < 0 ? -1 : 0);
688 if (-128 <= value && value < 128) {
689 Timestamp.INT_CACHE_[value] = obj;
695 * Returns a Timestamp 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 {Timestamp} the corresponding Timestamp value.
701 Timestamp.fromNumber = function(value) {
702 if (isNaN(value) || !isFinite(value)) {
703 return Timestamp.ZERO;
704 } else if (value <= -Timestamp.TWO_PWR_63_DBL_) {
705 return Timestamp.MIN_VALUE;
706 } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) {
707 return Timestamp.MAX_VALUE;
708 } else if (value < 0) {
709 return Timestamp.fromNumber(-value).negate();
711 return new Timestamp(
712 (value % Timestamp.TWO_PWR_32_DBL_) | 0,
713 (value / Timestamp.TWO_PWR_32_DBL_) | 0);
718 * Returns a Timestamp 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 {Timestamp} the corresponding Timestamp value.
725 Timestamp.fromBits = function(lowBits, highBits) {
726 return new Timestamp(lowBits, highBits);
730 * Returns a Timestamp representation of the given string, written using the given radix.
733 * @param {string} str the textual representation of the Timestamp.
734 * @param {number} opt_radix the radix in which the text is written.
735 * @return {Timestamp} the corresponding Timestamp value.
737 Timestamp.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 Timestamp.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 = Timestamp.fromNumber(Math.pow(radix, 8));
757 var result = Timestamp.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 = Timestamp.fromNumber(Math.pow(radix, size));
763 result = result.multiply(power).add(Timestamp.fromNumber(value));
765 result = result.multiply(radixToPower);
766 result = result.add(Timestamp.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 Timestamp representations of small integer values.
781 Timestamp.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 Timestamp.TWO_PWR_16_DBL_ = 1 << 16;
798 Timestamp.TWO_PWR_24_DBL_ = 1 << 24;
804 Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_;
810 Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2;
816 Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_;
822 Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_;
828 Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2;
830 /** @type {Timestamp} */
831 Timestamp.ZERO = Timestamp.fromInt(0);
833 /** @type {Timestamp} */
834 Timestamp.ONE = Timestamp.fromInt(1);
836 /** @type {Timestamp} */
837 Timestamp.NEG_ONE = Timestamp.fromInt(-1);
839 /** @type {Timestamp} */
840 Timestamp.MAX_VALUE =
841 Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0);
843 /** @type {Timestamp} */
844 Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0);
850 Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24);
855 module.exports = Timestamp;
856 module.exports.Timestamp = Timestamp;