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