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