|
| 1 | +// Copyright 2024 - 2025 Khalil Estell and the libhal contributors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://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, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +#include <cassert> |
| 16 | + |
| 17 | +#include <array> |
| 18 | +#include <chrono> |
| 19 | +#include <coroutine> |
| 20 | +#include <memory_resource> |
| 21 | +#include <span> |
| 22 | +#include <variant> |
| 23 | + |
| 24 | +import async_context; |
| 25 | + |
| 26 | +struct my_scheduler : public async::scheduler |
| 27 | +{ |
| 28 | + int sleep_count = 0; |
| 29 | + |
| 30 | +private: |
| 31 | + void do_schedule( |
| 32 | + [[maybe_unused]] async::context& p_context, |
| 33 | + [[maybe_unused]] async::blocked_by p_block_state, |
| 34 | + [[maybe_unused]] std::variant<async::sleep_duration, async::context*> |
| 35 | + p_block_info) override |
| 36 | + { |
| 37 | + if (std::holds_alternative<async::sleep_duration>(p_block_info)) { |
| 38 | + sleep_count++; |
| 39 | + } |
| 40 | + } |
| 41 | +}; |
| 42 | + |
| 43 | +async::future<void> coro_double_delay(async::context&) |
| 44 | +{ |
| 45 | + using namespace std::chrono_literals; |
| 46 | + co_await 100ns; |
| 47 | + co_await 100ns; |
| 48 | + co_return; |
| 49 | +} |
| 50 | +int main() |
| 51 | +{ |
| 52 | + auto scheduler = |
| 53 | + mem::make_strong_ptr<my_scheduler>(std::pmr::new_delete_resource()); |
| 54 | + auto buffer = mem::make_strong_ptr<std::array<async::u8, 1024>>( |
| 55 | + std::pmr::new_delete_resource()); |
| 56 | + auto buffer_span = mem::make_strong_ptr<std::span<async::u8>>( |
| 57 | + std::pmr::new_delete_resource(), *buffer); |
| 58 | + async::context my_context(scheduler, buffer_span); |
| 59 | + |
| 60 | + auto future_delay = coro_double_delay(my_context); |
| 61 | + |
| 62 | + assert(not future_delay.done()); |
| 63 | + |
| 64 | + future_delay.resume(); |
| 65 | + |
| 66 | + assert(scheduler->sleep_count == 1); |
| 67 | + |
| 68 | + future_delay.resume(); |
| 69 | + |
| 70 | + assert(scheduler->sleep_count == 2); |
| 71 | + assert(not scheduler->done()); |
| 72 | + |
| 73 | + future_delay.resume(); |
| 74 | + |
| 75 | + assert(scheduler->done()); |
| 76 | + |
| 77 | + return 0; |
| 78 | +} |
0 commit comments