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 BUTIL_MACROS_H_ |
11 | #define BUTIL_MACROS_H_ |
12 | |
13 | #include <stddef.h> // For size_t. |
14 | #include <string.h> // For memcpy. |
15 | |
16 | #include "butil/compiler_specific.h" // For ALLOW_UNUSED. |
17 | |
18 | // There must be many copy-paste versions of these macros which are same |
19 | // things, undefine them to avoid conflict. |
20 | #undef DISALLOW_COPY |
21 | #undef DISALLOW_ASSIGN |
22 | #undef DISALLOW_COPY_AND_ASSIGN |
23 | #undef DISALLOW_EVIL_CONSTRUCTORS |
24 | #undef DISALLOW_IMPLICIT_CONSTRUCTORS |
25 | |
26 | #if !defined(BUTIL_CXX11_ENABLED) |
27 | #define BUTIL_DELETE_FUNCTION(decl) decl |
28 | #else |
29 | #define BUTIL_DELETE_FUNCTION(decl) decl = delete |
30 | #endif |
31 | |
32 | // Put this in the private: declarations for a class to be uncopyable. |
33 | #define DISALLOW_COPY(TypeName) \ |
34 | BUTIL_DELETE_FUNCTION(TypeName(const TypeName&)) |
35 | |
36 | // Put this in the private: declarations for a class to be unassignable. |
37 | #define DISALLOW_ASSIGN(TypeName) \ |
38 | BUTIL_DELETE_FUNCTION(void operator=(const TypeName&)) |
39 | |
40 | // A macro to disallow the copy constructor and operator= functions |
41 | // This should be used in the private: declarations for a class |
42 | #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ |
43 | BUTIL_DELETE_FUNCTION(TypeName(const TypeName&)); \ |
44 | BUTIL_DELETE_FUNCTION(void operator=(const TypeName&)) |
45 | |
46 | // An older, deprecated, politically incorrect name for the above. |
47 | // NOTE: The usage of this macro was banned from our code base, but some |
48 | // third_party libraries are yet using it. |
49 | // TODO(tfarina): Figure out how to fix the usage of this macro in the |
50 | // third_party libraries and get rid of it. |
51 | #define DISALLOW_EVIL_CONSTRUCTORS(TypeName) DISALLOW_COPY_AND_ASSIGN(TypeName) |
52 | |
53 | // A macro to disallow all the implicit constructors, namely the |
54 | // default constructor, copy constructor and operator= functions. |
55 | // |
56 | // This should be used in the private: declarations for a class |
57 | // that wants to prevent anyone from instantiating it. This is |
58 | // especially useful for classes containing only static methods. |
59 | #define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \ |
60 | BUTIL_DELETE_FUNCTION(TypeName()); \ |
61 | DISALLOW_COPY_AND_ASSIGN(TypeName) |
62 | |
63 | // Concatenate numbers in c/c++ macros. |
64 | #ifndef BAIDU_CONCAT |
65 | # define BAIDU_CONCAT(a, b) BAIDU_CONCAT_HELPER(a, b) |
66 | # define BAIDU_CONCAT_HELPER(a, b) a##b |
67 | #endif |
68 | |
69 | #undef arraysize |
70 | // The arraysize(arr) macro returns the # of elements in an array arr. |
71 | // The expression is a compile-time constant, and therefore can be |
72 | // used in defining new arrays, for example. If you use arraysize on |
73 | // a pointer by mistake, you will get a compile-time error. |
74 | // |
75 | // One caveat is that arraysize() doesn't accept any array of an |
76 | // anonymous type or a type defined inside a function. In these rare |
77 | // cases, you have to use the unsafe ARRAYSIZE_UNSAFE() macro below. This is |
78 | // due to a limitation in C++'s template system. The limitation might |
79 | // eventually be removed, but it hasn't happened yet. |
80 | |
81 | // This template function declaration is used in defining arraysize. |
82 | // Note that the function doesn't need an implementation, as we only |
83 | // use its type. |
84 | namespace butil { |
85 | template <typename T, size_t N> |
86 | char (&ArraySizeHelper(T (&array)[N]))[N]; |
87 | } |
88 | |
89 | // That gcc wants both of these prototypes seems mysterious. VC, for |
90 | // its part, can't decide which to use (another mystery). Matching of |
91 | // template overloads: the final frontier. |
92 | #ifndef _MSC_VER |
93 | namespace butil { |
94 | template <typename T, size_t N> |
95 | char (&ArraySizeHelper(const T (&array)[N]))[N]; |
96 | } |
97 | #endif |
98 | |
99 | #define arraysize(array) (sizeof(::butil::ArraySizeHelper(array))) |
100 | |
101 | // gejun: Following macro was used in other modules. |
102 | #undef ARRAY_SIZE |
103 | #define ARRAY_SIZE(array) arraysize(array) |
104 | |
105 | // ARRAYSIZE_UNSAFE performs essentially the same calculation as arraysize, |
106 | // but can be used on anonymous types or types defined inside |
107 | // functions. It's less safe than arraysize as it accepts some |
108 | // (although not all) pointers. Therefore, you should use arraysize |
109 | // whenever possible. |
110 | // |
111 | // The expression ARRAYSIZE_UNSAFE(a) is a compile-time constant of type |
112 | // size_t. |
113 | // |
114 | // ARRAYSIZE_UNSAFE catches a few type errors. If you see a compiler error |
115 | // |
116 | // "warning: division by zero in ..." |
117 | // |
118 | // when using ARRAYSIZE_UNSAFE, you are (wrongfully) giving it a pointer. |
119 | // You should only use ARRAYSIZE_UNSAFE on statically allocated arrays. |
120 | // |
121 | // The following comments are on the implementation details, and can |
122 | // be ignored by the users. |
123 | // |
124 | // ARRAYSIZE_UNSAFE(arr) works by inspecting sizeof(arr) (the # of bytes in |
125 | // the array) and sizeof(*(arr)) (the # of bytes in one array |
126 | // element). If the former is divisible by the latter, perhaps arr is |
127 | // indeed an array, in which case the division result is the # of |
128 | // elements in the array. Otherwise, arr cannot possibly be an array, |
129 | // and we generate a compiler error to prevent the code from |
130 | // compiling. |
131 | // |
132 | // Since the size of bool is implementation-defined, we need to cast |
133 | // !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final |
134 | // result has type size_t. |
135 | // |
136 | // This macro is not perfect as it wrongfully accepts certain |
137 | // pointers, namely where the pointer size is divisible by the pointee |
138 | // size. Since all our code has to go through a 32-bit compiler, |
139 | // where a pointer is 4 bytes, this means all pointers to a type whose |
140 | // size is 3 or greater than 4 will be (righteously) rejected. |
141 | #undef ARRAYSIZE_UNSAFE |
142 | #define ARRAYSIZE_UNSAFE(a) \ |
143 | ((sizeof(a) / sizeof(*(a))) / \ |
144 | static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))) |
145 | |
146 | // Use implicit_cast as a safe version of static_cast or const_cast |
147 | // for upcasting in the type hierarchy (i.e. casting a pointer to Foo |
148 | // to a pointer to SuperclassOfFoo or casting a pointer to Foo to |
149 | // a const pointer to Foo). |
150 | // When you use implicit_cast, the compiler checks that the cast is safe. |
151 | // Such explicit implicit_casts are necessary in surprisingly many |
152 | // situations where C++ demands an exact type match instead of an |
153 | // argument type convertible to a target type. |
154 | // |
155 | // The From type can be inferred, so the preferred syntax for using |
156 | // implicit_cast is the same as for static_cast etc.: |
157 | // |
158 | // implicit_cast<ToType>(expr) |
159 | // |
160 | // implicit_cast would have been part of the C++ standard library, |
161 | // but the proposal was submitted too late. It will probably make |
162 | // its way into the language in the future. |
163 | namespace butil { |
164 | template<typename To, typename From> |
165 | inline To implicit_cast(From const &f) { |
166 | return f; |
167 | } |
168 | } |
169 | |
170 | #if defined(BUTIL_CXX11_ENABLED) |
171 | |
172 | // C++11 supports compile-time assertion directly |
173 | #define BAIDU_CASSERT(expr, msg) static_assert(expr, #msg) |
174 | |
175 | #else |
176 | |
177 | // Assert constant boolean expressions at compile-time |
178 | // Params: |
179 | // expr the constant expression to be checked |
180 | // msg an error infomation conforming name conventions of C/C++ |
181 | // variables(alphabets/numbers/underscores, no blanks). For |
182 | // example "cannot_accept_a_number_bigger_than_128" is valid |
183 | // while "this number is out-of-range" is illegal. |
184 | // |
185 | // when an asssertion like "BAIDU_CASSERT(false, you_should_not_be_here)" |
186 | // breaks, a compilation error is printed: |
187 | // |
188 | // foo.cpp:401: error: enumerator value for `you_should_not_be_here___19' not |
189 | // integer constant |
190 | // |
191 | // You can call BAIDU_CASSERT at global scope, inside a class or a function |
192 | // |
193 | // BAIDU_CASSERT(false, you_should_not_be_here); |
194 | // int main () { ... } |
195 | // |
196 | // struct Foo { |
197 | // BAIDU_CASSERT(1 == 0, Never_equals); |
198 | // }; |
199 | // |
200 | // int bar(...) |
201 | // { |
202 | // BAIDU_CASSERT (value < 10, invalid_value); |
203 | // } |
204 | // |
205 | namespace butil { |
206 | template <bool> struct CAssert { static const int x = 1; }; |
207 | template <> struct CAssert<false> { static const char * x; }; |
208 | } |
209 | |
210 | #define BAIDU_CASSERT(expr, msg) \ |
211 | enum { BAIDU_CONCAT(BAIDU_CONCAT(LINE_, __LINE__), __##msg) \ |
212 | = ::butil::CAssert<!!(expr)>::x }; |
213 | |
214 | #endif // BUTIL_CXX11_ENABLED |
215 | |
216 | // The impl. of chrome does not work for offsetof(Object, private_filed) |
217 | #undef COMPILE_ASSERT |
218 | #define COMPILE_ASSERT(expr, msg) BAIDU_CASSERT(expr, msg) |
219 | |
220 | // bit_cast<Dest,Source> is a template function that implements the |
221 | // equivalent of "*reinterpret_cast<Dest*>(&source)". We need this in |
222 | // very low-level functions like the protobuf library and fast math |
223 | // support. |
224 | // |
225 | // float f = 3.14159265358979; |
226 | // int i = bit_cast<int32_t>(f); |
227 | // // i = 0x40490fdb |
228 | // |
229 | // The classical address-casting method is: |
230 | // |
231 | // // WRONG |
232 | // float f = 3.14159265358979; // WRONG |
233 | // int i = * reinterpret_cast<int*>(&f); // WRONG |
234 | // |
235 | // The address-casting method actually produces undefined behavior |
236 | // according to ISO C++ specification section 3.10 -15 -. Roughly, this |
237 | // section says: if an object in memory has one type, and a program |
238 | // accesses it with a different type, then the result is undefined |
239 | // behavior for most values of "different type". |
240 | // |
241 | // This is true for any cast syntax, either *(int*)&f or |
242 | // *reinterpret_cast<int*>(&f). And it is particularly true for |
243 | // conversions between integral lvalues and floating-point lvalues. |
244 | // |
245 | // The purpose of 3.10 -15- is to allow optimizing compilers to assume |
246 | // that expressions with different types refer to different memory. gcc |
247 | // 4.0.1 has an optimizer that takes advantage of this. So a |
248 | // non-conforming program quietly produces wildly incorrect output. |
249 | // |
250 | // The problem is not the use of reinterpret_cast. The problem is type |
251 | // punning: holding an object in memory of one type and reading its bits |
252 | // back using a different type. |
253 | // |
254 | // The C++ standard is more subtle and complex than this, but that |
255 | // is the basic idea. |
256 | // |
257 | // Anyways ... |
258 | // |
259 | // bit_cast<> calls memcpy() which is blessed by the standard, |
260 | // especially by the example in section 3.9 . Also, of course, |
261 | // bit_cast<> wraps up the nasty logic in one place. |
262 | // |
263 | // Fortunately memcpy() is very fast. In optimized mode, with a |
264 | // constant size, gcc 2.95.3, gcc 4.0.1, and msvc 7.1 produce inline |
265 | // code with the minimal amount of data movement. On a 32-bit system, |
266 | // memcpy(d,s,4) compiles to one load and one store, and memcpy(d,s,8) |
267 | // compiles to two loads and two stores. |
268 | // |
269 | // I tested this code with gcc 2.95.3, gcc 4.0.1, icc 8.1, and msvc 7.1. |
270 | // |
271 | // WARNING: if Dest or Source is a non-POD type, the result of the memcpy |
272 | // is likely to surprise you. |
273 | namespace butil { |
274 | template <class Dest, class Source> |
275 | inline Dest bit_cast(const Source& source) { |
276 | COMPILE_ASSERT(sizeof(Dest) == sizeof(Source), VerifySizesAreEqual); |
277 | |
278 | Dest dest; |
279 | memcpy(&dest, &source, sizeof(dest)); |
280 | return dest; |
281 | } |
282 | } // namespace butil |
283 | |
284 | // Used to explicitly mark the return value of a function as unused. If you are |
285 | // really sure you don't want to do anything with the return value of a function |
286 | // that has been marked WARN_UNUSED_RESULT, wrap it with this. Example: |
287 | // |
288 | // scoped_ptr<MyType> my_var = ...; |
289 | // if (TakeOwnership(my_var.get()) == SUCCESS) |
290 | // ignore_result(my_var.release()); |
291 | // |
292 | namespace butil { |
293 | template<typename T> |
294 | inline void ignore_result(const T&) { |
295 | } |
296 | } // namespace butil |
297 | |
298 | // The following enum should be used only as a constructor argument to indicate |
299 | // that the variable has static storage class, and that the constructor should |
300 | // do nothing to its state. It indicates to the reader that it is legal to |
301 | // declare a static instance of the class, provided the constructor is given |
302 | // the butil::LINKER_INITIALIZED argument. Normally, it is unsafe to declare a |
303 | // static variable that has a constructor or a destructor because invocation |
304 | // order is undefined. However, IF the type can be initialized by filling with |
305 | // zeroes (which the loader does for static variables), AND the destructor also |
306 | // does nothing to the storage, AND there are no virtual methods, then a |
307 | // constructor declared as |
308 | // explicit MyClass(butil::LinkerInitialized x) {} |
309 | // and invoked as |
310 | // static MyClass my_variable_name(butil::LINKER_INITIALIZED); |
311 | namespace butil { |
312 | enum LinkerInitialized { LINKER_INITIALIZED }; |
313 | |
314 | // Use these to declare and define a static local variable (static T;) so that |
315 | // it is leaked so that its destructors are not called at exit. If you need |
316 | // thread-safe initialization, use butil/lazy_instance.h instead. |
317 | #undef CR_DEFINE_STATIC_LOCAL |
318 | #define CR_DEFINE_STATIC_LOCAL(type, name, arguments) \ |
319 | static type& name = *new type arguments |
320 | |
321 | } // namespace butil |
322 | |
323 | // Convert symbol to string |
324 | #ifndef BAIDU_SYMBOLSTR |
325 | # define BAIDU_SYMBOLSTR(a) BAIDU_SYMBOLSTR_HELPER(a) |
326 | # define BAIDU_SYMBOLSTR_HELPER(a) #a |
327 | #endif |
328 | |
329 | #ifndef BAIDU_TYPEOF |
330 | # if defined(BUTIL_CXX11_ENABLED) |
331 | # define BAIDU_TYPEOF decltype |
332 | # else |
333 | # ifdef _MSC_VER |
334 | # include <boost/typeof/typeof.hpp> |
335 | # define BAIDU_TYPEOF BOOST_TYPEOF |
336 | # else |
337 | # define BAIDU_TYPEOF typeof |
338 | # endif |
339 | # endif // BUTIL_CXX11_ENABLED |
340 | #endif // BAIDU_TYPEOF |
341 | |
342 | // ptr: the pointer to the member. |
343 | // type: the type of the container struct this is embedded in. |
344 | // member: the name of the member within the struct. |
345 | #ifndef container_of |
346 | # define container_of(ptr, type, member) ({ \ |
347 | const BAIDU_TYPEOF( ((type *)0)->member ) *__mptr = (ptr); \ |
348 | (type *)( (char *)__mptr - offsetof(type,member) );}) |
349 | #endif |
350 | |
351 | // DEFINE_SMALL_ARRAY(MyType, my_array, size, 64); |
352 | // my_array is typed `MyType*' and as long as `size'. If `size' is not |
353 | // greater than 64, the array is allocated on stack. |
354 | // |
355 | // NOTE: NEVER use ARRAY_SIZE(my_array) which is always 1. |
356 | |
357 | #if defined(__cplusplus) |
358 | namespace butil { |
359 | namespace internal { |
360 | template <typename T> struct ArrayDeleter { |
361 | ArrayDeleter() : arr(0) {} |
362 | ~ArrayDeleter() { delete[] arr; } |
363 | T* arr; |
364 | }; |
365 | }} |
366 | |
367 | // Many versions of clang does not support variable-length array with non-pod |
368 | // types, have to implement the macro differently. |
369 | #if !defined(__clang__) |
370 | # define DEFINE_SMALL_ARRAY(Tp, name, size, maxsize) \ |
371 | Tp* name = 0; \ |
372 | const unsigned name##_size = (size); \ |
373 | const unsigned name##_stack_array_size = (name##_size <= (maxsize) ? name##_size : 0); \ |
374 | Tp name##_stack_array[name##_stack_array_size]; \ |
375 | ::butil::internal::ArrayDeleter<Tp> name##_array_deleter; \ |
376 | if (name##_stack_array_size) { \ |
377 | name = name##_stack_array; \ |
378 | } else { \ |
379 | name = new (::std::nothrow) Tp[name##_size]; \ |
380 | name##_array_deleter.arr = name; \ |
381 | } |
382 | #else |
383 | // This implementation works for GCC as well, however it needs extra 16 bytes |
384 | // for ArrayCtorDtor. |
385 | namespace butil { |
386 | namespace internal { |
387 | template <typename T> struct ArrayCtorDtor { |
388 | ArrayCtorDtor(void* arr, unsigned size) : _arr((T*)arr), _size(size) { |
389 | for (unsigned i = 0; i < size; ++i) { new (_arr + i) T; } |
390 | } |
391 | ~ArrayCtorDtor() { |
392 | for (unsigned i = 0; i < _size; ++i) { _arr[i].~T(); } |
393 | } |
394 | private: |
395 | T* _arr; |
396 | unsigned _size; |
397 | }; |
398 | }} |
399 | # define DEFINE_SMALL_ARRAY(Tp, name, size, maxsize) \ |
400 | Tp* name = 0; \ |
401 | const unsigned name##_size = (size); \ |
402 | const unsigned name##_stack_array_size = (name##_size <= (maxsize) ? name##_size : 0); \ |
403 | char name##_stack_array[sizeof(Tp) * name##_stack_array_size]; \ |
404 | ::butil::internal::ArrayDeleter<char> name##_array_deleter; \ |
405 | if (name##_stack_array_size) { \ |
406 | name = (Tp*)name##_stack_array; \ |
407 | } else { \ |
408 | name = (Tp*)new (::std::nothrow) char[sizeof(Tp) * name##_size];\ |
409 | name##_array_deleter.arr = (char*)name; \ |
410 | } \ |
411 | const ::butil::internal::ArrayCtorDtor<Tp> name##_array_ctor_dtor(name, name##_size); |
412 | #endif // !defined(__clang__) |
413 | #endif // defined(__cplusplus) |
414 | |
415 | // Put following code somewhere global to run it before main(): |
416 | // |
417 | // BAIDU_GLOBAL_INIT() |
418 | // { |
419 | // ... your code ... |
420 | // } |
421 | // |
422 | // Your can: |
423 | // * Write any code and access global variables. |
424 | // * Use ASSERT_*. |
425 | // * Have multiple BAIDU_GLOBAL_INIT() in one scope. |
426 | // |
427 | // Since the code run in global scope, quit with exit() or similar functions. |
428 | |
429 | #if defined(__cplusplus) |
430 | # define BAIDU_GLOBAL_INIT \ |
431 | namespace { /*anonymous namespace */ \ |
432 | struct BAIDU_CONCAT(BaiduGlobalInit, __LINE__) { \ |
433 | BAIDU_CONCAT(BaiduGlobalInit, __LINE__)() { init(); } \ |
434 | void init(); \ |
435 | } BAIDU_CONCAT(baidu_global_init_dummy_, __LINE__); \ |
436 | } /* anonymous namespace */ \ |
437 | void BAIDU_CONCAT(BaiduGlobalInit, __LINE__)::init |
438 | #else |
439 | # define BAIDU_GLOBAL_INIT \ |
440 | static void __attribute__((constructor)) \ |
441 | BAIDU_CONCAT(baidu_global_init_, __LINE__) |
442 | |
443 | #endif // __cplusplus |
444 | |
445 | #endif // BUTIL_MACROS_H_ |
446 | |