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 bool Cancel(Task& task); 36 37 bool RunUntilIdle(); 38 39 bool RunUntil(chrono::SystemClock::time_point end_time); 40 41 bool RunFor(chrono::SystemClock::duration duration); 42 now()43 chrono::SystemClock::time_point now() { return now_; } 44 45 private: 46 // Insert |task| into task_queue_ maintaining its min-heap property, keyed by 47 // |time_due|. 48 void PostTaskInternal(::pw::async::backend::NativeTask& task, 49 chrono::SystemClock::time_point time_due); 50 51 // Dequeue and run each task that is due. 52 // Returns true iff any tasks were invoked during the run. 53 bool ExecuteDueTasks(); 54 55 // Dequeue each task and run each TaskFunction with a PW_STATUS_CANCELLED 56 // status. 57 // Returns true iff any tasks were invoked during the run. 58 bool DrainTaskQueue(); 59 60 Dispatcher& dispatcher_; 61 bool stop_requested_ = false; 62 63 // A priority queue of scheduled tasks sorted by earliest due times first. 64 IntrusiveList<::pw::async::backend::NativeTask> task_queue_; 65 66 // Tracks the current time as viewed by the test dispatcher. 67 chrono::SystemClock::time_point now_; 68 }; 69 70 } // namespace pw::async::test::backend 71