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