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