utils.h 11 KB

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