utils.h 13 KB

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