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