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