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_UTILS_H_
29 #define DOUBLE_CONVERSION_UTILS_H_
30
31 #include <cstdlib>
32 #include <cstring>
33
34 #include "mozilla/Assertions.h"
35 #ifndef DOUBLE_CONVERSION_ASSERT
36 #define DOUBLE_CONVERSION_ASSERT(condition) \
37 MOZ_ASSERT(condition)
38 #endif
39 #ifndef DOUBLE_CONVERSION_UNIMPLEMENTED
40 #define DOUBLE_CONVERSION_UNIMPLEMENTED() MOZ_CRASH()
41 #endif
42 #ifndef DOUBLE_CONVERSION_NO_RETURN
43 #ifdef _MSC_VER
44 #define DOUBLE_CONVERSION_NO_RETURN __declspec(noreturn)
45 #else
46 #define DOUBLE_CONVERSION_NO_RETURN __attribute__((noreturn))
47 #endif
48 #endif
49 #ifndef DOUBLE_CONVERSION_UNREACHABLE
50 #ifdef _MSC_VER
51 void DOUBLE_CONVERSION_NO_RETURN abort_noreturn();
abort_noreturn()52 inline void abort_noreturn() { MOZ_CRASH(); }
53 #define DOUBLE_CONVERSION_UNREACHABLE() (abort_noreturn())
54 #else
55 #define DOUBLE_CONVERSION_UNREACHABLE() MOZ_CRASH()
56 #endif
57 #endif
58
59 #ifndef DOUBLE_CONVERSION_UNUSED
60 #ifdef __GNUC__
61 #define DOUBLE_CONVERSION_UNUSED __attribute__((unused))
62 #else
63 #define DOUBLE_CONVERSION_UNUSED
64 #endif
65 #endif
66
67 // Double operations detection based on target architecture.
68 // Linux uses a 80bit wide floating point stack on x86. This induces double
69 // rounding, which in turn leads to wrong results.
70 // An easy way to test if the floating-point operations are correct is to
71 // evaluate: 89255.0/1e22. If the floating-point stack is 64 bits wide then
72 // the result is equal to 89255e-22.
73 // The best way to test this, is to create a division-function and to compare
74 // the output of the division with the expected result. (Inlining must be
75 // disabled.)
76 // On Linux,x86 89255e-22 != Div_double(89255.0/1e22)
77 //
78 // For example:
79 /*
80 // -- in div.c
81 double Div_double(double x, double y) { return x / y; }
82
83 // -- in main.c
84 double Div_double(double x, double y); // Forward declaration.
85
86 int main(int argc, char** argv) {
87 return Div_double(89255.0, 1e22) == 89255e-22;
88 }
89 */
90 // Run as follows ./main || echo "correct"
91 //
92 // If it prints "correct" then the architecture should be here, in the "correct" section.
93 #if defined(_M_X64) || defined(__x86_64__) || \
94 defined(__ARMEL__) || defined(__avr32__) || defined(_M_ARM) || defined(_M_ARM64) || \
95 defined(__hppa__) || defined(__ia64__) || \
96 defined(__mips__) || \
97 defined(__powerpc__) || defined(__ppc__) || defined(__ppc64__) || \
98 defined(_POWER) || defined(_ARCH_PPC) || defined(_ARCH_PPC64) || \
99 defined(__sparc__) || defined(__sparc) || defined(__s390__) || \
100 defined(__SH4__) || defined(__alpha__) || \
101 defined(_MIPS_ARCH_MIPS32R2) || defined(__ARMEB__) ||\
102 defined(__AARCH64EL__) || defined(__aarch64__) || defined(__AARCH64EB__) || \
103 defined(__riscv) || defined(__e2k__) || \
104 defined(__or1k__) || defined(__arc__) || \
105 defined(__EMSCRIPTEN__)
106 #define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1
107 #elif defined(__mc68000__) || \
108 defined(__pnacl__) || defined(__native_client__)
109 #undef DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS
110 #elif defined(_M_IX86) || defined(__i386__) || defined(__i386)
111 #if defined(_WIN32)
112 // Windows uses a 64bit wide floating point stack.
113 #define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1
114 #else
115 #undef DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS
116 #endif // _WIN32
117 #else
118 #error Target architecture was not detected as supported by Double-Conversion.
119 #endif
120
121 #if defined(_WIN32) && !defined(__MINGW32__)
122
123 typedef signed char int8_t;
124 typedef unsigned char uint8_t;
125 typedef short int16_t; // NOLINT
126 typedef unsigned short uint16_t; // NOLINT
127 typedef int int32_t;
128 typedef unsigned int uint32_t;
129 typedef __int64 int64_t;
130 typedef unsigned __int64 uint64_t;
131 // intptr_t and friends are defined in crtdefs.h through stdio.h.
132
133 #else
134
135 #include <stdint.h>
136
137 #endif
138
139 typedef uint16_t uc16;
140
141 // The following macro works on both 32 and 64-bit platforms.
142 // Usage: instead of writing 0x1234567890123456
143 // write DOUBLE_CONVERSION_UINT64_2PART_C(0x12345678,90123456);
144 #define DOUBLE_CONVERSION_UINT64_2PART_C(a, b) (((static_cast<uint64_t>(a) << 32) + 0x##b##u))
145
146
147 // The expression DOUBLE_CONVERSION_ARRAY_SIZE(a) is a compile-time constant of type
148 // size_t which represents the number of elements of the given
149 // array. You should only use DOUBLE_CONVERSION_ARRAY_SIZE on statically allocated
150 // arrays.
151 #ifndef DOUBLE_CONVERSION_ARRAY_SIZE
152 #define DOUBLE_CONVERSION_ARRAY_SIZE(a) \
153 ((sizeof(a) / sizeof(*(a))) / \
154 static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
155 #endif
156
157 // A macro to disallow the evil copy constructor and operator= functions
158 // This should be used in the private: declarations for a class
159 #ifndef DOUBLE_CONVERSION_DISALLOW_COPY_AND_ASSIGN
160 #define DOUBLE_CONVERSION_DISALLOW_COPY_AND_ASSIGN(TypeName) \
161 TypeName(const TypeName&); \
162 void operator=(const TypeName&)
163 #endif
164
165 // A macro to disallow all the implicit constructors, namely the
166 // default constructor, copy constructor and operator= functions.
167 //
168 // This should be used in the private: declarations for a class
169 // that wants to prevent anyone from instantiating it. This is
170 // especially useful for classes containing only static methods.
171 #ifndef DOUBLE_CONVERSION_DISALLOW_IMPLICIT_CONSTRUCTORS
172 #define DOUBLE_CONVERSION_DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
173 TypeName(); \
174 DOUBLE_CONVERSION_DISALLOW_COPY_AND_ASSIGN(TypeName)
175 #endif
176
177 namespace double_conversion {
178
StrLength(const char * string)179 inline int StrLength(const char* string) {
180 size_t length = strlen(string);
181 DOUBLE_CONVERSION_ASSERT(length == static_cast<size_t>(static_cast<int>(length)));
182 return static_cast<int>(length);
183 }
184
185 // This is a simplified version of V8's Vector class.
186 template <typename T>
187 class Vector {
188 public:
Vector()189 Vector() : start_(NULL), length_(0) {}
Vector(T * data,int len)190 Vector(T* data, int len) : start_(data), length_(len) {
191 DOUBLE_CONVERSION_ASSERT(len == 0 || (len > 0 && data != NULL));
192 }
193
194 // Returns a vector using the same backing storage as this one,
195 // spanning from and including 'from', to but not including 'to'.
SubVector(int from,int to)196 Vector<T> SubVector(int from, int to) {
197 DOUBLE_CONVERSION_ASSERT(to <= length_);
198 DOUBLE_CONVERSION_ASSERT(from < to);
199 DOUBLE_CONVERSION_ASSERT(0 <= from);
200 return Vector<T>(start() + from, to - from);
201 }
202
203 // Returns the length of the vector.
length()204 int length() const { return length_; }
205
206 // Returns whether or not the vector is empty.
is_empty()207 bool is_empty() const { return length_ == 0; }
208
209 // Returns the pointer to the start of the data in the vector.
start()210 T* start() const { return start_; }
211
212 // Access individual vector elements - checks bounds in debug mode.
213 T& operator[](int index) const {
214 DOUBLE_CONVERSION_ASSERT(0 <= index && index < length_);
215 return start_[index];
216 }
217
first()218 T& first() { return start_[0]; }
219
last()220 T& last() { return start_[length_ - 1]; }
221
pop_back()222 void pop_back() {
223 DOUBLE_CONVERSION_ASSERT(!is_empty());
224 --length_;
225 }
226
227 private:
228 T* start_;
229 int length_;
230 };
231
232
233 // Helper class for building result strings in a character buffer. The
234 // purpose of the class is to use safe operations that checks the
235 // buffer bounds on all operations in debug mode.
236 class StringBuilder {
237 public:
StringBuilder(char * buffer,int buffer_size)238 StringBuilder(char* buffer, int buffer_size)
239 : buffer_(buffer, buffer_size), position_(0) { }
240
~StringBuilder()241 ~StringBuilder() { if (!is_finalized()) Finalize(); }
242
size()243 int size() const { return buffer_.length(); }
244
245 // Get the current position in the builder.
position()246 int position() const {
247 DOUBLE_CONVERSION_ASSERT(!is_finalized());
248 return position_;
249 }
250
251 // Reset the position.
Reset()252 void Reset() { position_ = 0; }
253
254 // Add a single character to the builder. It is not allowed to add
255 // 0-characters; use the Finalize() method to terminate the string
256 // instead.
AddCharacter(char c)257 void AddCharacter(char c) {
258 DOUBLE_CONVERSION_ASSERT(c != '\0');
259 DOUBLE_CONVERSION_ASSERT(!is_finalized() && position_ < buffer_.length());
260 buffer_[position_++] = c;
261 }
262
263 // Add an entire string to the builder. Uses strlen() internally to
264 // compute the length of the input string.
AddString(const char * s)265 void AddString(const char* s) {
266 AddSubstring(s, StrLength(s));
267 }
268
269 // Add the first 'n' characters of the given string 's' to the
270 // builder. The input string must have enough characters.
AddSubstring(const char * s,int n)271 void AddSubstring(const char* s, int n) {
272 DOUBLE_CONVERSION_ASSERT(!is_finalized() && position_ + n < buffer_.length());
273 DOUBLE_CONVERSION_ASSERT(static_cast<size_t>(n) <= strlen(s));
274 memmove(&buffer_[position_], s, n);
275 position_ += n;
276 }
277
278
279 // Add character padding to the builder. If count is non-positive,
280 // nothing is added to the builder.
AddPadding(char c,int count)281 void AddPadding(char c, int count) {
282 for (int i = 0; i < count; i++) {
283 AddCharacter(c);
284 }
285 }
286
287 // Finalize the string by 0-terminating it and returning the buffer.
Finalize()288 char* Finalize() {
289 DOUBLE_CONVERSION_ASSERT(!is_finalized() && position_ < buffer_.length());
290 buffer_[position_] = '\0';
291 // Make sure nobody managed to add a 0-character to the
292 // buffer while building the string.
293 DOUBLE_CONVERSION_ASSERT(strlen(buffer_.start()) == static_cast<size_t>(position_));
294 position_ = -1;
295 DOUBLE_CONVERSION_ASSERT(is_finalized());
296 return buffer_.start();
297 }
298
299 private:
300 Vector<char> buffer_;
301 int position_;
302
is_finalized()303 bool is_finalized() const { return position_ < 0; }
304
305 DOUBLE_CONVERSION_DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder);
306 };
307
308 // The type-based aliasing rule allows the compiler to assume that pointers of
309 // different types (for some definition of different) never alias each other.
310 // Thus the following code does not work:
311 //
312 // float f = foo();
313 // int fbits = *(int*)(&f);
314 //
315 // The compiler 'knows' that the int pointer can't refer to f since the types
316 // don't match, so the compiler may cache f in a register, leaving random data
317 // in fbits. Using C++ style casts makes no difference, however a pointer to
318 // char data is assumed to alias any other pointer. This is the 'memcpy
319 // exception'.
320 //
321 // Bit_cast uses the memcpy exception to move the bits from a variable of one
322 // type of a variable of another type. Of course the end result is likely to
323 // be implementation dependent. Most compilers (gcc-4.2 and MSVC 2005)
324 // will completely optimize BitCast away.
325 //
326 // There is an additional use for BitCast.
327 // Recent gccs will warn when they see casts that may result in breakage due to
328 // the type-based aliasing rule. If you have checked that there is no breakage
329 // you can use BitCast to cast one pointer type to another. This confuses gcc
330 // enough that it can no longer see that you have cast one pointer type to
331 // another thus avoiding the warning.
332 template <class Dest, class Source>
BitCast(const Source & source)333 Dest BitCast(const Source& source) {
334 // Compile time assertion: sizeof(Dest) == sizeof(Source)
335 // A compile error here means your Dest and Source have different sizes.
336 #if __cplusplus >= 201103L
337 static_assert(sizeof(Dest) == sizeof(Source),
338 "source and destination size mismatch");
339 #else
340 DOUBLE_CONVERSION_UNUSED
341 typedef char VerifySizesAreEqual[sizeof(Dest) == sizeof(Source) ? 1 : -1];
342 #endif
343
344 Dest dest;
345 memmove(&dest, &source, sizeof(dest));
346 return dest;
347 }
348
349 template <class Dest, class Source>
BitCast(Source * source)350 Dest BitCast(Source* source) {
351 return BitCast<Dest>(reinterpret_cast<uintptr_t>(source));
352 }
353
354 } // namespace double_conversion
355
356 #endif // DOUBLE_CONVERSION_UTILS_H_
357