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