aboutsummaryrefslogtreecommitdiff
path: root/pw_async_basic/public/pw_async_basic/fake_dispatcher.h
blob: 43d35038a85c36d79d2465dd59bcecb7a2311824 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright 2023 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#pragma once

#include "pw_async/dispatcher.h"
#include "pw_async/task.h"
#include "pw_containers/intrusive_list.h"

namespace pw::async::test::backend {

class NativeFakeDispatcher final {
 public:
  explicit NativeFakeDispatcher(Dispatcher& test_dispatcher);
  ~NativeFakeDispatcher();

  void RequestStop();

  void Post(Task& task);

  void PostAfter(Task& task, chrono::SystemClock::duration delay);

  void PostAt(Task& task, chrono::SystemClock::time_point time);

  bool Cancel(Task& task);

  bool RunUntilIdle();

  bool RunUntil(chrono::SystemClock::time_point end_time);

  bool RunFor(chrono::SystemClock::duration duration);

  chrono::SystemClock::time_point now() { return now_; }

 private:
  // Insert |task| into task_queue_ maintaining its min-heap property, keyed by
  // |time_due|.
  void PostTaskInternal(::pw::async::backend::NativeTask& task,
                        chrono::SystemClock::time_point time_due);

  // Dequeue and run each task that is due.
  // Returns true iff any tasks were invoked during the run.
  bool ExecuteDueTasks();

  // Dequeue each task and run each TaskFunction with a PW_STATUS_CANCELLED
  // status.
  // Returns true iff any tasks were invoked during the run.
  bool DrainTaskQueue();

  Dispatcher& dispatcher_;
  bool stop_requested_ = false;

  // A priority queue of scheduled tasks sorted by earliest due times first.
  IntrusiveList<::pw::async::backend::NativeTask> task_queue_;

  // Tracks the current time as viewed by the test dispatcher.
  chrono::SystemClock::time_point now_;
};

}  // namespace pw::async::test::backend