double-conversion-utils.h 14 KB

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