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