1// Copyright 2010 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6//     * Redistributions of source code must retain the above copyright
7//       notice, this list of conditions and the following disclaimer.
8//     * Redistributions in binary form must reproduce the above
9//       copyright notice, this list of conditions and the following
10//       disclaimer in the documentation and/or other materials provided
11//       with the distribution.
12//     * Neither the name of Google Inc. nor the names of its
13//       contributors may be used to endorse or promote products derived
14//       from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#ifndef DOUBLE_CONVERSION_DOUBLE_H_
29#define DOUBLE_CONVERSION_DOUBLE_H_
30
31#include "diy-fp.h"
32
33namespace WTF {
34
35namespace double_conversion {
36
37    // We assume that doubles and uint64_t have the same endianness.
38    static uint64_t double_to_uint64(double d) { return BitCast<uint64_t>(d); }
39    static double uint64_to_double(uint64_t d64) { return BitCast<double>(d64); }
40
41    // Helper functions for doubles.
42    class Double {
43    public:
44        static const uint64_t kSignMask = UINT64_2PART_C(0x80000000, 00000000);
45        static const uint64_t kExponentMask = UINT64_2PART_C(0x7FF00000, 00000000);
46        static const uint64_t kSignificandMask = UINT64_2PART_C(0x000FFFFF, FFFFFFFF);
47        static const uint64_t kHiddenBit = UINT64_2PART_C(0x00100000, 00000000);
48        static const int kPhysicalSignificandSize = 52;  // Excludes the hidden bit.
49        static const int kSignificandSize = 53;
50
51        Double() : d64_(0) {}
52        explicit Double(double d) : d64_(double_to_uint64(d)) {}
53        explicit Double(uint64_t d64) : d64_(d64) {}
54        explicit Double(DiyFp diy_fp)
55        : d64_(DiyFpToUint64(diy_fp)) {}
56
57        // The value encoded by this Double must be greater or equal to +0.0.
58        // It must not be special (infinity, or NaN).
59        DiyFp AsDiyFp() const {
60            ASSERT(Sign() > 0);
61            ASSERT(!IsSpecial());
62            return DiyFp(Significand(), Exponent());
63        }
64
65        // The value encoded by this Double must be strictly greater than 0.
66        DiyFp AsNormalizedDiyFp() const {
67            ASSERT(value() > 0.0);
68            uint64_t f = Significand();
69            int e = Exponent();
70
71            // The current double could be a denormal.
72            while ((f & kHiddenBit) == 0) {
73                f <<= 1;
74                e--;
75            }
76            // Do the final shifts in one go.
77            f <<= DiyFp::kSignificandSize - kSignificandSize;
78            e -= DiyFp::kSignificandSize - kSignificandSize;
79            return DiyFp(f, e);
80        }
81
82        // Returns the double's bit as uint64.
83        uint64_t AsUint64() const {
84            return d64_;
85        }
86
87        // Returns the next greater double. Returns +infinity on input +infinity.
88        double NextDouble() const {
89            if (d64_ == kInfinity) return Double(kInfinity).value();
90            if (Sign() < 0 && Significand() == 0) {
91                // -0.0
92                return 0.0;
93            }
94            if (Sign() < 0) {
95                return Double(d64_ - 1).value();
96            } else {
97                return Double(d64_ + 1).value();
98            }
99        }
100
101        int Exponent() const {
102            if (IsDenormal()) return kDenormalExponent;
103
104            uint64_t d64 = AsUint64();
105            int biased_e =
106            static_cast<int>((d64 & kExponentMask) >> kPhysicalSignificandSize);
107            return biased_e - kExponentBias;
108        }
109
110        uint64_t Significand() const {
111            uint64_t d64 = AsUint64();
112            uint64_t significand = d64 & kSignificandMask;
113            if (!IsDenormal()) {
114                return significand + kHiddenBit;
115            } else {
116                return significand;
117            }
118        }
119
120        // Returns true if the double is a denormal.
121        bool IsDenormal() const {
122            uint64_t d64 = AsUint64();
123            return (d64 & kExponentMask) == 0;
124        }
125
126        // We consider denormals not to be special.
127        // Hence only Infinity and NaN are special.
128        bool IsSpecial() const {
129            uint64_t d64 = AsUint64();
130            return (d64 & kExponentMask) == kExponentMask;
131        }
132
133        bool IsNan() const {
134            uint64_t d64 = AsUint64();
135            return ((d64 & kExponentMask) == kExponentMask) &&
136            ((d64 & kSignificandMask) != 0);
137        }
138
139        bool IsInfinite() const {
140            uint64_t d64 = AsUint64();
141            return ((d64 & kExponentMask) == kExponentMask) &&
142            ((d64 & kSignificandMask) == 0);
143        }
144
145        int Sign() const {
146            uint64_t d64 = AsUint64();
147            return (d64 & kSignMask) == 0? 1: -1;
148        }
149
150        // Precondition: the value encoded by this Double must be greater or equal
151        // than +0.0.
152        DiyFp UpperBoundary() const {
153            ASSERT(Sign() > 0);
154            return DiyFp(Significand() * 2 + 1, Exponent() - 1);
155        }
156
157        // Computes the two boundaries of this.
158        // The bigger boundary (m_plus) is normalized. The lower boundary has the same
159        // exponent as m_plus.
160        // Precondition: the value encoded by this Double must be greater than 0.
161        void NormalizedBoundaries(DiyFp* out_m_minus, DiyFp* out_m_plus) const {
162            ASSERT(value() > 0.0);
163            DiyFp v = this->AsDiyFp();
164            bool significand_is_zero = (v.f() == kHiddenBit);
165            DiyFp m_plus = DiyFp::Normalize(DiyFp((v.f() << 1) + 1, v.e() - 1));
166            DiyFp m_minus;
167            if (significand_is_zero && v.e() != kDenormalExponent) {
168                // The boundary is closer. Think of v = 1000e10 and v- = 9999e9.
169                // Then the boundary (== (v - v-)/2) is not just at a distance of 1e9 but
170                // at a distance of 1e8.
171                // The only exception is for the smallest normal: the largest denormal is
172                // at the same distance as its successor.
173                // Note: denormals have the same exponent as the smallest normals.
174                m_minus = DiyFp((v.f() << 2) - 1, v.e() - 2);
175            } else {
176                m_minus = DiyFp((v.f() << 1) - 1, v.e() - 1);
177            }
178            m_minus.set_f(m_minus.f() << (m_minus.e() - m_plus.e()));
179            m_minus.set_e(m_plus.e());
180            *out_m_plus = m_plus;
181            *out_m_minus = m_minus;
182        }
183
184        double value() const { return uint64_to_double(d64_); }
185
186        // Returns the significand size for a given order of magnitude.
187        // If v = f*2^e with 2^p-1 <= f <= 2^p then p+e is v's order of magnitude.
188        // This function returns the number of significant binary digits v will have
189        // once it's encoded into a double. In almost all cases this is equal to
190        // kSignificandSize. The only exceptions are denormals. They start with
191        // leading zeroes and their effective significand-size is hence smaller.
192        static int SignificandSizeForOrderOfMagnitude(int order) {
193            if (order >= (kDenormalExponent + kSignificandSize)) {
194                return kSignificandSize;
195            }
196            if (order <= kDenormalExponent) return 0;
197            return order - kDenormalExponent;
198        }
199
200        static double Infinity() {
201            return Double(kInfinity).value();
202        }
203
204        static double NaN() {
205            return Double(kNaN).value();
206        }
207
208    private:
209        static const int kExponentBias = 0x3FF + kPhysicalSignificandSize;
210        static const int kDenormalExponent = -kExponentBias + 1;
211        static const int kMaxExponent = 0x7FF - kExponentBias;
212        static const uint64_t kInfinity = UINT64_2PART_C(0x7FF00000, 00000000);
213        static const uint64_t kNaN = UINT64_2PART_C(0x7FF80000, 00000000);
214
215        const uint64_t d64_;
216
217        static uint64_t DiyFpToUint64(DiyFp diy_fp) {
218            uint64_t significand = diy_fp.f();
219            int exponent = diy_fp.e();
220            while (significand > kHiddenBit + kSignificandMask) {
221                significand >>= 1;
222                exponent++;
223            }
224            if (exponent >= kMaxExponent) {
225                return kInfinity;
226            }
227            if (exponent < kDenormalExponent) {
228                return 0;
229            }
230            while (exponent > kDenormalExponent && (significand & kHiddenBit) == 0) {
231                significand <<= 1;
232                exponent--;
233            }
234            uint64_t biased_exponent;
235            if (exponent == kDenormalExponent && (significand & kHiddenBit) == 0) {
236                biased_exponent = 0;
237            } else {
238                biased_exponent = static_cast<uint64_t>(exponent + kExponentBias);
239            }
240            return (significand & kSignificandMask) |
241            (biased_exponent << kPhysicalSignificandSize);
242        }
243    };
244
245}  // namespace double_conversion
246
247} // namespace WTF
248
249#endif  // DOUBLE_CONVERSION_DOUBLE_H_
250