Debian Codegraph @

js/src/builtin/temporal/Int96.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "builtin/temporal/Int96.h"
8
9 #include "mozilla/Assertions.h"
10 #include "mozilla/Casting.h"
11 #include "mozilla/FloatingPoint.h"
12 #include "mozilla/Maybe.h"
13
14 #include <cmath>
15 #include <stddef.h>
16 #include <stdint.h>
17
18 #include "jsnum.h"
19
20 using namespace js;
21 using namespace js::temporal;
22
23 mozilla::Maybe<Int96> Int96::fromInteger(double value) {
24 MOZ_ASSERT(IsInteger(value));
25
26 // Fast path for the common case.
27 int64_t intValue;
28 if (mozilla::NumberEqualsInt64(value, &intValue)) {
29 return mozilla::Some(Int96{intValue});
30 }
31
32 // First double integer which requires more than three digits.
33 constexpr double maximum = 0x1p+96;
34
35 // Reject if the value needs more than 96 bits.
36 if (std::abs(value) >= maximum) {
37 return mozilla::Nothing();
38 }
39
40 // Inlined version of |BigInt::createFromDouble()| for DigitBits=32. See the
41 // comments in |BigInt::createFromDouble()| for how this code works.
42 constexpr int DigitBits = 32;
43
44 // The number can't have more than three digits when it's below |maximum|.
45 Int96::Digits digits = {};
46
47 int exponent = int(mozilla::ExponentComponent(value));
48 MOZ_ASSERT(0 <= exponent && exponent <= 95,
49 "exponent is lower than exponent of 0x1p+96");
50
51 int length = exponent / DigitBits + 1;
52 MOZ_ASSERT(1 <= length && length <= 3);
53
54 using Double = mozilla::FloatingPoint<double>;
55 uint64_t mantissa =
56 mozilla::BitwiseCast<uint64_t>(value) & Double::kSignificandBits;
57
58 // Add implicit high bit.
59 mantissa |= 1ull << Double::kSignificandWidth;
60
61 // 0-indexed position of the double's most significant bit within the `msd`.
62 int msdTopBit = exponent % DigitBits;
63
64 // First, build the MSD by shifting the mantissa appropriately.
65 int remainingMantissaBits = int(Double::kSignificandWidth - msdTopBit);
66 digits[--length] = mantissa >> remainingMantissaBits;
67
68 // Fill in digits containing mantissa contributions.
69 mantissa = mantissa << (64 - remainingMantissaBits);
70 if (mantissa) {
71 MOZ_ASSERT(length > 0);
72 digits[--length] = uint32_t(mantissa >> 32);
73
74 if (uint32_t(mantissa)) {
75 MOZ_ASSERT(length > 0);
76 digits[--length] = uint32_t(mantissa);
77 }
78 }
79
80 return mozilla::Some(Int96{digits, value < 0});
81 }