-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasync_context.cppm
More file actions
2174 lines (1996 loc) · 67.8 KB
/
async_context.cppm
File metadata and controls
2174 lines (1996 loc) · 67.8 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2024 - 2026 Khalil Estell and the libhal contributors
//
// 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
//
// http://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.
module;
#define DEBUGGING 0
#include <cstddef>
#include <cstdint>
#include <bit>
#include <chrono>
#include <concepts>
#include <coroutine>
#include <exception>
#include <new>
#include <span>
#include <type_traits>
#include <utility>
#include <variant>
#if DEBUGGING
#include <print>
#endif
export module async_context;
namespace async::inline v0 {
/**
* @brief Unsigned 8-bit integer type alias
*
* This is a type alias for std::uint8_t, used throughout the async_context
* library for byte-sized operations.
*/
export using u8 = std::uint8_t;
/**
* @brief Byte type alias
*
* This is a type alias for std::uint8_t, used to represent byte-sized values.
* It's an alias for u8 and is provided for semantic clarity in contexts where
* byte-level operations are performed.
*/
export using byte = std::uint8_t;
/**
* @brief Size type alias
*
* This is a type alias for std::size_t, used to represent sizes and counts
* throughout the async_context library.
*/
export using usize = std::size_t;
/**
* @brief Unsigned pointer type alias
*
* This is a type alias for std::uintptr_t, used to represent pointer-sized
* unsigned integer values.
*/
export using uptr = std::uintptr_t;
/**
* @brief Bit mask for pointer alignment checking
*
* This constant represents a bitmask used to check if a pointer is properly
* aligned to the word size (uptr). It's calculated as sizeof(uptr) - 1.
*/
constexpr size_t mask = sizeof(uptr) - 1uz;
/**
* @brief Bit shift for word alignment calculations
*
* This constant represents the number of bits to shift when calculating
* word-aligned memory requirements. It's calculated as
* std::countr_zero(sizeof(uptr)).
*/
constexpr size_t shift = std::countr_zero(sizeof(uptr));
/**
* @brief Enumeration of blocking states for async operations
*
* This enum describes the various states a coroutine can be in when blocked
* from execution. Each state has different implications for how the scheduler
* should handle resumption of the coroutine.
*
* The blocking states are ordered from least to most restrictive:
* - nothing: Ready to run, no blocking
* - time: Must wait for a specific duration before resuming
* - io: Blocked by I/O operation that must complete
* - sync: Blocked by resource contention (mutex, semaphore)
* - external: Blocked by external coroutine system
*/
export enum class blocked_by : u8 {
/// Not blocked by anything, ready to run, can be resumed.
nothing = 0,
/// Blocked by a time duration that must elapse before resuming.
///
/// Another way of saying this is that the active coroutine is requesting to
/// be rescheduled at or after the time duration provided. The sleep time
/// provided is the minimum that a scheduler must wait before resuming the
/// coroutine. If the coroutine is resumed earlier, then this is erroneous
/// behavior. This behavior is clearly wrong, but is well defined. The
/// coroutine will resume earlier than it had anticipated, which can cause
/// other problems down the line. For example, if a coroutine resets a device
/// and must wait 50ms before attempting to communicate with it again. If that
/// time isn't upheld, then the code may thrown an exception when the device
/// is not online by the time of resumption.
///
/// This blocked by state is special in that it is not poll-able. Unlike the
/// blocked by states below, when a coroutine requests to be rescheduled, the
/// scheduler must ensure that the context/future it is bound to is resumed at
/// the right time.
time = 1,
/// Blocked by an I/O operation (DMA, bus transaction, etc.).
/// An interrupt or I/O completion will call unblock() when ready.
///
/// This blocked by state is poll-able, meaning that the coroutine may be
/// resumed before the context is unblocked.
/// Coroutines MUST check that their I/O operations have completed before
/// continuing on with their operations. If a coroutine is resumed and their
/// I/O operation is still pending, those coroutines should block themselves
/// by I/O again to signal to the scheduler that they are not ready yet.
///
/// A time estimate may be provided to the scheduler to give extra information
/// about when to poll or reschedule the context again. The time information
/// may be ignored.
io = 2,
/// Blocked by a resource contention.
///
/// Examples: mutex, semaphore, two coroutines competing for an I2C bus.
///
/// If the coroutine is resumed, the coroutine should check that it can
/// acquire the resource before assuming that it can. Just like I/O, if the
/// coroutine determines that its still blocked by sync, then it must re-block
/// itself by sync.
sync = 3,
/// Blocked by an external coroutine outside the async::context system.
///
/// Examples: co_awaiting a std::task, std::generator, or third-party
/// coroutine library.
///
/// A coroutine invoking a 3rd party async library is considered to be a
/// coroutine supervisor. A coroutine supervisor stays as the active coroutine
/// on its context, and must manually resume the 3rd party async library until
/// it finishes. This is important since the async context scheduler has no
/// knowledge of the 3rd party async operation and how it works.
///
/// If the external async library has the ability to call unblock() on the
/// context, then it should, but is not mandated to do so. Like I/O, this is
/// pollable by a scheduler and the coroutine code should block on external if
/// the external coroutine is still active.
external = 4,
};
/**
* @brief Represents an async execution context for coroutines
*
* The context class manages coroutine execution, memory allocation, and
* blocking states. It provides the infrastructure for running coroutines in
* stack-based environments without heap allocation.
*
* Derived classes must:
* 1. Provide stack memory via initialize_stack_memory()
* 2. Implement do_schedule() to handle blocking state notifications
*
* The context is designed to be cache-line optimized (≤ 64 bytes) and supports
* stack-based coroutine allocation. This makes it suitable for embedded systems
* with limited memory resources.
*/
export class context;
/**
* @brief Thrown when an async::context runs out of stack memory
*
* This exception is thrown when a coroutine attempts to allocate more memory
* than is available in the context's stack buffer. It indicates that the
* context has insufficient memory to accommodate the coroutine's execution
* frame.
*
* @note The violator pointer may not be valid when caught, as the context might
* have been destroyed during exception propagation.
*/
export struct bad_coroutine_alloc : std::bad_alloc
{
/**
* @brief Construct a bad_coroutine_alloc exception
*
* @param p_violator Pointer to the context that ran out of memory
*/
bad_coroutine_alloc(context const* p_violator)
: violator(p_violator)
{
}
/**
* @brief Get exception message
*
* @return C-string describing the error condition
*/
[[nodiscard]] char const* what() const noexcept override
{
return "An async::context ran out of memory!";
}
/**
* @brief A pointer to a context that ran out of memory
*
* NOTE: This pointer must NOT be assumed to be valid when caught. The
* context could have been destroyed during propagation to the catch block.
* The address MUST be compared against a valid and living context to
* confirm they are the same. In the event the application can determine
* that the violator has the same address of another known valid context,
* then valid context should be accessed and NOT this pointer.
*
*/
context const* violator;
};
/**
* @brief Thrown when a coroutine awaits a cancelled future
*
* This exception is thrown when a coroutine attempts to await a future that
* has been cancelled. It indicates that the operation was explicitly cancelled
* before completion.
*/
export class operation_cancelled : public std::exception
{
/**
* @brief Get exception message
*
* @return C-string describing the cancellation error
*/
[[nodiscard]] char const* what() const noexcept override
{
return "This future has been cancelled!";
}
};
// =============================================================================
//
// Context
//
// =============================================================================
/**
* @brief Sleep duration in microseconds
*
* Uses microsecond granularity and u32 representation for an optimal balance:
*
* - **Granularity**: Microseconds provide sufficient precision for real-time
* scheduling. Nanoseconds are too fine-grained—most systems cannot achieve
* that level of accuracy. Milliseconds are too coarse; many embedded
* schedulers regularly achieve 50-100µs precision with minimal context
* switching overhead.
*
* - **Range**: A u32 microseconds can represent durations up to ~4,294 seconds
* (1 hour 11 minutes), which is a practical upper bound for async operation
* delays. Longer delays should use alternative mechanisms or be broken into
* smaller segments.
*/
export using sleep_duration = std::chrono::duration<std::uint32_t, std::micro>;
/**
* @brief Information about the block state when context::schedule is called
*
*/
export using block_info =
std::variant<std::monostate, sleep_duration, context*>;
class promise_base;
/**
* @brief Interface for receiving notifications when an async context is
* unblocked
*
* Implement this interface to receive notifications when a context transitions
* from a blocked state to `blocked_by::nothing`. This is the primary mechanism
* for schedulers to efficiently track which contexts become ready for execution
* without polling.
*
* The `on_unblock()` method is called from within `context::unblock()`, which
* may be invoked from an ISR, a driver completion handler, or another thread.
* Implementations MUST be ISR-safe and noexcept. Avoid any operations that
* could block, allocate memory, or acquire non-ISR-safe locks within
* `on_unblock()`.
*
* Typical usage is through `context_handle`, which automatically registers and
* deregisters the listener on construction and destruction respectively.
* Direct registration is possible via `context::on_unblock()` but requires
* manual lifetime management — the listener MUST outlive the context it is
* registered with.
*
* Example implementation:
* @code
* class my_scheduler : public async::unblock_listener {
* private:
* void on_unblock(async::context& p_context) noexcept override {
* m_ready_queue.push(&p_context);
* }
* // ...
* };
* @endcode
*/
export struct unblock_listener
{
public:
template<typename Callable>
static auto from(Callable&& p_handler)
{
struct lambda_unblock_listener : public unblock_listener
{
Callable handler;
lambda_unblock_listener(Callable&& p_handler)
: handler(std::move(p_handler))
{
}
private:
void on_unblock(async::context& p_context) noexcept override
{
handler(p_context);
}
};
return lambda_unblock_listener{ std::forward<Callable>(p_handler) };
}
virtual ~unblock_listener() = default;
private:
friend class context;
/**
* @brief Called when a context transitions to the unblocked state
*
* This method is invoked by `context::unblock()` immediately after the
* context's state is set to `blocked_by::nothing`. It signals to the
* implementing scheduler that the context is now ready to be resumed.
*
* @param p_context The context that has just been unblocked. The context's
* state will be `blocked_by::nothing` at the time of this call. The
* implementor may read any state from the context but MUST NOT resume or
* destroy it within this call.
*
* @note This method MUST be noexcept and ISR-safe. It may be called from
* any execution context including interrupt handlers.
*/
virtual void on_unblock(context& p_context) noexcept = 0;
};
/**
* @brief The base context class for managing coroutine execution
*
* The context class is the core of the async_context library. It manages:
*
* - Stack-based coroutine allocation
* - Coroutine execution state and blocking information
* - Memory management for coroutine frames
* - Scheduler integration through virtual methods
*
* Derived classes must implement the do_schedule() method to integrate with
* custom schedulers and provide stack memory via initialize_stack_memory().
*
* @note Context objects should be kept alive as long as coroutines are running
* on them. The context must be properly cleaned up to prevent memory leaks.
*/
export class context
{
public:
// We store a single reference to a noop_coroutine() as multiple calls to this
// function are not guaranteed to compare equal. In order to have a
// noop_coroutine that plays nicely with our cancellation code, we need a
// single handle for all to reference as a "done" state.
inline static auto const noop_sentinel = std::noop_coroutine();
static auto constexpr default_timeout = sleep_duration(0);
/**
* @brief Default constructor for context
*
* Creates context without a stack. `initialize_stack_memory()` must be called
* before passing this context to a coroutine.
*/
context() = default;
/**
* @brief Construct a new context object with stack memory.
*
* @param p_stack - the stack memory for the async operations
*/
context(std::span<uptr> p_stack)
{
initialize_stack_memory(p_stack);
}
/**
* @brief Delete copy constructor
*
* Contexts cannot be copied as they manage unique stack memory.
*/
context(context const&) = delete;
/**
* @brief Delete copy assignment operator
*
* Contexts cannot be copied as they manage unique stack memory.
*/
context& operator=(context const&) = delete;
/**
* @brief Move constructor
*
* Transfers ownership of stack and state from the source context. The
* moved-from context is reset to its default state (no stack, no active
* operations).
*
* @param p_other The context to move from (will be reset to default state)
*/
context(context&& p_other) noexcept
: m_active_handle(std::exchange(p_other.m_active_handle, noop_sentinel))
, m_stack_pointer(std::exchange(p_other.m_stack_pointer, nullptr))
, m_stack(std::exchange(p_other.m_stack, {}))
, m_original(std::exchange(p_other.m_original, nullptr))
, m_listener(std::exchange(p_other.m_listener, nullptr))
, m_sleep_time(std::exchange(p_other.m_sleep_time, sleep_duration::zero()))
, m_sync_blocker(std::exchange(p_other.m_sync_blocker, nullptr))
, m_state(std::exchange(p_other.m_state, blocked_by::nothing))
{
}
/**
* @brief Move assignment operator
*
* Transfers ownership of stack and state from the source context. The
* current context is cancelled before assignment, and the moved-from context
* is reset to its default state.
*
* @param p_other The context to move from (will be reset to default state)
* @return Reference to this context
*/
context& operator=(context&& p_other) noexcept
{
if (this != &p_other) {
cancel();
m_active_handle = std::exchange(p_other.m_active_handle, noop_sentinel);
m_stack_pointer = std::exchange(p_other.m_stack_pointer, nullptr);
m_stack = std::exchange(p_other.m_stack, {});
m_original = std::exchange(p_other.m_original, nullptr);
m_listener = std::exchange(p_other.m_listener, nullptr);
m_sleep_time =
std::exchange(p_other.m_sleep_time, sleep_duration::zero());
m_sync_blocker = std::exchange(p_other.m_sync_blocker, nullptr);
m_state = std::exchange(p_other.m_state, blocked_by::nothing);
}
return *this;
}
/**
* @brief Initialize stack memory for the context
*
* This method must be called by derived context implementations to provide
* the stack memory that will be used for coroutine frame allocation.
*
* @param p_stack_memory - Stack memory provided by the derived context. It is
* the responsibility of the derived context to manage this memory. If this
* memory was dynamically allocated, then it is the responsibility of the
* derived class to deallocate that memory.
*
* @note The stack memory must be properly aligned and sized to accommodate
* coroutine frames. This is a required step for any derived context
* implementation.
*/
constexpr void initialize_stack_memory(std::span<uptr> p_stack_memory)
{
m_stack = p_stack_memory;
m_stack_pointer = m_stack.data();
}
/**
* @brief Unblocks the context without invoking the unblock listener
*
* This method transitions the context to "nothing" (ready to run).
*/
constexpr void unblock_without_notification() noexcept
{
get_original().m_state = blocked_by::nothing;
get_original().m_sleep_time = sleep_duration::zero();
get_original().m_sync_blocker = nullptr;
}
/**
* @brief Unblocks the context and clears blocking state
*
* The state of the context after this is called:
*
* 1. Block state becomes (block_by::nothing)
* 2. sleep time is set to 0us.
* 3. sync blocker is set to nullptr.
*
* The unblock listener is called before clearing the context state in the
* event that the unblock listener wants to inspect information from the
* context.
*
* @note this API is safe to call within an interrupt service routine.
*/
constexpr void unblock() noexcept
{
if (get_original().m_listener) {
get_original().m_listener->on_unblock(*this);
}
// We clear this context state information after the unblock listener is
// invoked to allow the unblock listener to inspect the context's current
// state prior to being unblocked.
unblock_without_notification();
}
/**
* @brief Blocks the context for a specified time duration
*
* This method blocks the current coroutine for the specified duration,
* transitioning it to the time-blocking state. The scheduler is responsible
* for resuming this context after the duration has elapsed.
*
* @param p_duration The time duration to block for
* @return std::suspend_always to suspend the coroutine until resumed
*/
template<typename Rep, typename Period>
constexpr std::suspend_always block_by_time(
std::chrono::duration<Rep, Period> p_duration) noexcept
{
get_original().m_state = blocked_by::time;
get_original().m_sleep_time =
std::chrono::duration_cast<sleep_duration>(p_duration);
return {};
}
/**
* @brief Blocks the context for an I/O operation
*
* This method blocks the current coroutine until an I/O operation completes.
* The context can be resumed by calling unblock() when the I/O is ready.
*
* @param p_duration Optional time estimate for when to poll or reschedule
* the context again. The scheduler may ignore this hint.
* @return std::suspend_always to suspend the coroutine until resumed
*/
constexpr std::suspend_always block_by_io(
sleep_duration p_duration = default_timeout) noexcept
{
get_original().m_state = blocked_by::io;
get_original().m_sleep_time = p_duration;
return {};
}
/**
* @brief Blocks the context by resource contention (sync)
*
* This method blocks the current coroutine until a synchronization resource
* becomes available. The context can be resumed at any time to check if the
* resource can be claimed. A scheduler can collect the set of contexts
* blocked by `p_blocker` and when `p_blocker` is no longer blocked by
* anything, unblock and resume any of those context to have them acquire
* access over the bus.
*
* @param p_blocker Pointer to the context that is currently blocking this one
* @return std::suspend_always to suspend the coroutine until resumed
*/
constexpr std::suspend_always block_by_sync(context* p_blocker) noexcept
{
get_original().m_state = blocked_by::sync;
get_original().m_sync_blocker = p_blocker;
return {};
}
/**
* @brief Blocks the context by an external coroutine system
*
* This method blocks the current coroutine when it's awaiting an operation
* from an external coroutine library (e.g., std::task, std::generator). The
* coroutine is considered a supervising coroutine. The coroutine may be
* resumed while blocked by external.
*
* @return std::suspend_always to suspend the coroutine until resumed
*/
constexpr std::suspend_always block_by_external() noexcept
{
get_original().m_state = blocked_by::external;
return {};
}
/**
* @brief Get the current active coroutine handle
*
* This method returns the coroutine handle that is currently active on this
* context.
*
* NOTE: It is UB to `destroy()` the returned handle. This coroutine is
* managed/owned by this context and thus, the returned coroutine MUST NOT be
* destroyed.
*
* @return std::coroutine_handle<> representing the active coroutine.
*/
[[nodiscard]] constexpr std::coroutine_handle<> active_handle() const noexcept
{
return m_active_handle;
}
/**
* @brief Get the current blocking state of this context
*
* This method returns the current blocking state that determines how the
* scheduler should handle this context.
*
* @return blocked_by enum value indicating the current blocking state
*/
[[nodiscard]] constexpr auto state() const noexcept
{
return get_original().m_state;
}
/**
* @brief Check if the context has completed its operation
*
* This method determines whether the context is in a "done" state, meaning
* it has completed all operations and no longer needs to be scheduled. The
* stack memory of the context should be completely unused when this function
* returns `true`.
*
* @return true if the context is done, false otherwise
*/
[[nodiscard]] constexpr bool done() const
{
return m_active_handle == noop_sentinel;
}
/**
* @brief Cancel all operations on this context
*
* This method cancels all pending operations on this context.
*/
void cancel();
/**
* @brief Resume the active coroutine on this context
*
* This method resumes the currently active coroutine. It only has an effect
* if the context is not blocked by time, as time-blocking contexts must wait
* for their designated duration to elapse.
*/
void resume()
{
// We cannot resume the a coroutine blocked by time. Only the scheduler can
// unblock a context state.
//
// This needs to be here to ensure that sync_wait is possible, otherwise the
// blocked_by::time semantic cannot be supported.
if (state() != blocked_by::time) {
m_active_handle.resume();
}
}
/**
* @brief Perform sync_wait operation
*
* This method waits synchronously for all coroutines on this context to
* complete. It uses the provided delay function to sleep for the required
* duration when waiting for time-based operations.
*
* @tparam DelayFunc The type of the delay function (must be invocable with
* sleep_duration parameter)
* @param p_delay - a delay function, that accepts a sleep duration and
* returns void.
*
* @note This method is primarily intended for testing and simple applications
* where a synchronous wait is needed. It's not suitable for production
* embedded systems that require precise timing or real-time scheduling.
*/
void sync_wait(std::invocable<sleep_duration> auto&& p_delay)
{
while (not done()) {
resume();
if (state() == blocked_by::time) {
if (auto delay_time = sleep_time();
delay_time > sleep_duration::zero()) {
p_delay(delay_time);
}
unblock_without_notification();
}
}
}
/**
* @brief Get the amount of stack memory used by active coroutines
*
* This method returns how much stack space has been consumed by currently
* active coroutines.
*
* @return The number of `uptr` sized words used in the stack
*/
[[nodiscard]] constexpr auto memory_used() const noexcept
{
return m_stack_pointer - m_stack.data();
}
/**
* @brief Get the total capacity of the stack memory
*
* This method returns the total size of the stack buffer in uptr words.
*
* @return The total capacity in uptr words
*/
[[nodiscard]] constexpr auto capacity() const noexcept
{
return m_stack.size();
}
/**
* @brief Get the remaining stack memory available
*
* This method returns how much stack space is still available for new
* coroutine allocation.
*
* @return The number of `uptr` sized words used in the stack
*/
[[nodiscard]] constexpr auto memory_remaining() const noexcept
{
return capacity() - memory_used();
}
/**
* @brief Amount of time to delay resuming this context
*
* When a context is blocked by for a set duration of time, it is the
* responsibility of the scheduler to ensure that the context is not resumed
* until that duration of time has elapsed. In the event that the context is
* not blocked by time, then this returns 0.
*
* Calling this function multiple times returns the last sleep duration that
* was set by the async operation contained within the context. It is the
* responsibility of the scheduler to unblock this context, otherwise, calling
* resume() will immediately without resuming async operation.
*
* @return constexpr sleep_duration - the amount of time to delay resuming
* this context.
*/
[[nodiscard]] constexpr sleep_duration sleep_time() const noexcept
{
return get_original().m_sleep_time;
}
/**
* @brief Sets the unblock listener
*
* There can only be a single unblock listener per context, thus any
* previously set unblock listener will be removed.
*
* Because this API takes the address of the listener, it is important that
* the context outlive the listener.
*
* `remove_unblock_handler()` must be called before the end of the lifetime of
* the `p_listener` object. It is undefined behavior to allow a listener to be
* destroyed before it is removed from this context.
*
* @param p_listener - the address of the unblock listener to be invoked when
* this context is unblocked.
*/
void on_unblock(unblock_listener* p_listener)
{
get_original().m_listener = p_listener;
}
/**
* @brief Clears the on_unblock listener from this context
*
* After this is called, any call to `unblock()` will not invoke an unblock
* listener.
*
* It is the responsibility of the application to clear the unblock listener
* is cleared, before the end of the lifetime of the object that was passed to
* on_unblock().
*/
void clear_unblock_listener() noexcept
{
get_original().m_listener = nullptr;
}
/**
* @brief Get the address of the context currently blocking this one blocking
*
* If this context's state is `blocked_by::sync` then there is a context that
* currently holds a resource that this context needs. That context's address
* can be acquired by this API.
*
* @returns context const* - returns a const pointer to the other context that
* is blocking this context. If no such context exists, then a nullptr is
* returned.
*/
[[nodiscard]] context const* get_blocker() const
{
return get_original().m_sync_blocker;
}
~context()
{
cancel();
}
private:
template<typename T>
friend class promise;
friend class promise_base;
friend class proxy_context;
/**
* @brief Check if this is a proxy context
*
* This method determines whether the current context is acting as a proxy
* for another context.
*
* @return true if this is a proxy context, false otherwise
*/
[[nodiscard]] constexpr bool is_proxy() const noexcept
{
return m_original != nullptr;
}
/**
* @brief Get a reference to the original context
*
* If this object is a proxy, then the original context will be pulled from
* the proxy information and if its not, then a reference to `this` is
* returned.
*
* @return context& - reference to the original context
*/
[[nodiscard]] constexpr context const& get_original() const noexcept
{
if (is_proxy()) {
return *m_original;
} else {
return *this;
}
}
/**
* @brief Get a reference to the original context
*
* If this object is a proxy, then the original context will be pulled from
* the proxy information and if its not, then a reference to `this` is
* returned.
*
* @return context& - reference to the original context
*/
[[nodiscard]] constexpr context& get_original() noexcept
{
if (is_proxy()) {
return *m_original;
} else {
return *this;
}
}
/**
* @brief Set the active coroutine handle for this context
*
* This method sets the coroutine that is currently running on this context.
*
* @param p_active_handle The coroutine handle to set as active
*/
constexpr void active_handle(std::coroutine_handle<> p_active_handle)
{
m_active_handle = p_active_handle;
}
/**
* @brief Allocate memory for a coroutine frame on the stack
*
* This method allocates space on the context's stack for a coroutine frame.
* It ensures that the allocation fits within the available stack space.
*
* @param p_bytes The number of bytes to allocate
* @return Pointer to the allocated memory location
* @throws bad_coroutine_alloc if there's insufficient stack space
*/
[[nodiscard]] constexpr void* allocate(std::size_t p_bytes)
{
// The extra 1 word is for the stack pointer's address
size_t const words_to_allocate = 1uz + ((p_bytes + mask) >> shift);
auto const new_stack_index = m_stack_pointer + words_to_allocate;
if (new_stack_index > &m_stack.back()) [[unlikely]] {
throw bad_coroutine_alloc(this);
}
// Put the address of the stack pointer member on the stack, before the
// coroutine frame, such that the delete operation can find the address and
// update it.
*m_stack_pointer = std::bit_cast<uptr>(&m_stack_pointer);
#if DEBUGGING
std::println("💾 Allocating {} words, current stack {}, new stack {}, "
"stack pointer member address: 0x{:x}",
words_to_allocate,
static_cast<void*>(m_stack_pointer),
static_cast<void*>(new_stack_index),
*m_stack_pointer);
#endif
// Address of the coroutine frame will be the current position of the stack
// pointer + 1 to avoid overwriting the stack pointer address.
auto* const coroutine_frame_stack_address = m_stack_pointer + 1uz;
m_stack_pointer = new_stack_index;
return coroutine_frame_stack_address;
}
// A concern for this library is how large the context objet is thus the word
// sizes for each field is denoted below.
std::coroutine_handle<> m_active_handle = noop_sentinel; // word 1
uptr* m_stack_pointer = nullptr; // word 2
std::span<uptr> m_stack{}; // word 3-4
context* m_original = nullptr; // word 5
unblock_listener* m_listener = nullptr; // word 6
sleep_duration m_sleep_time = sleep_duration::zero(); // word 7
context* m_sync_blocker = nullptr; // word 8
blocked_by m_state = blocked_by::nothing; // word 9: pad 3
};
/**
* @brief A proxy context that provides isolated stack space for supervised
* coroutines
*
* The proxy_context class allows creating a sub-context with its own stack
* space that is isolated from the parent context. This is particularly useful
* for implementing timeouts and supervision of coroutines.
*
* When a proxy context is created, it takes the remaining stack space from the
* parent context and ensures that the parent's stack is properly clamped to
* prevent overwrites.
*/
export class proxy_context : public context
{
public:
/**
* @brief Create a proxy context from an existing parent context
*
* This static method creates a new proxy context that uses a portion of the
* parent context's stack memory. The proxy takes control over the remaining
* stack space, effectively creating an isolated sub-context.
*
* @param p_parent The parent context to create a proxy from
* @return A new proxy_context instance
*/
static proxy_context from(context& p_parent)
{
return { p_parent };
}
/**
* @brief Delete copy constructor
*
* Proxy contexts cannot be copied as they manage unique stack memory.
*/
proxy_context(proxy_context const&) = delete;
/**
* @brief Delete copy assignment operator
*
* Proxy contexts cannot be copied as they manage unique stack memory.
*/
proxy_context& operator=(proxy_context const&) = delete;
/**
* @brief Delete move constructor
*
* Proxy contexts cannot be moved as they manage unique stack memory.
*/
proxy_context(proxy_context&&) = delete;
/**
* @brief Delete move assignment operator
*
* Proxy contexts cannot be moved as they manage unique stack memory.
*/
proxy_context& operator=(proxy_context&&) = delete;