xref: /aosp_15_r20/external/pigweed/pw_sync/public/pw_sync/lock_testing.h (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #pragma once
15 
16 /// This file provides types that meet C++'s lock-related named requirements,
17 /// but do no actual locking. They are only intended for use in tests.
18 
19 #include <chrono>
20 #include <ratio>
21 
22 #include "pw_sync/virtual_basic_lockable.h"
23 
24 namespace pw::sync::test {
25 
26 /// Fake lock that meet's C++'s \em BasicLockable named requirement.
27 class FakeBasicLockable : public VirtualBasicLockable {
28  public:
29   virtual ~FakeBasicLockable() = default;
30 
locked()31   bool locked() const { return locked_; }
32 
33  protected:
34   bool locked_ = false;
35 
36  private:
37   void DoLockOperation(Operation operation) override;
38 };
39 
40 /// Fake lock that meet's C++'s \em Lockable named requirement.
41 class FakeLockable : public FakeBasicLockable {
42  public:
43   bool try_lock();
44 };
45 
46 /// Fake clock that merely provides the expected dependent types.
47 struct FakeClock {
48   using rep = int64_t;
49   using period = std::micro;
50   using duration = std::chrono::duration<rep, period>;
51   using time_point = std::chrono::time_point<FakeClock>;
52 };
53 
54 /// Fake clock that provides invalid dependent types.
55 ///
56 /// This clock is guaranteed to fail `is_lockable_until<Lock, NoClock>` for any
57 /// `Lock`.
58 struct NotAClock {
59   using rep = void;
60   using period = void;
61   using duration = void;
62   using time_point = void;
63 };
64 
65 /// Fake lock that meet's C++'s \em TimedLockable named requirement.
66 class FakeTimedLockable : public FakeLockable {
67  public:
try_lock_for(const FakeClock::duration &)68   bool try_lock_for(const FakeClock::duration&) { return try_lock(); }
try_lock_until(const FakeClock::time_point &)69   bool try_lock_until(const FakeClock::time_point&) { return try_lock(); }
70 };
71 
72 }  // namespace pw::sync::test
73