• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_TEST_MOVE_ONLY_INT_H_
6 #define BASE_TEST_MOVE_ONLY_INT_H_
7 
8 #include <utility>
9 
10 #include "base/functional/callback.h"
11 #include "third_party/abseil-cpp/absl/cleanup/cleanup.h"
12 
13 namespace base {
14 
15 // A move-only class that holds an integer. This is designed for testing
16 // containers. See also CopyOnlyInt.
17 class MoveOnlyInt {
18  public:
data_(data)19   explicit MoveOnlyInt(int data = 1) : data_(data) {}
MoveOnlyInt(MoveOnlyInt && other)20   MoveOnlyInt(MoveOnlyInt&& other) : data_(other.data_) { other.data_ = 0; }
21 
22   MoveOnlyInt(const MoveOnlyInt&) = delete;
23   MoveOnlyInt& operator=(const MoveOnlyInt&) = delete;
24 
25   ~MoveOnlyInt();
26 
27   MoveOnlyInt& operator=(MoveOnlyInt&& other) {
28     data_ = other.data_;
29     other.data_ = 0;
30     return *this;
31   }
32 
33   friend bool operator==(const MoveOnlyInt& lhs,
34                          const MoveOnlyInt& rhs) = default;
35   friend auto operator<=>(const MoveOnlyInt& lhs,
36                           const MoveOnlyInt& rhs) = default;
37 
38   friend bool operator==(const MoveOnlyInt& lhs, int rhs) {
39     return lhs.data_ == rhs;
40   }
41   friend bool operator==(int lhs, const MoveOnlyInt& rhs) {
42     return lhs == rhs.data_;
43   }
44   friend auto operator<=>(const MoveOnlyInt& lhs, int rhs) {
45     return lhs.data_ <=> rhs;
46   }
47   friend auto operator<=>(int lhs, const MoveOnlyInt& rhs) {
48     return lhs <=> rhs.data_;
49   }
50 
data()51   int data() const { return data_; }
52 
53   // Called with the value of `data()` when an instance of `MoveOnlyInt` is
54   // destroyed. Returns an `absl::Cleanup` scoper that automatically
55   // unregisters the callback when the scoper is destroyed.
SetScopedDestructionCallback(RepeatingCallback<void (int)> callback)56   static auto SetScopedDestructionCallback(
57       RepeatingCallback<void(int)> callback) {
58     GetDestructionCallbackStorage() = std::move(callback);
59     return absl::Cleanup([] { GetDestructionCallbackStorage().Reset(); });
60   }
61 
62  private:
63   static RepeatingCallback<void(int)>& GetDestructionCallbackStorage();
64 
65   volatile int data_;
66 };
67 
68 }  // namespace base
69 
70 #endif  // BASE_TEST_MOVE_ONLY_INT_H_
71