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