• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "pw_async/dispatcher.h"
17 #include "pw_async/task.h"
18 #include "pw_containers/intrusive_list.h"
19 
20 namespace pw::async::test::backend {
21 
22 class NativeFakeDispatcher final {
23  public:
24   explicit NativeFakeDispatcher(Dispatcher& test_dispatcher);
25   ~NativeFakeDispatcher();
26 
27   void RequestStop();
28 
29   void Post(Task& task);
30 
31   void PostAfter(Task& task, chrono::SystemClock::duration delay);
32 
33   void PostAt(Task& task, chrono::SystemClock::time_point time);
34 
35   void PostPeriodic(Task& task, chrono::SystemClock::duration interval);
36   void PostPeriodicAt(Task& task,
37                       chrono::SystemClock::duration interval,
38                       chrono::SystemClock::time_point start_time);
39 
40   bool Cancel(Task& task);
41 
42   void RunUntilIdle();
43 
44   void RunUntil(chrono::SystemClock::time_point end_time);
45 
46   void RunFor(chrono::SystemClock::duration duration);
47 
now()48   chrono::SystemClock::time_point now() { return now_; }
49 
50  private:
51   // Insert |task| into task_queue_ maintaining its min-heap property, keyed by
52   // |time_due|.
53   void PostTaskInternal(::pw::async::backend::NativeTask& task,
54                         chrono::SystemClock::time_point time_due);
55 
56   // Dequeue and run each task that is due.
57   void ExecuteDueTasks();
58 
59   // Dequeue each task and run each TaskFunction with a PW_STATUS_CANCELLED
60   // status.
61   void DrainTaskQueue();
62 
63   Dispatcher& dispatcher_;
64   bool stop_requested_ = false;
65 
66   // A priority queue of scheduled tasks sorted by earliest due times first.
67   IntrusiveList<::pw::async::backend::NativeTask> task_queue_;
68 
69   // Tracks the current time as viewed by the test dispatcher.
70   chrono::SystemClock::time_point now_;
71 };
72 
73 }  // namespace pw::async::test::backend
74