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