utils.h 12 KB

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