xref: /llvm-project/libcxx/test/std/atomics/atomics.ref/operator_plus_equals.pass.cpp (revision 42ba740afffa16f991be6aa36626bd872d41ebc0)
1 //
2 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3 // See https://llvm.org/LICENSE.txt for license information.
4 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5 //
6 //===----------------------------------------------------------------------===//
7 
8 // UNSUPPORTED: c++03, c++11, c++14, c++17
9 // XFAIL: !has-64-bit-atomics
10 
11 // integral-type operator+=(integral-type) const noexcept;
12 // floating-point-type operator+=(floating-point-type) const noexcept;
13 // T* operator+=(difference_type) const noexcept;
14 
15 #include <atomic>
16 #include <concepts>
17 #include <cassert>
18 #include <type_traits>
19 
20 #include "atomic_helpers.h"
21 #include "test_helper.h"
22 #include "test_macros.h"
23 
24 template <typename T>
25 concept has_operator_plus_equals = requires { std::declval<T const>() += std::declval<T>(); };
26 
27 template <typename T>
28 struct TestDoesNotHaveOperatorPlusEquals {
29   void operator()() const { static_assert(!has_operator_plus_equals<std::atomic_ref<T>>); }
30 };
31 
32 template <typename T>
33 struct TestOperatorPlusEquals {
34   void operator()() const {
35     if constexpr (std::is_arithmetic_v<T>) {
36       T x(T(1));
37       std::atomic_ref<T> const a(x);
38 
39       std::same_as<T> decltype(auto) y = (a += T(2));
40       assert(y == T(3));
41       assert(x == T(3));
42       ASSERT_NOEXCEPT(a += T(0));
43     } else if constexpr (std::is_pointer_v<T>) {
44       using U = std::remove_pointer_t<T>;
45       U t[9]  = {};
46       T p{&t[1]};
47       std::atomic_ref<T> const a(p);
48 
49       std::same_as<T> decltype(auto) y = (a += 2);
50       assert(y == &t[3]);
51       assert(a == &t[3]);
52       ASSERT_NOEXCEPT(a += 0);
53     } else {
54       static_assert(std::is_void_v<T>);
55     }
56 
57     // memory_order::seq_cst
58     {
59       auto plus_equals = [](std::atomic_ref<T> const& x, T old_val, T new_val) { x += (new_val - old_val); };
60       auto load        = [](std::atomic_ref<T> const& x) { return x.load(); };
61       test_seq_cst<T>(plus_equals, load);
62     }
63   }
64 };
65 
66 int main(int, char**) {
67   TestEachIntegralType<TestOperatorPlusEquals>()();
68 
69   TestOperatorPlusEquals<float>()();
70   TestOperatorPlusEquals<double>()();
71 
72   TestEachPointerType<TestOperatorPlusEquals>()();
73 
74   TestDoesNotHaveOperatorPlusEquals<bool>()();
75   TestDoesNotHaveOperatorPlusEquals<UserAtomicType>()();
76   TestDoesNotHaveOperatorPlusEquals<LargeUserAtomicType>()();
77 
78   return 0;
79 }
80