Codemod: use #include angle brackets in folly and thrift
[folly.git] / folly / Traits.h
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 // @author: Andrei Alexandrescu
18
19 #ifndef FOLLY_BASE_TRAITS_H_
20 #define FOLLY_BASE_TRAITS_H_
21
22 #include <memory>
23 #include <limits>
24 #include <type_traits>
25 #include <functional>
26
27 #include <folly/Portability.h>
28
29 // libc++ doesn't provide this header, nor does msvc
30 #ifdef FOLLY_HAVE_BITS_CXXCONFIG_H
31 // This file appears in two locations: inside fbcode and in the
32 // libstdc++ source code (when embedding fbstring as std::string).
33 // To aid in this schizophrenic use, two macros are defined in
34 // c++config.h:
35 //   _LIBSTDCXX_FBSTRING - Set inside libstdc++.  This is useful to
36 //      gate use inside fbcode v. libstdc++
37 #include <bits/c++config.h>
38 #endif
39
40 #include <boost/type_traits.hpp>
41 #include <boost/mpl/and.hpp>
42 #include <boost/mpl/has_xxx.hpp>
43 #include <boost/mpl/not.hpp>
44
45 namespace folly {
46
47 /**
48  * IsRelocatable<T>::value describes the ability of moving around
49  * memory a value of type T by using memcpy (as opposed to the
50  * conservative approach of calling the copy constructor and then
51  * destroying the old temporary. Essentially for a relocatable type,
52  * the following two sequences of code should be semantically
53  * equivalent:
54  *
55  * void move1(T * from, T * to) {
56  *   new(to) T(from);
57  *   (*from).~T();
58  * }
59  *
60  * void move2(T * from, T * to) {
61  *   memcpy(to, from, sizeof(T));
62  * }
63  *
64  * Most C++ types are relocatable; the ones that aren't would include
65  * internal pointers or (very rarely) would need to update remote
66  * pointers to pointers tracking them. All C++ primitive types and
67  * type constructors are relocatable.
68  *
69  * This property can be used in a variety of optimizations. Currently
70  * fbvector uses this property intensively.
71  *
72  * The default conservatively assumes the type is not
73  * relocatable. Several specializations are defined for known
74  * types. You may want to add your own specializations. Do so in
75  * namespace folly and make sure you keep the specialization of
76  * IsRelocatable<SomeStruct> in the same header as SomeStruct.
77  *
78  * You may also declare a type to be relocatable by including
79  *    `typedef std::true_type IsRelocatable;`
80  * in the class header.
81  *
82  * It may be unset in a base class by overriding the typedef to false_type.
83  */
84 /*
85  * IsTriviallyCopyable describes the value semantics property. C++11 contains
86  * the type trait is_trivially_copyable; however, it is not yet implemented
87  * in gcc (as of 4.7.1), and the user may wish to specify otherwise.
88  */
89 /*
90  * IsZeroInitializable describes the property that default construction is the
91  * same as memset(dst, 0, sizeof(T)).
92  */
93
94 namespace traits_detail {
95
96 #define FOLLY_HAS_TRUE_XXX(name)                          \
97   BOOST_MPL_HAS_XXX_TRAIT_DEF(name);                      \
98   template <class T> struct name ## _is_true              \
99     : std::is_same<typename T::name, std::true_type> {};  \
100   template <class T> struct has_true_ ## name             \
101     : std::conditional<                                   \
102         has_ ## name <T>::value,                          \
103         name ## _is_true<T>,                              \
104         std::false_type                                   \
105       >:: type {};
106
107 FOLLY_HAS_TRUE_XXX(IsRelocatable)
108 FOLLY_HAS_TRUE_XXX(IsZeroInitializable)
109 FOLLY_HAS_TRUE_XXX(IsTriviallyCopyable)
110
111 #undef FOLLY_HAS_TRUE_XXX
112 }
113
114 template <class T> struct IsTriviallyCopyable
115   : std::integral_constant<bool,
116       !std::is_class<T>::value ||
117       // TODO: add alternate clause is_trivially_copyable, when available
118       traits_detail::has_true_IsTriviallyCopyable<T>::value
119     > {};
120
121 template <class T> struct IsRelocatable
122   : std::integral_constant<bool,
123       !std::is_class<T>::value ||
124       // TODO add this line (and some tests for it) when we upgrade to gcc 4.7
125       //std::is_trivially_move_constructible<T>::value ||
126       IsTriviallyCopyable<T>::value ||
127       traits_detail::has_true_IsRelocatable<T>::value
128     > {};
129
130 template <class T> struct IsZeroInitializable
131   : std::integral_constant<bool,
132       !std::is_class<T>::value ||
133       traits_detail::has_true_IsZeroInitializable<T>::value
134     > {};
135
136 } // namespace folly
137
138 /**
139  * Use this macro ONLY inside namespace folly. When using it with a
140  * regular type, use it like this:
141  *
142  * // Make sure you're at namespace ::folly scope
143  * template<> FOLLY_ASSUME_RELOCATABLE(MyType)
144  *
145  * When using it with a template type, use it like this:
146  *
147  * // Make sure you're at namespace ::folly scope
148  * template<class T1, class T2>
149  * FOLLY_ASSUME_RELOCATABLE(MyType<T1, T2>)
150  */
151 #define FOLLY_ASSUME_RELOCATABLE(...) \
152   struct IsRelocatable<  __VA_ARGS__ > : std::true_type {};
153
154 /**
155  * Use this macro ONLY inside namespace boost. When using it with a
156  * regular type, use it like this:
157  *
158  * // Make sure you're at namespace ::boost scope
159  * template<> FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(MyType)
160  *
161  * When using it with a template type, use it like this:
162  *
163  * // Make sure you're at namespace ::boost scope
164  * template<class T1, class T2>
165  * FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(MyType<T1, T2>)
166  */
167 #define FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(...) \
168   struct has_nothrow_constructor<  __VA_ARGS__ > : ::boost::true_type {};
169
170 /**
171  * The FOLLY_ASSUME_FBVECTOR_COMPATIBLE* macros below encode two
172  * assumptions: first, that the type is relocatable per IsRelocatable
173  * above, and that it has a nothrow constructor. Most types can be
174  * assumed to satisfy both conditions, but it is the responsibility of
175  * the user to state that assumption. User-defined classes will not
176  * work with fbvector (see FBVector.h) unless they state this
177  * combination of properties.
178  *
179  * Use FOLLY_ASSUME_FBVECTOR_COMPATIBLE with regular types like this:
180  *
181  * FOLLY_ASSUME_FBVECTOR_COMPATIBLE(MyType)
182  *
183  * The versions FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1, _2, _3, and _4
184  * allow using the macro for describing templatized classes with 1, 2,
185  * 3, and 4 template parameters respectively. For template classes
186  * just use the macro with the appropriate number and pass the name of
187  * the template to it. Example:
188  *
189  * template <class T1, class T2> class MyType { ... };
190  * ...
191  * // Make sure you're at global scope
192  * FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(MyType)
193  */
194
195 // Use this macro ONLY at global level (no namespace)
196 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE(...)                           \
197   namespace folly { template<> FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__) }   \
198   namespace boost { \
199   template<> FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(__VA_ARGS__) }
200 // Use this macro ONLY at global level (no namespace)
201 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(...)                         \
202   namespace folly {                                                     \
203   template <class T1> FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__<T1>) }       \
204     namespace boost {                                                   \
205     template <class T1> FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(__VA_ARGS__<T1>) }
206 // Use this macro ONLY at global level (no namespace)
207 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(...)                 \
208   namespace folly {                                             \
209   template <class T1, class T2>                                 \
210   FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__<T1, T2>) }               \
211     namespace boost {                                           \
212     template <class T1, class T2>                               \
213     FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(__VA_ARGS__<T1, T2>) }
214 // Use this macro ONLY at global level (no namespace)
215 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE_3(...)                         \
216   namespace folly {                                                     \
217   template <class T1, class T2, class T3>                               \
218   FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__<T1, T2, T3>) }                   \
219     namespace boost {                                                   \
220     template <class T1, class T2, class T3>                             \
221     FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(__VA_ARGS__<T1, T2, T3>) }
222 // Use this macro ONLY at global level (no namespace)
223 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE_4(...)                         \
224   namespace folly {                                                     \
225   template <class T1, class T2, class T3, class T4>                     \
226   FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__<T1, T2, T3, T4>) }               \
227     namespace boost {                                                   \
228     template <class T1, class T2, class T3, class T4>                   \
229     FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(__VA_ARGS__<T1, T2, T3, T4>) }
230
231 /**
232  * Instantiate FOLLY_ASSUME_FBVECTOR_COMPATIBLE for a few types. It is
233  * safe to assume that pair is compatible if both of its components
234  * are. Furthermore, all STL containers can be assumed to comply,
235  * although that is not guaranteed by the standard.
236  */
237
238 FOLLY_NAMESPACE_STD_BEGIN
239
240 template <class T, class U>
241   struct pair;
242 #ifndef _GLIBCXX_USE_FB
243 template <class T, class R, class A>
244   class basic_string;
245 #else
246 template <class T, class R, class A, class S>
247   class basic_string;
248 #endif
249 template <class T, class A>
250   class vector;
251 template <class T, class A>
252   class deque;
253 template <class T, class A>
254   class list;
255 template <class T, class C, class A>
256   class set;
257 template <class K, class V, class C, class A>
258   class map;
259 template <class T>
260   class shared_ptr;
261
262 FOLLY_NAMESPACE_STD_END
263
264 namespace boost {
265
266 template <class T> class shared_ptr;
267
268 template <class T, class U>
269 struct has_nothrow_constructor< std::pair<T, U> >
270     : ::boost::mpl::and_< has_nothrow_constructor<T>,
271                           has_nothrow_constructor<U> > {};
272
273 } // namespace boost
274
275 namespace folly {
276
277 // STL commonly-used types
278 template <class T, class U>
279 struct IsRelocatable<  std::pair<T, U> >
280     : ::boost::mpl::and_< IsRelocatable<T>, IsRelocatable<U> > {};
281
282 // Is T one of T1, T2, ..., Tn?
283 template <class T, class... Ts>
284 struct IsOneOf {
285   enum { value = false };
286 };
287
288 template <class T, class T1, class... Ts>
289 struct IsOneOf<T, T1, Ts...> {
290   enum { value = std::is_same<T, T1>::value || IsOneOf<T, Ts...>::value };
291 };
292
293 /**
294  * A traits class to check for incomplete types.
295  *
296  * Example:
297  *
298  *  struct FullyDeclared {}; // complete type
299  *  struct ForwardDeclared; // incomplete type
300  *
301  *  is_complete<int>::value // evaluates to true
302  *  is_complete<FullyDeclared>::value // evaluates to true
303  *  is_complete<ForwardDeclared>::value // evaluates to false
304  *
305  *  struct ForwardDeclared {}; // declared, at last
306  *
307  *  is_complete<ForwardDeclared>::value // now it evaluates to true
308  *
309  * @author: Marcelo Juchem <marcelo@fb.com>
310  */
311 template <typename T>
312 class is_complete {
313   template <unsigned long long> struct sfinae {};
314   template <typename U>
315   constexpr static bool test(sfinae<sizeof(U)>*) { return true; }
316   template <typename> constexpr static bool test(...) { return false; }
317 public:
318   constexpr static bool value = test<T>(nullptr);
319 };
320
321 /*
322  * Complementary type traits for integral comparisons.
323  *
324  * For instance, `if(x < 0)` yields an error in clang for unsigned types
325  *  when -Werror is used due to -Wtautological-compare
326  *
327  *
328  * @author: Marcelo Juchem <marcelo@fb.com>
329  */
330
331 namespace detail {
332
333 template <typename T, bool>
334 struct is_negative_impl {
335   constexpr static bool check(T x) { return x < 0; }
336 };
337
338 template <typename T>
339 struct is_negative_impl<T, false> {
340   constexpr static bool check(T x) { return false; }
341 };
342
343 template <typename RHS, RHS rhs, typename LHS>
344 bool less_than_impl(
345   typename std::enable_if<
346     (rhs <= std::numeric_limits<LHS>::max()
347       && rhs > std::numeric_limits<LHS>::min()),
348     LHS
349   >::type const lhs
350 ) {
351   return lhs < rhs;
352 }
353
354 template <typename RHS, RHS rhs, typename LHS>
355 bool less_than_impl(
356   typename std::enable_if<
357     (rhs > std::numeric_limits<LHS>::max()),
358     LHS
359   >::type const
360 ) {
361   return true;
362 }
363
364 template <typename RHS, RHS rhs, typename LHS>
365 bool less_than_impl(
366   typename std::enable_if<
367     (rhs <= std::numeric_limits<LHS>::min()),
368     LHS
369   >::type const
370 ) {
371   return false;
372 }
373
374 template <typename RHS, RHS rhs, typename LHS>
375 bool greater_than_impl(
376   typename std::enable_if<
377     (rhs <= std::numeric_limits<LHS>::max()
378       && rhs >= std::numeric_limits<LHS>::min()),
379     LHS
380   >::type const lhs
381 ) {
382   return lhs > rhs;
383 }
384
385 template <typename RHS, RHS rhs, typename LHS>
386 bool greater_than_impl(
387   typename std::enable_if<
388     (rhs > std::numeric_limits<LHS>::max()),
389     LHS
390   >::type const
391 ) {
392   return false;
393 }
394
395 template <typename RHS, RHS rhs, typename LHS>
396 bool greater_than_impl(
397   typename std::enable_if<
398     (rhs < std::numeric_limits<LHS>::min()),
399     LHS
400   >::type const
401 ) {
402   return true;
403 }
404
405 } // namespace detail {
406
407 // same as `x < 0`
408 template <typename T>
409 constexpr bool is_negative(T x) {
410   return folly::detail::is_negative_impl<T, std::is_signed<T>::value>::check(x);
411 }
412
413 // same as `x <= 0`
414 template <typename T>
415 constexpr bool is_non_positive(T x) { return !x || folly::is_negative(x); }
416
417 // same as `x > 0`
418 template <typename T>
419 constexpr bool is_positive(T x) { return !is_non_positive(x); }
420
421 // same as `x >= 0`
422 template <typename T>
423 constexpr bool is_non_negative(T x) {
424   return !x || is_positive(x);
425 }
426
427 template <typename RHS, RHS rhs, typename LHS>
428 bool less_than(LHS const lhs) {
429   return detail::less_than_impl<
430     RHS, rhs, typename std::remove_reference<LHS>::type
431   >(lhs);
432 }
433
434 template <typename RHS, RHS rhs, typename LHS>
435 bool greater_than(LHS const lhs) {
436   return detail::greater_than_impl<
437     RHS, rhs, typename std::remove_reference<LHS>::type
438   >(lhs);
439 }
440
441 } // namespace folly
442
443 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_3(std::basic_string);
444 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::vector);
445 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::list);
446 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::deque);
447 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::unique_ptr);
448 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(std::shared_ptr);
449 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(std::function);
450
451 // Boost
452 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(boost::shared_ptr);
453
454 #define FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, cv_qual) \
455   template <typename TTheClass_, typename RTheReturn_, typename... TTheArgs_> \
456   class classname<TTheClass_, RTheReturn_(TTheArgs_...) cv_qual> { \
457     template < \
458       typename UTheClass_, RTheReturn_ (UTheClass_::*)(TTheArgs_...) cv_qual \
459     > struct sfinae {}; \
460     template <typename UTheClass_> \
461     constexpr static bool test(sfinae<UTheClass_, &UTheClass_::func_name>*) \
462     { return true; } \
463     template <typename> \
464     constexpr static bool test(...) { return false; } \
465   public: \
466     constexpr static bool value = test<TTheClass_>(nullptr); \
467   }
468
469 /*
470  * The FOLLY_CREATE_HAS_MEMBER_FN_TRAITS is used to create traits
471  * classes that check for the existence of a member function with
472  * a given name and signature. It currently does not support
473  * checking for inherited members.
474  *
475  * Such classes receive two template parameters: the class to be checked
476  * and the signature of the member function. A static boolean field
477  * named `value` (which is also constexpr) tells whether such member
478  * function exists.
479  *
480  * Each traits class created is bound only to the member name, not to
481  * its signature nor to the type of the class containing it.
482  *
483  * Say you need to know if a given class has a member function named
484  * `test` with the following signature:
485  *
486  *    int test() const;
487  *
488  * You'd need this macro to create a traits class to check for a member
489  * named `test`, and then use this traits class to check for the signature:
490  *
491  * namespace {
492  *
493  * FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(has_test_traits, test);
494  *
495  * } // unnamed-namespace
496  *
497  * void some_func() {
498  *   cout << "Does class Foo have a member int test() const? "
499  *     << boolalpha << has_test_traits<Foo, int() const>::value;
500  * }
501  *
502  * You can use the same traits class to test for a completely different
503  * signature, on a completely different class, as long as the member name
504  * is the same:
505  *
506  * void some_func() {
507  *   cout << "Does class Foo have a member int test()? "
508  *     << boolalpha << has_test_traits<Foo, int()>::value;
509  *   cout << "Does class Foo have a member int test() const? "
510  *     << boolalpha << has_test_traits<Foo, int() const>::value;
511  *   cout << "Does class Bar have a member double test(const string&, long)? "
512  *     << boolalpha << has_test_traits<Bar, double(const string&, long)>::value;
513  * }
514  *
515  * @author: Marcelo Juchem <marcelo@fb.com>
516  */
517 #define FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(classname, func_name) \
518   template <typename, typename> class classname; \
519   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, ); \
520   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, const); \
521   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, volatile); \
522   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, volatile const)
523
524 #endif //FOLLY_BASE_TRAITS_H_