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