Initialize Tizen 2.3
[external/chromium.git] / base / basictypes.h
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef BASE_BASICTYPES_H_
6 #define BASE_BASICTYPES_H_
7 #pragma once
8
9 #include <limits.h>         // So we can set the bounds of our types
10 #include <stddef.h>         // For size_t
11 #include <string.h>         // for memcpy
12
13 #include "base/port.h"    // Types that only need exist on certain systems
14
15 #ifndef COMPILER_MSVC
16 // stdint.h is part of C99 but MSVC doesn't have it.
17 #include <stdint.h>         // For intptr_t.
18 #endif
19
20 typedef signed char         schar;
21 typedef signed char         int8;
22 typedef short               int16;
23 // TODO: Remove these type guards.  These are to avoid conflicts with
24 // obsolete/protypes.h in the Gecko SDK.
25 #ifndef _INT32
26 #define _INT32
27 typedef int                 int32;
28 #endif
29
30 // The NSPR system headers define 64-bit as |long| when possible, except on
31 // Mac OS X.  In order to not have typedef mismatches, we do the same on LP64.
32 //
33 // On Mac OS X, |long long| is used for 64-bit types for compatibility with
34 // <inttypes.h> format macros even in the LP64 model.
35 #if defined(__LP64__) && !defined(OS_MACOSX)
36 typedef long                int64;
37 #else
38 typedef long long           int64;
39 #endif
40
41 // NOTE: unsigned types are DANGEROUS in loops and other arithmetical
42 // places.  Use the signed types unless your variable represents a bit
43 // pattern (eg a hash value) or you really need the extra bit.  Do NOT
44 // use 'unsigned' to express "this value should always be positive";
45 // use assertions for this.
46
47 typedef unsigned char      uint8;
48 typedef unsigned short     uint16;
49 // TODO: Remove these type guards.  These are to avoid conflicts with
50 // obsolete/protypes.h in the Gecko SDK.
51 #ifndef _UINT32
52 #define _UINT32
53 typedef unsigned int       uint32;
54 #endif
55
56 // See the comment above about NSPR and 64-bit.
57 #if defined(__LP64__) && !defined(OS_MACOSX)
58 typedef unsigned long uint64;
59 #else
60 typedef unsigned long long uint64;
61 #endif
62
63 // A type to represent a Unicode code-point value. As of Unicode 4.0,
64 // such values require up to 21 bits.
65 // (For type-checking on pointers, make this explicitly signed,
66 // and it should always be the signed version of whatever int32 is.)
67 typedef signed int         char32;
68
69 const uint8  kuint8max  = (( uint8) 0xFF);
70 const uint16 kuint16max = ((uint16) 0xFFFF);
71 const uint32 kuint32max = ((uint32) 0xFFFFFFFF);
72 const uint64 kuint64max = ((uint64) GG_LONGLONG(0xFFFFFFFFFFFFFFFF));
73 const  int8  kint8min   = ((  int8) 0x80);
74 const  int8  kint8max   = ((  int8) 0x7F);
75 const  int16 kint16min  = (( int16) 0x8000);
76 const  int16 kint16max  = (( int16) 0x7FFF);
77 const  int32 kint32min  = (( int32) 0x80000000);
78 const  int32 kint32max  = (( int32) 0x7FFFFFFF);
79 const  int64 kint64min  = (( int64) GG_LONGLONG(0x8000000000000000));
80 const  int64 kint64max  = (( int64) GG_LONGLONG(0x7FFFFFFFFFFFFFFF));
81
82 // A macro to disallow the copy constructor and operator= functions
83 // This should be used in the private: declarations for a class
84 #define DISALLOW_COPY_AND_ASSIGN(TypeName) \
85   TypeName(const TypeName&);               \
86   void operator=(const TypeName&)
87
88 // An older, deprecated, politically incorrect name for the above.
89 // NOTE: The usage of this macro was baned from our code base, but some
90 // third_party libraries are yet using it.
91 // TODO(tfarina): Figure out how to fix the usage of this macro in the
92 // third_party libraries and get rid of it.
93 #define DISALLOW_EVIL_CONSTRUCTORS(TypeName) DISALLOW_COPY_AND_ASSIGN(TypeName)
94
95 // A macro to disallow all the implicit constructors, namely the
96 // default constructor, copy constructor and operator= functions.
97 //
98 // This should be used in the private: declarations for a class
99 // that wants to prevent anyone from instantiating it. This is
100 // especially useful for classes containing only static methods.
101 #define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
102   TypeName();                                    \
103   DISALLOW_COPY_AND_ASSIGN(TypeName)
104
105 // The arraysize(arr) macro returns the # of elements in an array arr.
106 // The expression is a compile-time constant, and therefore can be
107 // used in defining new arrays, for example.  If you use arraysize on
108 // a pointer by mistake, you will get a compile-time error.
109 //
110 // One caveat is that arraysize() doesn't accept any array of an
111 // anonymous type or a type defined inside a function.  In these rare
112 // cases, you have to use the unsafe ARRAYSIZE_UNSAFE() macro below.  This is
113 // due to a limitation in C++'s template system.  The limitation might
114 // eventually be removed, but it hasn't happened yet.
115
116 // This template function declaration is used in defining arraysize.
117 // Note that the function doesn't need an implementation, as we only
118 // use its type.
119 template <typename T, size_t N>
120 char (&ArraySizeHelper(T (&array)[N]))[N];
121
122 // That gcc wants both of these prototypes seems mysterious. VC, for
123 // its part, can't decide which to use (another mystery). Matching of
124 // template overloads: the final frontier.
125 #ifndef _MSC_VER
126 template <typename T, size_t N>
127 char (&ArraySizeHelper(const T (&array)[N]))[N];
128 #endif
129
130 #define arraysize(array) (sizeof(ArraySizeHelper(array)))
131
132 // ARRAYSIZE_UNSAFE performs essentially the same calculation as arraysize,
133 // but can be used on anonymous types or types defined inside
134 // functions.  It's less safe than arraysize as it accepts some
135 // (although not all) pointers.  Therefore, you should use arraysize
136 // whenever possible.
137 //
138 // The expression ARRAYSIZE_UNSAFE(a) is a compile-time constant of type
139 // size_t.
140 //
141 // ARRAYSIZE_UNSAFE catches a few type errors.  If you see a compiler error
142 //
143 //   "warning: division by zero in ..."
144 //
145 // when using ARRAYSIZE_UNSAFE, you are (wrongfully) giving it a pointer.
146 // You should only use ARRAYSIZE_UNSAFE on statically allocated arrays.
147 //
148 // The following comments are on the implementation details, and can
149 // be ignored by the users.
150 //
151 // ARRAYSIZE_UNSAFE(arr) works by inspecting sizeof(arr) (the # of bytes in
152 // the array) and sizeof(*(arr)) (the # of bytes in one array
153 // element).  If the former is divisible by the latter, perhaps arr is
154 // indeed an array, in which case the division result is the # of
155 // elements in the array.  Otherwise, arr cannot possibly be an array,
156 // and we generate a compiler error to prevent the code from
157 // compiling.
158 //
159 // Since the size of bool is implementation-defined, we need to cast
160 // !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final
161 // result has type size_t.
162 //
163 // This macro is not perfect as it wrongfully accepts certain
164 // pointers, namely where the pointer size is divisible by the pointee
165 // size.  Since all our code has to go through a 32-bit compiler,
166 // where a pointer is 4 bytes, this means all pointers to a type whose
167 // size is 3 or greater than 4 will be (righteously) rejected.
168
169 #define ARRAYSIZE_UNSAFE(a) \
170   ((sizeof(a) / sizeof(*(a))) / \
171    static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
172
173
174 // Use implicit_cast as a safe version of static_cast or const_cast
175 // for upcasting in the type hierarchy (i.e. casting a pointer to Foo
176 // to a pointer to SuperclassOfFoo or casting a pointer to Foo to
177 // a const pointer to Foo).
178 // When you use implicit_cast, the compiler checks that the cast is safe.
179 // Such explicit implicit_casts are necessary in surprisingly many
180 // situations where C++ demands an exact type match instead of an
181 // argument type convertable to a target type.
182 //
183 // The From type can be inferred, so the preferred syntax for using
184 // implicit_cast is the same as for static_cast etc.:
185 //
186 //   implicit_cast<ToType>(expr)
187 //
188 // implicit_cast would have been part of the C++ standard library,
189 // but the proposal was submitted too late.  It will probably make
190 // its way into the language in the future.
191 template<typename To, typename From>
192 inline To implicit_cast(From const &f) {
193   return f;
194 }
195
196 // The COMPILE_ASSERT macro can be used to verify that a compile time
197 // expression is true. For example, you could use it to verify the
198 // size of a static array:
199 //
200 //   COMPILE_ASSERT(ARRAYSIZE_UNSAFE(content_type_names) == CONTENT_NUM_TYPES,
201 //                  content_type_names_incorrect_size);
202 //
203 // or to make sure a struct is smaller than a certain size:
204 //
205 //   COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large);
206 //
207 // The second argument to the macro is the name of the variable. If
208 // the expression is false, most compilers will issue a warning/error
209 // containing the name of the variable.
210
211 template <bool>
212 struct CompileAssert {
213 };
214
215 #undef COMPILE_ASSERT
216 #define COMPILE_ASSERT(expr, msg) \
217   typedef CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1]
218
219 // Implementation details of COMPILE_ASSERT:
220 //
221 // - COMPILE_ASSERT works by defining an array type that has -1
222 //   elements (and thus is invalid) when the expression is false.
223 //
224 // - The simpler definition
225 //
226 //     #define COMPILE_ASSERT(expr, msg) typedef char msg[(expr) ? 1 : -1]
227 //
228 //   does not work, as gcc supports variable-length arrays whose sizes
229 //   are determined at run-time (this is gcc's extension and not part
230 //   of the C++ standard).  As a result, gcc fails to reject the
231 //   following code with the simple definition:
232 //
233 //     int foo;
234 //     COMPILE_ASSERT(foo, msg); // not supposed to compile as foo is
235 //                               // not a compile-time constant.
236 //
237 // - By using the type CompileAssert<(bool(expr))>, we ensures that
238 //   expr is a compile-time constant.  (Template arguments must be
239 //   determined at compile-time.)
240 //
241 // - The outer parentheses in CompileAssert<(bool(expr))> are necessary
242 //   to work around a bug in gcc 3.4.4 and 4.0.1.  If we had written
243 //
244 //     CompileAssert<bool(expr)>
245 //
246 //   instead, these compilers will refuse to compile
247 //
248 //     COMPILE_ASSERT(5 > 0, some_message);
249 //
250 //   (They seem to think the ">" in "5 > 0" marks the end of the
251 //   template argument list.)
252 //
253 // - The array size is (bool(expr) ? 1 : -1), instead of simply
254 //
255 //     ((expr) ? 1 : -1).
256 //
257 //   This is to avoid running into a bug in MS VC 7.1, which
258 //   causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1.
259
260
261 // MetatagId refers to metatag-id that we assign to
262 // each metatag <name, value> pair..
263 typedef uint32 MetatagId;
264
265 // Argument type used in interfaces that can optionally take ownership
266 // of a passed in argument.  If TAKE_OWNERSHIP is passed, the called
267 // object takes ownership of the argument.  Otherwise it does not.
268 enum Ownership {
269   DO_NOT_TAKE_OWNERSHIP,
270   TAKE_OWNERSHIP
271 };
272
273 // bit_cast<Dest,Source> is a template function that implements the
274 // equivalent of "*reinterpret_cast<Dest*>(&source)".  We need this in
275 // very low-level functions like the protobuf library and fast math
276 // support.
277 //
278 //   float f = 3.14159265358979;
279 //   int i = bit_cast<int32>(f);
280 //   // i = 0x40490fdb
281 //
282 // The classical address-casting method is:
283 //
284 //   // WRONG
285 //   float f = 3.14159265358979;            // WRONG
286 //   int i = * reinterpret_cast<int*>(&f);  // WRONG
287 //
288 // The address-casting method actually produces undefined behavior
289 // according to ISO C++ specification section 3.10 -15 -.  Roughly, this
290 // section says: if an object in memory has one type, and a program
291 // accesses it with a different type, then the result is undefined
292 // behavior for most values of "different type".
293 //
294 // This is true for any cast syntax, either *(int*)&f or
295 // *reinterpret_cast<int*>(&f).  And it is particularly true for
296 // conversions betweeen integral lvalues and floating-point lvalues.
297 //
298 // The purpose of 3.10 -15- is to allow optimizing compilers to assume
299 // that expressions with different types refer to different memory.  gcc
300 // 4.0.1 has an optimizer that takes advantage of this.  So a
301 // non-conforming program quietly produces wildly incorrect output.
302 //
303 // The problem is not the use of reinterpret_cast.  The problem is type
304 // punning: holding an object in memory of one type and reading its bits
305 // back using a different type.
306 //
307 // The C++ standard is more subtle and complex than this, but that
308 // is the basic idea.
309 //
310 // Anyways ...
311 //
312 // bit_cast<> calls memcpy() which is blessed by the standard,
313 // especially by the example in section 3.9 .  Also, of course,
314 // bit_cast<> wraps up the nasty logic in one place.
315 //
316 // Fortunately memcpy() is very fast.  In optimized mode, with a
317 // constant size, gcc 2.95.3, gcc 4.0.1, and msvc 7.1 produce inline
318 // code with the minimal amount of data movement.  On a 32-bit system,
319 // memcpy(d,s,4) compiles to one load and one store, and memcpy(d,s,8)
320 // compiles to two loads and two stores.
321 //
322 // I tested this code with gcc 2.95.3, gcc 4.0.1, icc 8.1, and msvc 7.1.
323 //
324 // WARNING: if Dest or Source is a non-POD type, the result of the memcpy
325 // is likely to surprise you.
326
327 template <class Dest, class Source>
328 inline Dest bit_cast(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   typedef char VerifySizesAreEqual [sizeof(Dest) == sizeof(Source) ? 1 : -1];
332
333   Dest dest;
334   memcpy(&dest, &source, sizeof(dest));
335   return dest;
336 }
337
338 // Used to explicitly mark the return value of a function as unused. If you are
339 // really sure you don't want to do anything with the return value of a function
340 // that has been marked WARN_UNUSED_RESULT, wrap it with this. Example:
341 //
342 //   scoped_ptr<MyType> my_var = ...;
343 //   if (TakeOwnership(my_var.get()) == SUCCESS)
344 //     ignore_result(my_var.release());
345 //
346 template<typename T>
347 inline void ignore_result(const T& ignored) {
348 }
349
350 // The following enum should be used only as a constructor argument to indicate
351 // that the variable has static storage class, and that the constructor should
352 // do nothing to its state.  It indicates to the reader that it is legal to
353 // declare a static instance of the class, provided the constructor is given
354 // the base::LINKER_INITIALIZED argument.  Normally, it is unsafe to declare a
355 // static variable that has a constructor or a destructor because invocation
356 // order is undefined.  However, IF the type can be initialized by filling with
357 // zeroes (which the loader does for static variables), AND the destructor also
358 // does nothing to the storage, AND there are no virtual methods, then a
359 // constructor declared as
360 //       explicit MyClass(base::LinkerInitialized x) {}
361 // and invoked as
362 //       static MyClass my_variable_name(base::LINKER_INITIALIZED);
363 namespace base {
364 enum LinkerInitialized { LINKER_INITIALIZED };
365 }  // base
366
367 #endif  // BASE_BASICTYPES_H_