├── .github └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── demo ├── Cargo.lock ├── Cargo.toml └── src │ └── main.rs └── src └── lib.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | 2 | on: 3 | pull_request: 4 | branches: [main] 5 | push: 6 | branches: [main] 7 | 8 | name: CI 9 | 10 | jobs: 11 | build: 12 | name: Build 13 | runs-on: ubuntu-latest 14 | needs: [lints, docs] 15 | env: 16 | RUSTFLAGS: "-D warnings" 17 | strategy: 18 | matrix: 19 | target: 20 | - aarch64-unknown-linux-gnu 21 | - x86_64-pc-windows-gnu 22 | - x86_64-unknown-linux-gnu 23 | steps: 24 | - name: Checkout sources 25 | uses: actions/checkout@v3 26 | 27 | - name: Install cross 28 | uses: taiki-e/install-action@cross 29 | 30 | - name: Build 31 | run: cross build --all-features --all-targets --release --target=${{ matrix.target }} 32 | 33 | test: 34 | name: Test Suite 35 | runs-on: ubuntu-latest 36 | needs: [lints, docs] 37 | env: 38 | RUSTFLAGS: "-D warnings" 39 | steps: 40 | - name: Checkout sources 41 | uses: actions/checkout@v3 42 | 43 | - name: Install stable toolchain 44 | uses: dtolnay/rust-toolchain@stable 45 | 46 | #- uses: Swatinem/rust-cache@v1 47 | 48 | - name: Run cargo test 49 | run: cargo test -- --test-threads 1 50 | 51 | demo: 52 | name: Test Suite 53 | runs-on: ubuntu-latest 54 | needs: [lints, docs] 55 | env: 56 | RUSTFLAGS: "-D warnings" 57 | steps: 58 | - name: Checkout sources 59 | uses: actions/checkout@v3 60 | 61 | - name: Install stable toolchain 62 | uses: dtolnay/rust-toolchain@stable 63 | 64 | #- uses: Swatinem/rust-cache@v1 65 | 66 | - name: Run cargo test 67 | run: cd demo && cargo run 68 | 69 | msrv: 70 | name: Minimum Supported Rust Version 71 | runs-on: ubuntu-latest 72 | needs: [lints, docs] 73 | env: 74 | RUSTFLAGS: "-D warnings" 75 | steps: 76 | - name: Checkout sources 77 | uses: actions/checkout@v3 78 | 79 | - name: Install cargo-binstall 80 | uses: taiki-e/install-action@cargo-binstall 81 | 82 | - name: Install cargo-msrv 83 | run: cargo binstall --version 0.16.0-beta.17 --no-confirm cargo-msrv 84 | 85 | #- uses: Swatinem/rust-cache@v1 86 | 87 | - name: Check MSRV 88 | run: cargo msrv verify --log-target=stdout --output-format=json 89 | 90 | semver: 91 | name: Semantic Versioning 92 | runs-on: ubuntu-latest 93 | needs: [lints, docs] 94 | steps: 95 | - name: Checkout sources 96 | uses: actions/checkout@v3 97 | - name: Check semver 98 | uses: obi1kenobi/cargo-semver-checks-action@v2 99 | 100 | lints: 101 | name: Lints 102 | runs-on: ubuntu-latest 103 | steps: 104 | - name: Checkout sources 105 | uses: actions/checkout@v3 106 | 107 | - name: Install stable toolchain 108 | uses: dtolnay/rust-toolchain@stable 109 | with: 110 | components: clippy 111 | 112 | - name: Run cargo fmt 113 | run: cargo fmt --all -- --check 114 | 115 | - name: Run cargo clippy 116 | run: cargo clippy --all-features --all-targets -- -D warnings 117 | 118 | docs: 119 | name: Documentation 120 | runs-on: ubuntu-latest 121 | steps: 122 | - name: Checkout sources 123 | uses: actions/checkout@v3 124 | 125 | - name: Install stable toolchain 126 | uses: dtolnay/rust-toolchain@stable 127 | 128 | - name: Run cargo doc 129 | env: 130 | RUSTDOCFLAGS: "-Dwarnings" 131 | run: cargo doc --no-deps 132 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **/target/* 2 | Cargo.lock 3 | 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cassette" 3 | version = "0.3.0" 4 | authors = ["James Munns "] 5 | edition = "2018" 6 | rust-version = "1.68" 7 | license = "MIT OR Apache-2.0" 8 | description = "A simple, single-future, non-blocking executor intended for building state machines" 9 | readme = "README.md" 10 | documentation = "https://docs.rs/cassette" 11 | homepage = "https://github.com/jamesmunns/cassette" 12 | repository = "https://github.com/jamesmunns/cassette" 13 | 14 | keywords = ["async", "no-std"] 15 | categories = ["asynchronous"] 16 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2021 Anthony James Munns 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Cassette 2 | 3 | A simple, single-future, non-blocking executor intended for building state machines. Designed to be no-std and embedded friendly. 4 | 5 | This executor TOTALLY IGNORES wakers and context, meaning that all async functions should expect to be polled repeatedly until completion. 6 | 7 | ## Inspiration 8 | 9 | So, I'm really not good at async, but I like the idea of being able to use the ability to yield or await on tasks that will require some time to complete. 10 | 11 | The idea here is that you would write one, top level `async` function that would either eventually resolve to some value, or that will run forever (to act as a state machine). 12 | 13 | ## How it works 14 | 15 | 1. You write some async functions 16 | 2. You call the "top level" async function 17 | 3. You poll on it until it resolves (or forever) 18 | 19 | Note: This demo is available in the [`demo/` folder](./demo) of this repo. 20 | 21 | ### Step 1 - You write some async functions 22 | 23 | Here's the "context" of our state machine, describing a couple of high level behaviors, as well as individual substeps. 24 | 25 | ```rust 26 | struct Demo { 27 | lol: u32, 28 | } 29 | 30 | impl Demo { 31 | async fn entry(&mut self) { 32 | for _ in 0..10 { 33 | self.entry_1().await; 34 | self.entry_2().await; 35 | } 36 | } 37 | 38 | async fn entry_1(&mut self) { 39 | self.start_at_zero().await; 40 | self.add_one_until_ten().await; 41 | self.sub_one_until_zero().await; 42 | } 43 | 44 | async fn entry_2(&mut self) { 45 | self.start_at_five().await; 46 | self.sub_one_until_zero().await; 47 | self.add_one_until_ten().await; 48 | } 49 | 50 | async fn start_at_zero(&mut self) { 51 | self.lol = 0; 52 | } 53 | 54 | async fn start_at_five(&mut self) { 55 | self.lol = 5; 56 | } 57 | 58 | async fn add_one_until_ten(&mut self) { 59 | loop { 60 | delay(self).await; // simulate fake delays/not ready state 61 | self.lol += 1; 62 | if self.lol >= 10 { 63 | return; 64 | } 65 | } 66 | } 67 | 68 | async fn sub_one_until_zero(&mut self) { 69 | loop { 70 | delay(self).await; // simulate fake delays/not ready state 71 | self.lol -= 1; 72 | if self.lol == 0 { 73 | return; 74 | } 75 | } 76 | } 77 | } 78 | ``` 79 | 80 | We can also make simple little futures for code that needs to be polled until ready: 81 | 82 | ```rust 83 | static FAKE: AtomicU32 = AtomicU32::new(0); 84 | struct CountFuture; 85 | impl Future for CountFuture { 86 | type Output = (); 87 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 88 | let x = FAKE.fetch_add(1, Ordering::SeqCst); 89 | print!("{}, ", x); 90 | if (x % 5) == 0 { 91 | Poll::Ready(()) 92 | } else { 93 | cx.waker().wake_by_ref(); 94 | Poll::Pending 95 | } 96 | } 97 | } 98 | 99 | async fn delay(ctxt: &mut Demo) { 100 | println!("delay says lol: {}", ctxt.lol); 101 | let x = CountFuture; 102 | x.await; 103 | println!("and delay!"); 104 | } 105 | ``` 106 | 107 | ### Step 2 - You call the "top level" async function 108 | 109 | ```rust 110 | fn main() { 111 | // Make a new struct 112 | let mut demo = Demo { lol: 100 }; 113 | 114 | // Call the entry point future, and pin it 115 | let x = core::pin::pin!(demo.entry()); 116 | 117 | // Give the pinned future to Cassette 118 | // for execution 119 | let mut cm = Cassette::new(x); 120 | 121 | /* ... */ 122 | } 123 | ``` 124 | 125 | ### Step 3 - You poll on it until it resolves (or forever) 126 | 127 | ```rust 128 | fn main() { 129 | /* ... */ 130 | 131 | loop { 132 | if let Some(x) = cm.poll_on() { 133 | println!("Done!: `{:?}`", x); 134 | break; 135 | } 136 | } 137 | } 138 | ``` 139 | 140 | ## A larger demo 141 | 142 | If you'd like to see a larger demo, I used Cassette to implement an I2C peripheral bootloader state machine for a `thumbv6m` target. You can check out [that PR](https://github.com/sprocket-board/sprocket-boot/pull/1) for more context. 143 | 144 | ## License 145 | 146 | This crate is licensed under the [MIT](./LICENSE-MIT) and [Apache 2.0](./LICENSE-APACHE) licenses. 147 | -------------------------------------------------------------------------------- /demo/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "cassette" 7 | version = "0.3.0" 8 | 9 | [[package]] 10 | name = "demo" 11 | version = "0.1.0" 12 | dependencies = [ 13 | "cassette", 14 | ] 15 | -------------------------------------------------------------------------------- /demo/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "demo" 3 | version = "0.1.0" 4 | authors = ["James Munns "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | cassette = { path = "../" } 11 | 12 | -------------------------------------------------------------------------------- /demo/src/main.rs: -------------------------------------------------------------------------------- 1 | use core::{ 2 | future::Future, 3 | pin::Pin, 4 | sync::atomic::{AtomicU32, Ordering}, 5 | task::{Context, Poll}, 6 | }; 7 | 8 | use cassette::Cassette; 9 | 10 | struct Demo { 11 | lol: u32, 12 | } 13 | 14 | impl Demo { 15 | async fn entry(&mut self) { 16 | for _ in 0..10 { 17 | self.entry_1().await; 18 | self.entry_2().await; 19 | } 20 | } 21 | 22 | async fn entry_1(&mut self) { 23 | self.start_at_zero().await; 24 | self.add_one_until_ten().await; 25 | self.sub_one_until_zero().await; 26 | } 27 | 28 | async fn entry_2(&mut self) { 29 | self.start_at_five().await; 30 | self.sub_one_until_zero().await; 31 | self.add_one_until_ten().await; 32 | } 33 | 34 | async fn start_at_zero(&mut self) { 35 | self.lol = 0; 36 | } 37 | 38 | async fn start_at_five(&mut self) { 39 | self.lol = 5; 40 | } 41 | 42 | async fn add_one_until_ten(&mut self) { 43 | loop { 44 | delay(self).await; // simulate fake delays/not ready state 45 | self.lol += 1; 46 | if self.lol >= 10 { 47 | return; 48 | } 49 | } 50 | } 51 | 52 | async fn sub_one_until_zero(&mut self) { 53 | loop { 54 | delay(self).await; // simulate fake delays/not ready state 55 | self.lol -= 1; 56 | if self.lol == 0 { 57 | return; 58 | } 59 | } 60 | } 61 | } 62 | 63 | fn main() { 64 | let mut demo = Demo { lol: 100 }; 65 | let x = core::pin::pin!(demo.entry()); 66 | 67 | let mut cm = Cassette::new(x); 68 | 69 | loop { 70 | if let Some(x) = cm.poll_on() { 71 | println!("Done!: `{:?}`", x); 72 | break; 73 | } 74 | } 75 | } 76 | 77 | static FAKE: AtomicU32 = AtomicU32::new(0); 78 | struct CountFuture; 79 | impl Future for CountFuture { 80 | type Output = (); 81 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 82 | let x = FAKE.fetch_add(1, Ordering::SeqCst); 83 | print!("{}, ", x); 84 | if (x % 5) == 0 { 85 | Poll::Ready(()) 86 | } else { 87 | cx.waker().wake_by_ref(); 88 | Poll::Pending 89 | } 90 | } 91 | } 92 | 93 | async fn delay(ctxt: &mut Demo) { 94 | println!("delay says lol: {}", ctxt.lol); 95 | let x = CountFuture; 96 | x.await; 97 | println!("and delay!"); 98 | } 99 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(not(test), no_std)] 2 | 3 | //! A simple, single-future, non-blocking executor intended for building state machines. Designed to be no-std and embedded friendly. 4 | //! 5 | //! This executor TOTALLY IGNORES wakers and context, meaning that all async functions should expect to be polled repeatedly until completion. 6 | //! 7 | //! ## Inspiration 8 | //! 9 | //! So, I'm really not good at async, but I like the idea of being able to use the ability to yield or await on tasks that will require some time to complete. 10 | //! 11 | //! The idea here is that you would write one, top level `async` function that would either eventually resolve to some value, or that will run forever (to act as a state machine). 12 | //! 13 | //! ## How it works 14 | //! 15 | //! 1. You write some async functions 16 | //! 2. You call the "top level" async function 17 | //! 3. You poll on it until it resolves (or forever) 18 | //! 19 | //! Note: This demo is available in the [`demo/` folder](./../demo) of this repo. 20 | //! 21 | //! ### Step 1 - You write some async functions 22 | //! 23 | //! Here's the "context" of our state machine, describing a couple of high level behaviors, as well as individual substeps. 24 | //! 25 | //! ```rust 26 | //! struct Demo { 27 | //! lol: u32, 28 | //! } 29 | //! 30 | //! impl Demo { 31 | //! async fn entry(&mut self) { 32 | //! for _ in 0..10 { 33 | //! self.entry_1().await; 34 | //! self.entry_2().await; 35 | //! } 36 | //! } 37 | //! 38 | //! async fn entry_1(&mut self) { 39 | //! self.start_at_zero().await; 40 | //! self.add_one_until_ten().await; 41 | //! self.sub_one_until_zero().await; 42 | //! } 43 | //! 44 | //! async fn entry_2(&mut self) { 45 | //! self.start_at_five().await; 46 | //! self.sub_one_until_zero().await; 47 | //! self.add_one_until_ten().await; 48 | //! } 49 | //! 50 | //! async fn start_at_zero(&mut self) { 51 | //! self.lol = 0; 52 | //! } 53 | //! 54 | //! async fn start_at_five(&mut self) { 55 | //! self.lol = 5; 56 | //! } 57 | //! 58 | //! async fn add_one_until_ten(&mut self) { 59 | //! loop { 60 | //! delay(self).await; // simulate fake delays/not ready state 61 | //! self.lol += 1; 62 | //! if self.lol >= 10 { 63 | //! return; 64 | //! } 65 | //! } 66 | //! } 67 | //! 68 | //! async fn sub_one_until_zero(&mut self) { 69 | //! loop { 70 | //! delay(self).await; // simulate fake delays/not ready state 71 | //! self.lol -= 1; 72 | //! if self.lol == 0 { 73 | //! return; 74 | //! } 75 | //! } 76 | //! } 77 | //! } 78 | //! 79 | //! # use core::{ 80 | //! # future::Future, 81 | //! # pin::Pin, 82 | //! # sync::atomic::{AtomicU32, Ordering}, 83 | //! # task::{Context, Poll}, 84 | //! # }; 85 | //! # static FAKE: AtomicU32 = AtomicU32::new(0); 86 | //! # struct CountFuture; 87 | //! # impl Future for CountFuture { 88 | //! # type Output = (); 89 | //! # fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 90 | //! # let x = FAKE.fetch_add(1, Ordering::SeqCst); 91 | //! # print!("{}, ", x); 92 | //! # if (x % 5) == 0 { 93 | //! # Poll::Ready(()) 94 | //! # } else { 95 | //! # cx.waker().wake_by_ref(); 96 | //! # Poll::Pending 97 | //! # } 98 | //! # } 99 | //! # } 100 | //! # 101 | //! # async fn delay(ctxt: &mut Demo) { 102 | //! # println!("delay says lol: {}", ctxt.lol); 103 | //! # let x = CountFuture; 104 | //! # x.await; 105 | //! # println!("and delay!"); 106 | //! # } 107 | //! ``` 108 | //! 109 | //! We can also make simple little futures for code that needs to be polled until ready: 110 | //! 111 | //! ```rust 112 | //! # use core::{ 113 | //! # future::Future, 114 | //! # pin::Pin, 115 | //! # sync::atomic::{AtomicU32, Ordering}, 116 | //! # task::{Context, Poll}, 117 | //! # }; 118 | //! static FAKE: AtomicU32 = AtomicU32::new(0); 119 | //! struct CountFuture; 120 | //! impl Future for CountFuture { 121 | //! type Output = (); 122 | //! fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 123 | //! let x = FAKE.fetch_add(1, Ordering::SeqCst); 124 | //! print!("{}, ", x); 125 | //! if (x % 5) == 0 { 126 | //! Poll::Ready(()) 127 | //! } else { 128 | //! cx.waker().wake_by_ref(); 129 | //! Poll::Pending 130 | //! } 131 | //! } 132 | //! } 133 | //! 134 | //! async fn delay(ctxt: &mut Demo) { 135 | //! println!("delay says lol: {}", ctxt.lol); 136 | //! let x = CountFuture; 137 | //! x.await; 138 | //! println!("and delay!"); 139 | //! } 140 | //! # 141 | //! # struct Demo { 142 | //! # lol: u32, 143 | //! # } 144 | //! ``` 145 | //! 146 | //! ### Step 2 - You call the "top level" async function 147 | //! 148 | //! ```rust 149 | //! # struct Demo { 150 | //! # lol: u32, 151 | //! # } 152 | //! # 153 | //! # impl Demo { 154 | //! # async fn entry(&mut self) { 155 | //! # panic!() 156 | //! # } 157 | //! # } 158 | //! # 159 | //! 160 | //! use cassette::Cassette; 161 | //! 162 | //! fn main() { 163 | //! // Make a new struct 164 | //! let mut demo = Demo { lol: 100 }; 165 | //! 166 | //! // Call the entry point future, and pin it 167 | //! let x = core::pin::pin!(demo.entry()); 168 | //! 169 | //! // Give the pinned future to Cassette 170 | //! // for execution 171 | //! let mut cm = Cassette::new(x); 172 | //! 173 | //! /* ... */ 174 | //! } 175 | //! ``` 176 | //! 177 | //! ### Step 3 - You poll on it until it resolves (or forever) 178 | //! 179 | //! ```rust 180 | //! # use cassette::Cassette; 181 | //! 182 | //! # struct Demo { 183 | //! # lol: u32, 184 | //! # } 185 | //! # 186 | //! # impl Demo { 187 | //! # async fn entry(&mut self) { 188 | //! # } 189 | //! # } 190 | //! # 191 | //! fn main() { 192 | //! # // Make a new struct 193 | //! # let mut demo = Demo { lol: 100 }; 194 | //! # 195 | //! # // Call the entry point future, and pin it 196 | //! # let x = core::pin::pin!(demo.entry()); 197 | //! # 198 | //! # // Give the pinned future to Cassette 199 | //! # // for execution 200 | //! # let mut cm = Cassette::new(x); 201 | //! /* ... */ 202 | //! 203 | //! loop { 204 | //! if let Some(x) = cm.poll_on() { 205 | //! println!("Done!: `{:?}`", x); 206 | //! break; 207 | //! } 208 | //! } 209 | //! } 210 | //! ``` 211 | //! 212 | //! ## A larger demo 213 | //! 214 | //! If you'd like to see a larger demo, I used Cassette to implement an I2C peripheral bootloader state machine for a `thumbv6m` target. You can check out [that PR](https://github.com/sprocket-board/sprocket-boot/pull/1) for more context. 215 | //! 216 | //! ## License 217 | //! 218 | //! [MIT](https://github.com/jamesmunns/cassette/blob/main/LICENSE-MIT) or [Apache 2.0](https://github.com/jamesmunns/cassette/blob/main/LICENSE-APACHE) 219 | 220 | use core::{ 221 | future::Future, 222 | pin::Pin, 223 | task::{Context, Poll, RawWaker, RawWakerVTable, Waker}, 224 | }; 225 | 226 | fn no_op(_: *const ()) {} 227 | fn no_op_clone(_: *const ()) -> RawWaker { 228 | noop_raw_waker() 229 | } 230 | 231 | static RWVT: RawWakerVTable = RawWakerVTable::new(no_op_clone, no_op, no_op, no_op); 232 | 233 | #[inline] 234 | fn noop_raw_waker() -> RawWaker { 235 | RawWaker::new(core::ptr::null(), &RWVT) 236 | } 237 | 238 | /// A single-future non-blocking executor 239 | pub struct Cassette 240 | where 241 | T: Future + Unpin, 242 | { 243 | thing: T, 244 | fake_wake: Waker, 245 | done: bool, 246 | } 247 | 248 | impl Cassette 249 | where 250 | T: Future + Unpin, 251 | { 252 | /// Create a new Cassette containing a single pinned future 253 | /// 254 | /// # Example 255 | /// 256 | /// ``` 257 | /// use cassette::Cassette; 258 | /// 259 | /// struct Demo { 260 | /// lol: u32, 261 | /// } 262 | /// 263 | /// impl Demo { 264 | /// async fn entry(&mut self) { 265 | /// /* Huzzah! */ 266 | /// } 267 | /// } 268 | /// 269 | /// // Make a new struct 270 | /// let mut demo = Demo { lol: 100 }; 271 | /// 272 | /// // Call the entry point future, and pin it 273 | /// let x = core::pin::pin!(demo.entry()); 274 | /// 275 | /// // Give the pinned future to Cassette 276 | /// // for execution 277 | /// let mut cm = Cassette::new(x); 278 | /// ``` 279 | pub fn new(thing: T) -> Self { 280 | let raw_waker = noop_raw_waker(); 281 | let waker = unsafe { Waker::from_raw(raw_waker) }; 282 | 283 | Self { 284 | thing, 285 | fake_wake: waker, 286 | done: false, 287 | } 288 | } 289 | 290 | /// Perform a "single step" of the future contained by this 291 | /// Cassette. 292 | /// 293 | /// This is intended to be "polled to completion", which 294 | /// might be for forever. 295 | /// 296 | /// # Example 297 | /// 298 | /// ``` 299 | /// use cassette::Cassette; 300 | /// 301 | /// struct Demo { 302 | /// lol: u32, 303 | /// } 304 | /// 305 | /// impl Demo { 306 | /// async fn entry(&mut self) { 307 | /// /* Huzzah! */ 308 | /// } 309 | /// } 310 | /// 311 | /// // Make a new struct 312 | /// let mut demo = Demo { lol: 100 }; 313 | /// 314 | /// // Call the entry point future, and pin it 315 | /// let x = core::pin::pin!(demo.entry()); 316 | /// 317 | /// // Give the pinned future to Cassette 318 | /// // for execution 319 | /// let mut cm = Cassette::new(x); 320 | /// 321 | /// while cm.poll_on().is_none() { } 322 | /// println!("Future done!"); 323 | /// ``` 324 | /// 325 | /// ## Panics 326 | /// 327 | /// This method will panic if the contained future has already 328 | /// been completed as `Poll::Ready(_)`. 329 | pub fn poll_on(&mut self) -> Option<::Output> { 330 | assert!(!self.done, "Polled a completed future"); 331 | 332 | let mut ctxt = Context::from_waker(&self.fake_wake); 333 | let y = Pin::new(&mut self.thing).poll(&mut ctxt); 334 | match y { 335 | Poll::Pending => None, 336 | Poll::Ready(yes) => { 337 | self.done = true; 338 | Some(yes) 339 | } 340 | } 341 | } 342 | 343 | /// Block on the contained future forever 344 | /// 345 | /// ## Panics 346 | /// 347 | /// This method will panic if the contained future has already 348 | /// been completed as `Poll::Ready(_)`. 349 | pub fn block_on(mut self) -> ::Output { 350 | assert!(!self.done, "Blocked on completed future"); 351 | 352 | loop { 353 | if let Some(val) = self.poll_on() { 354 | return val; 355 | } 356 | } 357 | } 358 | 359 | /// Has the contained future resolved to `Poll::Ready(_)` yet? 360 | pub fn is_done(&self) -> bool { 361 | self.done 362 | } 363 | } 364 | 365 | /// Cooperatively gives up a timeslice to the task scheduler. 366 | #[inline] 367 | pub async fn yield_now() { 368 | YieldNow(false).await 369 | } 370 | 371 | struct YieldNow(bool); 372 | 373 | impl Future for YieldNow { 374 | type Output = (); 375 | 376 | // inspired by async-std v1.9.0 377 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 378 | if !self.0 { 379 | self.0 = true; 380 | 381 | // Wake immediately, so we get polled again 382 | // in the next timeslice. 383 | // 384 | // Not necessary if our executor is `Cassette`, but 385 | // on other executors we might produce a deadlock 386 | // otherwise. 387 | cx.waker().wake_by_ref(); 388 | Poll::Pending 389 | } else { 390 | Poll::Ready(()) 391 | } 392 | } 393 | } 394 | 395 | /// Runs a future to completion on the current thread. 396 | /// 397 | /// This function will block the caller until the given future has completed. 398 | /// 399 | /// Be aware that this function performs busy-waiting; it repeatedly polls 400 | /// the future until completion and completely ignores context and wakers. 401 | pub fn block_on(f: F) -> ::Output { 402 | let f = core::pin::pin!(f); 403 | Cassette::new(f).block_on() 404 | } 405 | --------------------------------------------------------------------------------