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