1 // Copyright 2016 Google Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 ////////////////////////////////////////////////////////////////////////////////
16 
17 #ifndef UTIL_BASICTYPES_H_
18 #define UTIL_BASICTYPES_H_
19 
20 #include <limits.h>         // So we can set the bounds of our types
21 #include <stddef.h>         // For size_t
22 #include <string.h>         // for memcpy
23 
24 #include "util/port.h"    // Types that only need exist on certain systems
25 
26 #ifndef COMPILER_MSVC
27 // stdint.h is part of C99 but MSVC doesn't have it.
28 #include <stdint.h>         // For intptr_t.
29 #endif
30 
31 typedef signed char         schar;
32 typedef signed char         int8;
33 typedef short               int16;
34 // TODO(mbelshe) Remove these type guards.  These are
35 //               temporary to avoid conflicts with npapi.h.
36 #ifndef _INT32
37 #define _INT32
38 typedef int                 int32;
39 #endif
40 
41 // The NSPR system headers define 64-bit as |long| when possible.  In order to
42 // not have typedef mismatches, we do the same on LP64.
43 #if __LP64__
44 typedef long                int64;
45 #else
46 typedef long long           int64;
47 #endif
48 
49 // NOTE: unsigned types are DANGEROUS in loops and other arithmetical
50 // places.  Use the signed types unless your variable represents a bit
51 // pattern (eg a hash value) or you really need the extra bit.  Do NOT
52 // use 'unsigned' to express "this value should always be positive";
53 // use assertions for this.
54 
55 typedef unsigned char      uint8;
56 typedef unsigned short     uint16;
57 // TODO(mbelshe) Remove these type guards.  These are
58 //               temporary to avoid conflicts with npapi.h.
59 #ifndef _UINT32
60 #define _UINT32
61 typedef unsigned int       uint32;
62 #endif
63 
64 // See the comment above about NSPR and 64-bit.
65 #if __LP64__
66 typedef unsigned long uint64;
67 #else
68 typedef unsigned long long uint64;
69 #endif
70 
71 // A type to represent a Unicode code-point value. As of Unicode 4.0,
72 // such values require up to 21 bits.
73 // (For type-checking on pointers, make this explicitly signed,
74 // and it should always be the signed version of whatever int32 is.)
75 typedef signed int         char32;
76 
77 const uint8  kuint8max  = (( uint8) 0xFF);
78 const uint16 kuint16max = ((uint16) 0xFFFF);
79 const uint32 kuint32max = ((uint32) 0xFFFFFFFF);
80 const uint64 kuint64max = ((uint64) GG_LONGLONG(0xFFFFFFFFFFFFFFFF));
81 const  int8  kint8min   = ((  int8) 0x80);
82 const  int8  kint8max   = ((  int8) 0x7F);
83 const  int16 kint16min  = (( int16) 0x8000);
84 const  int16 kint16max  = (( int16) 0x7FFF);
85 const  int32 kint32min  = (( int32) 0x80000000);
86 const  int32 kint32max  = (( int32) 0x7FFFFFFF);
87 const  int64 kint64min  = (( int64) GG_LONGLONG(0x8000000000000000));
88 const  int64 kint64max  = (( int64) GG_LONGLONG(0x7FFFFFFFFFFFFFFF));
89 
90 // A macro to disallow the copy constructor and operator= functions
91 // This should be used in the private: declarations for a class
92 #define DISALLOW_COPY_AND_ASSIGN(TypeName) \
93   TypeName(const TypeName&);               \
94   void operator=(const TypeName&)
95 
96 // An older, deprecated, politically incorrect name for the above.
97 #define DISALLOW_EVIL_CONSTRUCTORS(TypeName) DISALLOW_COPY_AND_ASSIGN(TypeName)
98 
99 // A macro to disallow all the implicit constructors, namely the
100 // default constructor, copy constructor and operator= functions.
101 //
102 // This should be used in the private: declarations for a class
103 // that wants to prevent anyone from instantiating it. This is
104 // especially useful for classes containing only static methods.
105 #define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
106   TypeName();                                    \
107   DISALLOW_COPY_AND_ASSIGN(TypeName)
108 
109 // The arraysize(arr) macro returns the # of elements in an array arr.
110 // The expression is a compile-time constant, and therefore can be
111 // used in defining new arrays, for example.  If you use arraysize on
112 // a pointer by mistake, you will get a compile-time error.
113 
114 // This template function declaration is used in defining arraysize.
115 // Note that the function doesn't need an implementation, as we only
116 // use its type.
117 template <typename T, size_t N>
118 char (&ArraySizeHelper(T (&array)[N]))[N];
119 
120 // That gcc wants both of these prototypes seems mysterious. VC, for
121 // its part, can't decide which to use (another mystery). Matching of
122 // template overloads: the final frontier.
123 #ifndef _MSC_VER
124 template <typename T, size_t N>
125 char (&ArraySizeHelper(const T (&array)[N]))[N];
126 #endif
127 
128 #define arraysize(array) (sizeof(ArraySizeHelper(array)))
129 
130 
131 // Use implicit_cast as a safe version of static_cast or const_cast
132 // for upcasting in the type hierarchy (i.e. casting a pointer to Foo
133 // to a pointer to SuperclassOfFoo or casting a pointer to Foo to
134 // a const pointer to Foo).
135 // When you use implicit_cast, the compiler checks that the cast is safe.
136 // Such explicit implicit_casts are necessary in surprisingly many
137 // situations where C++ demands an exact type match instead of an
138 // argument type convertable to a target type.
139 //
140 // The From type can be inferred, so the preferred syntax for using
141 // implicit_cast is the same as for static_cast etc.:
142 //
143 //   implicit_cast<ToType>(expr)
144 //
145 // implicit_cast would have been part of the C++ standard library,
146 // but the proposal was submitted too late.  It will probably make
147 // its way into the language in the future.
148 template<typename To, typename From>
implicit_cast(From const & f)149 inline To implicit_cast(From const &f) {
150   return f;
151 }
152 
153 // The COMPILE_ASSERT macro can be used to verify that a compile time
154 // expression is true. For example, you could use it to verify the
155 // size of a static array:
156 //
157 //   COMPILE_ASSERT(arraysize(content_type_names) == CONTENT_NUM_TYPES,
158 //                  content_type_names_incorrect_size);
159 //
160 // or to make sure a struct is smaller than a certain size:
161 //
162 //   COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large);
163 //
164 // The second argument to the macro is the name of the variable. If
165 // the expression is false, most compilers will issue a warning/error
166 // containing the name of the variable.
167 
168 template <bool>
169 struct CompileAssert {
170 };
171 
172 #undef COMPILE_ASSERT
173 #define COMPILE_ASSERT(expr, msg) \
174   typedef CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1]
175 
176 // Implementation details of COMPILE_ASSERT:
177 //
178 // - COMPILE_ASSERT works by defining an array type that has -1
179 //   elements (and thus is invalid) when the expression is false.
180 //
181 // - The simpler definition
182 //
183 //     #define COMPILE_ASSERT(expr, msg) typedef char msg[(expr) ? 1 : -1]
184 //
185 //   does not work, as gcc supports variable-length arrays whose sizes
186 //   are determined at run-time (this is gcc's extension and not part
187 //   of the C++ standard).  As a result, gcc fails to reject the
188 //   following code with the simple definition:
189 //
190 //     int foo;
191 //     COMPILE_ASSERT(foo, msg); // not supposed to compile as foo is
192 //                               // not a compile-time constant.
193 //
194 // - By using the type CompileAssert<(bool(expr))>, we ensures that
195 //   expr is a compile-time constant.  (Template arguments must be
196 //   determined at compile-time.)
197 //
198 // - The outter parentheses in CompileAssert<(bool(expr))> are necessary
199 //   to work around a bug in gcc 3.4.4 and 4.0.1.  If we had written
200 //
201 //     CompileAssert<bool(expr)>
202 //
203 //   instead, these compilers will refuse to compile
204 //
205 //     COMPILE_ASSERT(5 > 0, some_message);
206 //
207 //   (They seem to think the ">" in "5 > 0" marks the end of the
208 //   template argument list.)
209 //
210 // - The array size is (bool(expr) ? 1 : -1), instead of simply
211 //
212 //     ((expr) ? 1 : -1).
213 //
214 //   This is to avoid running into a bug in MS VC 7.1, which
215 //   causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1.
216 
217 
218 // MetatagId refers to metatag-id that we assign to
219 // each metatag <name, value> pair..
220 typedef uint32 MetatagId;
221 
222 // Argument type used in interfaces that can optionally take ownership
223 // of a passed in argument.  If TAKE_OWNERSHIP is passed, the called
224 // object takes ownership of the argument.  Otherwise it does not.
225 enum Ownership {
226   DO_NOT_TAKE_OWNERSHIP,
227   TAKE_OWNERSHIP
228 };
229 
230 // bit_cast<Dest,Source> is a template function that implements the
231 // equivalent of "*reinterpret_cast<Dest*>(&source)".  We need this in
232 // very low-level functions like the protobuf library and fast math
233 // support.
234 //
235 //   float f = 3.14159265358979;
236 //   int i = bit_cast<int32>(f);
237 //   // i = 0x40490fdb
238 //
239 // The classical address-casting method is:
240 //
241 //   // WRONG
242 //   float f = 3.14159265358979;            // WRONG
243 //   int i = * reinterpret_cast<int*>(&f);  // WRONG
244 //
245 // The address-casting method actually produces undefined behavior
246 // according to ISO C++ specification section 3.10 -15 -.  Roughly, this
247 // section says: if an object in memory has one type, and a program
248 // accesses it with a different type, then the result is undefined
249 // behavior for most values of "different type".
250 //
251 // This is true for any cast syntax, either *(int*)&f or
252 // *reinterpret_cast<int*>(&f).  And it is particularly true for
253 // conversions betweeen integral lvalues and floating-point lvalues.
254 //
255 // The purpose of 3.10 -15- is to allow optimizing compilers to assume
256 // that expressions with different types refer to different memory.  gcc
257 // 4.0.1 has an optimizer that takes advantage of this.  So a
258 // non-conforming program quietly produces wildly incorrect output.
259 //
260 // The problem is not the use of reinterpret_cast.  The problem is type
261 // punning: holding an object in memory of one type and reading its bits
262 // back using a different type.
263 //
264 // The C++ standard is more subtle and complex than this, but that
265 // is the basic idea.
266 //
267 // Anyways ...
268 //
269 // bit_cast<> calls memcpy() which is blessed by the standard,
270 // especially by the example in section 3.9 .  Also, of course,
271 // bit_cast<> wraps up the nasty logic in one place.
272 //
273 // Fortunately memcpy() is very fast.  In optimized mode, with a
274 // constant size, gcc 2.95.3, gcc 4.0.1, and msvc 7.1 produce inline
275 // code with the minimal amount of data movement.  On a 32-bit system,
276 // memcpy(d,s,4) compiles to one load and one store, and memcpy(d,s,8)
277 // compiles to two loads and two stores.
278 //
279 // I tested this code with gcc 2.95.3, gcc 4.0.1, icc 8.1, and msvc 7.1.
280 //
281 // WARNING: if Dest or Source is a non-POD type, the result of the memcpy
282 // is likely to surprise you.
283 
284 template <class Dest, class Source>
bit_cast(const Source & source)285 inline Dest bit_cast(const Source& source) {
286   // Compile time assertion: sizeof(Dest) == sizeof(Source)
287   // A compile error here means your Dest and Source have different sizes.
288   // typedef char VerifySizesAreEqual [sizeof(Dest) == sizeof(Source) ? 1 : -1];
289 
290   Dest dest;
291   memcpy(&dest, &source, sizeof(dest));
292   return dest;
293 }
294 
295 // The following enum should be used only as a constructor argument to indicate
296 // that the variable has static storage class, and that the constructor should
297 // do nothing to its state.  It indicates to the reader that it is legal to
298 // declare a static instance of the class, provided the constructor is given
299 // the base::LINKER_INITIALIZED argument.  Normally, it is unsafe to declare a
300 // static variable that has a constructor or a destructor because invocation
301 // order is undefined.  However, IF the type can be initialized by filling with
302 // zeroes (which the loader does for static variables), AND the destructor also
303 // does nothing to the storage, AND there are no virtual methods, then a
304 // constructor declared as
305 //       explicit MyClass(base::LinkerInitialized x) {}
306 // and invoked as
307 //       static MyClass my_variable_name(base::LINKER_INITIALIZED);
308 namespace base {
309 enum LinkerInitialized { LINKER_INITIALIZED };
310 }  // base
311 
312 // UnaligndLoad32 is put here instead of util/port.h to
313 // avoid the circular dependency between port.h and basictypes.h
314 // ARM does not support unaligned memory access.
315 #if defined(ARCH_CPU_X86_FAMILY)
316 // x86 and x86-64 can perform unaligned loads/stores directly;
UnalignedLoad32(const void * p)317 inline uint32 UnalignedLoad32(const void* p) {
318   return *reinterpret_cast<const uint32*>(p);
319 }
320 #else
321 #define NEED_ALIGNED_LOADS
322 // If target architecture does not support unaligned loads and stores,
323 // use memcpy version of UNALIGNED_LOAD32.
UnalignedLoad32(const void * p)324 inline uint32 UnalignedLoad32(const void* p) {
325   uint32 t;
326   memcpy(&t, reinterpret_cast<const uint8*>(p), sizeof(t));
327   return t;
328 }
329 
330 #endif
331 #endif  // UTIL_BASICTYPES_H_
332