folly copyright 2015 -> copyright 2016
[folly.git] / folly / Traits.h
1 /*
2  * Copyright 2016 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 FOLLY_GLIBCXX_NAMESPACE_CXX11_BEGIN
244 template <class T, class R, class A>
245   class basic_string;
246 FOLLY_GLIBCXX_NAMESPACE_CXX11_END
247 #else
248 template <class T, class R, class A, class S>
249   class basic_string;
250 #endif
251 template <class T, class A>
252   class vector;
253 template <class T, class A>
254   class deque;
255 FOLLY_GLIBCXX_NAMESPACE_CXX11_BEGIN
256 template <class T, class A>
257   class list;
258 FOLLY_GLIBCXX_NAMESPACE_CXX11_END
259 template <class T, class C, class A>
260   class set;
261 template <class K, class V, class C, class A>
262   class map;
263 template <class T>
264   class shared_ptr;
265
266 FOLLY_NAMESPACE_STD_END
267
268 namespace boost {
269
270 template <class T> class shared_ptr;
271
272 template <class T, class U>
273 struct has_nothrow_constructor< std::pair<T, U> >
274     : ::boost::mpl::and_< has_nothrow_constructor<T>,
275                           has_nothrow_constructor<U> > {};
276
277 } // namespace boost
278
279 namespace folly {
280
281 // STL commonly-used types
282 template <class T, class U>
283 struct IsRelocatable<  std::pair<T, U> >
284     : ::boost::mpl::and_< IsRelocatable<T>, IsRelocatable<U> > {};
285
286 // Is T one of T1, T2, ..., Tn?
287 template <class T, class... Ts>
288 struct IsOneOf {
289   enum { value = false };
290 };
291
292 template <class T, class T1, class... Ts>
293 struct IsOneOf<T, T1, Ts...> {
294   enum { value = std::is_same<T, T1>::value || IsOneOf<T, Ts...>::value };
295 };
296
297 /*
298  * Complementary type traits for integral comparisons.
299  *
300  * For instance, `if(x < 0)` yields an error in clang for unsigned types
301  *  when -Werror is used due to -Wtautological-compare
302  *
303  *
304  * @author: Marcelo Juchem <marcelo@fb.com>
305  */
306
307 namespace detail {
308
309 template <typename T, bool>
310 struct is_negative_impl {
311   constexpr static bool check(T x) { return x < 0; }
312 };
313
314 template <typename T>
315 struct is_negative_impl<T, false> {
316   constexpr static bool check(T) { return false; }
317 };
318
319 // folly::to integral specializations can end up generating code
320 // inside what are really static ifs (not executed because of the templated
321 // types) that violate -Wsign-compare so suppress them in order to not prevent
322 // all calling code from using it.
323 #pragma GCC diagnostic push
324 #pragma GCC diagnostic ignored "-Wsign-compare"
325
326 template <typename RHS, RHS rhs, typename LHS>
327 bool less_than_impl(LHS const lhs) {
328   return
329     rhs > std::numeric_limits<LHS>::max() ? true :
330     rhs <= std::numeric_limits<LHS>::min() ? false :
331     lhs < rhs;
332 }
333
334 #pragma GCC diagnostic pop
335
336 template <typename RHS, RHS rhs, typename LHS>
337 bool greater_than_impl(LHS const lhs) {
338   return
339     rhs > std::numeric_limits<LHS>::max() ? false :
340     rhs < std::numeric_limits<LHS>::min() ? true :
341     lhs > rhs;
342 }
343
344 } // namespace detail {
345
346 // same as `x < 0`
347 template <typename T>
348 constexpr bool is_negative(T x) {
349   return folly::detail::is_negative_impl<T, std::is_signed<T>::value>::check(x);
350 }
351
352 // same as `x <= 0`
353 template <typename T>
354 constexpr bool is_non_positive(T x) { return !x || folly::is_negative(x); }
355
356 // same as `x > 0`
357 template <typename T>
358 constexpr bool is_positive(T x) { return !is_non_positive(x); }
359
360 // same as `x >= 0`
361 template <typename T>
362 constexpr bool is_non_negative(T x) {
363   return !x || is_positive(x);
364 }
365
366 template <typename RHS, RHS rhs, typename LHS>
367 bool less_than(LHS const lhs) {
368   return detail::less_than_impl<
369     RHS, rhs, typename std::remove_reference<LHS>::type
370   >(lhs);
371 }
372
373 template <typename RHS, RHS rhs, typename LHS>
374 bool greater_than(LHS const lhs) {
375   return detail::greater_than_impl<
376     RHS, rhs, typename std::remove_reference<LHS>::type
377   >(lhs);
378 }
379
380 /**
381  * Like std::piecewise_construct, a tag type & instance used for in-place
382  * construction of non-movable contained types, e.g. by Synchronized.
383  */
384 struct construct_in_place_t {};
385 constexpr construct_in_place_t construct_in_place{};
386
387 } // namespace folly
388
389 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_3(std::basic_string);
390 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::vector);
391 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::list);
392 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::deque);
393 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::unique_ptr);
394 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(std::shared_ptr);
395 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(std::function);
396
397 // Boost
398 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(boost::shared_ptr);
399
400 #define FOLLY_CREATE_HAS_MEMBER_TYPE_TRAITS(classname, type_name) \
401   template <typename T> \
402   struct classname { \
403     template <typename C> \
404     constexpr static bool test(typename C::type_name*) { return true; } \
405     template <typename> \
406     constexpr static bool test(...) { return false; } \
407     constexpr static bool value = test<T>(nullptr); \
408   }
409
410 #define FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, cv_qual) \
411   template <typename TTheClass_, typename RTheReturn_, typename... TTheArgs_> \
412   class classname<TTheClass_, RTheReturn_(TTheArgs_...) cv_qual> { \
413     template < \
414       typename UTheClass_, RTheReturn_ (UTheClass_::*)(TTheArgs_...) cv_qual \
415     > struct sfinae {}; \
416     template <typename UTheClass_> \
417     constexpr static bool test(sfinae<UTheClass_, &UTheClass_::func_name>*) \
418     { return true; } \
419     template <typename> \
420     constexpr static bool test(...) { return false; } \
421   public: \
422     constexpr static bool value = test<TTheClass_>(nullptr); \
423   }
424
425 /*
426  * The FOLLY_CREATE_HAS_MEMBER_FN_TRAITS is used to create traits
427  * classes that check for the existence of a member function with
428  * a given name and signature. It currently does not support
429  * checking for inherited members.
430  *
431  * Such classes receive two template parameters: the class to be checked
432  * and the signature of the member function. A static boolean field
433  * named `value` (which is also constexpr) tells whether such member
434  * function exists.
435  *
436  * Each traits class created is bound only to the member name, not to
437  * its signature nor to the type of the class containing it.
438  *
439  * Say you need to know if a given class has a member function named
440  * `test` with the following signature:
441  *
442  *    int test() const;
443  *
444  * You'd need this macro to create a traits class to check for a member
445  * named `test`, and then use this traits class to check for the signature:
446  *
447  * namespace {
448  *
449  * FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(has_test_traits, test);
450  *
451  * } // unnamed-namespace
452  *
453  * void some_func() {
454  *   cout << "Does class Foo have a member int test() const? "
455  *     << boolalpha << has_test_traits<Foo, int() const>::value;
456  * }
457  *
458  * You can use the same traits class to test for a completely different
459  * signature, on a completely different class, as long as the member name
460  * is the same:
461  *
462  * void some_func() {
463  *   cout << "Does class Foo have a member int test()? "
464  *     << boolalpha << has_test_traits<Foo, int()>::value;
465  *   cout << "Does class Foo have a member int test() const? "
466  *     << boolalpha << has_test_traits<Foo, int() const>::value;
467  *   cout << "Does class Bar have a member double test(const string&, long)? "
468  *     << boolalpha << has_test_traits<Bar, double(const string&, long)>::value;
469  * }
470  *
471  * @author: Marcelo Juchem <marcelo@fb.com>
472  */
473 #define FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(classname, func_name) \
474   template <typename, typename> class classname; \
475   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, ); \
476   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, const); \
477   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL( \
478       classname, func_name, /* nolint */ volatile); \
479   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL( \
480       classname, func_name, /* nolint */ volatile const)
481
482 #endif //FOLLY_BASE_TRAITS_H_