xref: /llvm-project/libcxx/include/__utility/swap.h (revision f69585235ec85d54e0f3fc41b2d5700430907f99)
1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef _LIBCPP___UTILITY_SWAP_H
10 #define _LIBCPP___UTILITY_SWAP_H
11 
12 #include <__config>
13 #include <__cstddef/size_t.h>
14 #include <__type_traits/enable_if.h>
15 #include <__type_traits/is_assignable.h>
16 #include <__type_traits/is_constructible.h>
17 #include <__type_traits/is_nothrow_assignable.h>
18 #include <__type_traits/is_nothrow_constructible.h>
19 #include <__type_traits/is_swappable.h>
20 #include <__utility/declval.h>
21 #include <__utility/move.h>
22 
23 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
24 #  pragma GCC system_header
25 #endif
26 
27 _LIBCPP_PUSH_MACROS
28 #include <__undef_macros>
29 
30 _LIBCPP_BEGIN_NAMESPACE_STD
31 
32 #ifndef _LIBCPP_CXX03_LANG
33 template <class _Tp>
34 using __swap_result_t _LIBCPP_NODEBUG =
35     __enable_if_t<is_move_constructible<_Tp>::value && is_move_assignable<_Tp>::value>;
36 #else
37 template <class>
38 using __swap_result_t _LIBCPP_NODEBUG = void;
39 #endif
40 
41 template <class _Tp>
42 inline _LIBCPP_HIDE_FROM_ABI __swap_result_t<_Tp> _LIBCPP_CONSTEXPR_SINCE_CXX20 swap(_Tp& __x, _Tp& __y)
43     _NOEXCEPT_(is_nothrow_move_constructible<_Tp>::value&& is_nothrow_move_assignable<_Tp>::value) {
44   _Tp __t(std::move(__x));
45   __x = std::move(__y);
46   __y = std::move(__t);
47 }
48 
49 template <class _Tp, size_t _Np, __enable_if_t<__is_swappable_v<_Tp>, int> >
50 inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void swap(_Tp (&__a)[_Np], _Tp (&__b)[_Np])
51     _NOEXCEPT_(__is_nothrow_swappable_v<_Tp>) {
52   for (size_t __i = 0; __i != _Np; ++__i) {
53     swap(__a[__i], __b[__i]);
54   }
55 }
56 
57 _LIBCPP_END_NAMESPACE_STD
58 
59 _LIBCPP_POP_MACROS
60 
61 #endif // _LIBCPP___UTILITY_SWAP_H
62