├── .github ├── dependabot.yml └── workflows │ ├── ci.yml │ └── release.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples ├── local_executor.rs ├── main_as_attr.rs ├── main_macro.rs ├── thread_executor.rs └── thread_executor_arc.rs ├── src └── lib.rs └── tests └── macro_usages.rs /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: / 5 | schedule: 6 | interval: weekly 7 | commit-message: 8 | prefix: '' 9 | labels: [] 10 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | permissions: 4 | contents: read 5 | 6 | on: 7 | pull_request: 8 | push: 9 | branches: 10 | - main 11 | schedule: 12 | - cron: '0 2 * * 0' 13 | 14 | env: 15 | CARGO_INCREMENTAL: 0 16 | CARGO_NET_GIT_FETCH_WITH_CLI: true 17 | CARGO_NET_RETRY: 10 18 | CARGO_TERM_COLOR: always 19 | RUST_BACKTRACE: 1 20 | RUSTFLAGS: -D warnings 21 | RUSTDOCFLAGS: -D warnings 22 | RUSTUP_MAX_RETRIES: 10 23 | 24 | defaults: 25 | run: 26 | shell: bash 27 | 28 | jobs: 29 | fmt: 30 | uses: smol-rs/.github/.github/workflows/fmt.yml@main 31 | security_audit: 32 | uses: smol-rs/.github/.github/workflows/security_audit.yml@main 33 | permissions: 34 | checks: write 35 | contents: read 36 | issues: write 37 | secrets: inherit 38 | 39 | test: 40 | runs-on: ${{ matrix.os }} 41 | strategy: 42 | fail-fast: false 43 | matrix: 44 | os: [ubuntu-latest] 45 | rust: [nightly, beta, stable] 46 | steps: 47 | - uses: actions/checkout@v4 48 | - name: Install Rust 49 | # --no-self-update is necessary because the windows environment cannot self-update rustup.exe. 50 | run: rustup update ${{ matrix.rust }} --no-self-update && rustup default ${{ matrix.rust }} 51 | - run: cargo build --all --all-features --all-targets 52 | - name: Run cargo check (without dev-dependencies to catch missing feature flags) 53 | if: startsWith(matrix.rust, 'nightly') 54 | run: cargo check -Z features=dev_dep 55 | - run: cargo test 56 | 57 | msrv: 58 | runs-on: ubuntu-latest 59 | strategy: 60 | matrix: 61 | # When updating this, the reminder to update the minimum supported 62 | # Rust version in Cargo.toml and README.md. 63 | rust: ['1.63'] 64 | steps: 65 | - uses: actions/checkout@v4 66 | - name: Install Rust 67 | run: rustup update ${{ matrix.rust }} && rustup default ${{ matrix.rust }} 68 | - run: cargo build 69 | 70 | clippy: 71 | runs-on: ubuntu-latest 72 | steps: 73 | - uses: actions/checkout@v4 74 | - name: Install Rust 75 | run: rustup update stable 76 | - run: cargo clippy --all-features --all-targets 77 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | permissions: 4 | contents: write 5 | 6 | on: 7 | push: 8 | tags: 9 | - v[0-9]+.* 10 | 11 | jobs: 12 | create-release: 13 | if: github.repository_owner == 'smol-rs' 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v4 17 | - uses: taiki-e/create-gh-release-action@v1 18 | with: 19 | changelog: CHANGELOG.md 20 | branch: main 21 | env: 22 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Version 0.1.1 2 | 3 | - Bump `event-listener` to v5.1.0. (#3) 4 | 5 | # Version 0.1.0 6 | 7 | - Initial release 8 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "smol-macros" 3 | version = "0.1.1" 4 | edition = "2021" 5 | rust-version = "1.63" 6 | authors = ["John Nunley "] 7 | description = "Macros for setting up a smol runtime" 8 | license = "Apache-2.0 OR MIT" 9 | repository = "https://github.com/smol-rs/smol-macros" 10 | keywords = ["async", "await", "future", "io", "macro"] 11 | categories = ["asynchronous", "concurrency", "network-programming"] 12 | exclude = ["/.*"] 13 | 14 | [dependencies] 15 | async-executor = "1.6.0" 16 | async-io = "2.2.0" 17 | async-lock = "3.1.2" 18 | event-listener = "5.1.0" 19 | futures-lite = { version = "2.0.1", default-features = false } 20 | 21 | [dev-dependencies] 22 | async-lock = "3.1.2" 23 | macro_rules_attribute = "0.2.0" 24 | unsend = { version = "0.2.1", default-features = false, features = ["alloc"] } 25 | -------------------------------------------------------------------------------- /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 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # smol-macros 2 | 3 | [![Build](https://github.com/smol-rs/smol-macros/actions/workflows/ci.yml/badge.svg)]( 4 | https://github.com/smol-rs/smol-macros/actions) 5 | [![License](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)]( 6 | https://github.com/smol-rs/smol-macros) 7 | [![Cargo](https://img.shields.io/crates/v/smol-macros.svg)]( 8 | https://crates.io/crates/smol-macros) 9 | [![Documentation](https://docs.rs/smol-macros/badge.svg)]( 10 | https://docs.rs/smol-macros) 11 | 12 | Macros for using `smol-rs`. 13 | 14 | One of the advantages of [`smol`] is that it lets you set up your own executor, optimized for 15 | your own use cases. However, quick scaffolding is important for many organizational use cases. 16 | Especially when sane defaults are appreciated, setting up your own executor is a waste of 17 | time. 18 | 19 | This crate provides macros for setting up an efficient [`smol`] runtime quickly and 20 | effectively. It provides sane defaults that are useful for most applications. 21 | 22 | ## Simple Executor 23 | 24 | Just have an `async` main function, using the [`main`] macro. 25 | 26 | ```rust 27 | use smol_macros::main; 28 | 29 | main! { 30 | async fn main() { 31 | println!("Hello, world!"); 32 | } 33 | } 34 | ``` 35 | 36 | This crate uses declarative macros rather than procedural macros, in order to avoid needing 37 | to use heavy macro dependencies. If you want to use the proc macro syntax, you can use the 38 | [`macro_rules_attribute::apply`] function to emulate it. 39 | 40 | The following is equivalent to the previous example. 41 | 42 | ```rust 43 | use macro_rules_attribute::apply; 44 | use smol_macros::main; 45 | 46 | #[apply(main!)] 47 | async fn main() { 48 | println!("Hello, world!"); 49 | } 50 | ``` 51 | 52 | ## Task-Based Executor 53 | 54 | This crate re-exports [`smol::Executor`]. If that is used as the first parameter in a 55 | function in [`main`], it will automatically create the executor. 56 | 57 | ```rust 58 | use macro_rules_attribute::apply; 59 | use smol_macros::{main, Executor}; 60 | 61 | #[apply(main!)] 62 | async fn main(ex: &Executor<'_>) { 63 | ex.spawn(async { println!("Hello world!"); }).await; 64 | } 65 | ``` 66 | 67 | If the thread-safe [`smol::Executor`] is used here, a thread pool will be spawned to run 68 | the executor on multiple threads. For the thread-unsafe [`smol::LocalExecutor`], no threads 69 | will be spawned. 70 | 71 | See documentation for the [`main`] function for more details. 72 | 73 | ## Tests 74 | 75 | Use the [`test`] macro to set up test cases that run self-contained executors. 76 | 77 | ```rust 78 | use macro_rules_attribute::apply; 79 | use smol_macros::{test, Executor}; 80 | 81 | #[apply(test!)] 82 | async fn do_test(ex: &Executor<'_>) { 83 | ex.spawn(async { 84 | assert_eq!(1 + 1, 2); 85 | }).await; 86 | } 87 | ``` 88 | 89 | [`smol`]: https://crates.io/crates/smol 90 | [`smol::Executor`]: https://docs.rs/smol/latest/smol/struct.Executor.html 91 | [`smol::LocalExecutor`]: https://docs.rs/smol/latest/smol/struct.LocalExecutor.html 92 | [`macro_rules_attribute::apply`]: https://docs.rs/macro_rules_attribute/latest/macro_rules_attribute/attr.apply.html 93 | 94 | ## MSRV Policy 95 | 96 | The Minimum Supported Rust Version (MSRV) of this crate is **1.63**. As a **tentative** policy, the MSRV will not advance past the [current Rust version provided by Debian Stable](https://packages.debian.org/stable/rust/rustc). At the time of writing, this version of Rust is *1.63*. However, the MSRV may be advanced further in the event of a major ecosystem shift or a security vulnerability. 97 | 98 | ## License 99 | 100 | Licensed under either of 101 | 102 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 103 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 104 | 105 | at your option. 106 | 107 | #### Contribution 108 | 109 | Unless you explicitly state otherwise, any contribution intentionally submitted 110 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 111 | dual licensed as above, without any additional terms or conditions. 112 | -------------------------------------------------------------------------------- /examples/local_executor.rs: -------------------------------------------------------------------------------- 1 | //! Set up a thread executor that is local. 2 | 3 | use macro_rules_attribute::apply; 4 | use smol_macros::{main, LocalExecutor}; 5 | use std::time::Duration; 6 | 7 | #[apply(main!)] 8 | async fn main(ex: &LocalExecutor<'_>) { 9 | let mut tasks = vec![]; 10 | for i in 0..16 { 11 | let task = ex.spawn(async move { 12 | println!("Task number {i}"); 13 | }); 14 | 15 | tasks.push(task); 16 | } 17 | 18 | async_io::Timer::after(Duration::from_secs(1)).await; 19 | 20 | // Wait for tasks to complete. 21 | for task in tasks { 22 | task.await; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /examples/main_as_attr.rs: -------------------------------------------------------------------------------- 1 | //! Use the `macro_rules_attribute` to use `main` as an attribute. 2 | 3 | use macro_rules_attribute::apply; 4 | use smol_macros::main; 5 | 6 | #[apply(main!)] 7 | async fn main() { 8 | println!("hello world!"); 9 | } 10 | -------------------------------------------------------------------------------- /examples/main_macro.rs: -------------------------------------------------------------------------------- 1 | //! Example of using the `main` macro. 2 | 3 | use smol_macros::main; 4 | 5 | main! { 6 | async fn main() { 7 | println!("hello world!"); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /examples/thread_executor.rs: -------------------------------------------------------------------------------- 1 | //! Set up a thread executor. 2 | 3 | use smol_macros::{main, Executor}; 4 | use std::time::Duration; 5 | 6 | main! { 7 | async fn main(ex: &Executor<'_>) { 8 | let mut tasks = vec![]; 9 | for i in 0..16 { 10 | let task = ex.spawn(async move { 11 | println!("Task number {i}"); 12 | }); 13 | 14 | tasks.push(task); 15 | } 16 | 17 | async_io::Timer::after(Duration::from_secs(1)).await; 18 | 19 | // Wait for tasks to complete. 20 | for task in tasks { 21 | task.await; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /examples/thread_executor_arc.rs: -------------------------------------------------------------------------------- 1 | //! Set up a thread executor. 2 | 3 | use smol_macros::{main, Executor}; 4 | use std::sync::Arc; 5 | use std::time::Duration; 6 | 7 | main! { 8 | async fn main(ex: Arc>) { 9 | let mut tasks = vec![]; 10 | for i in 0..16 { 11 | let task = ex.spawn(async move { 12 | println!("Task number {i}"); 13 | }); 14 | 15 | tasks.push(task); 16 | } 17 | 18 | async_io::Timer::after(Duration::from_secs(1)).await; 19 | 20 | // Wait for tasks to complete. 21 | for task in tasks { 22 | task.await; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Macros for using `smol-rs`. 2 | //! 3 | //! One of the advantages of [`smol`] is that it lets you set up your own executor, optimized for 4 | //! your own use cases. However, quick scaffolding is important for many organizational use cases. 5 | //! Especially when sane defaults are appreciated, setting up your own executor is a waste of 6 | //! time. 7 | //! 8 | //! This crate provides macros for setting up an efficient [`smol`] runtime quickly and 9 | //! effectively. It provides sane defaults that are useful for most applications. 10 | //! 11 | //! ## Simple Executor 12 | //! 13 | //! Just have an `async` main function, using the [`main`] macro. 14 | //! 15 | //! 16 | //! ``` 17 | //! use smol_macros::main; 18 | //! 19 | //! main! { 20 | //! async fn main() { 21 | //! println!("Hello, world!"); 22 | //! } 23 | //! } 24 | //! ``` 25 | //! 26 | //! This crate uses declarative macros rather than procedural macros, in order to avoid needing 27 | //! to use heavy macro dependencies. If you want to use the proc macro syntax, you can use the 28 | //! [`macro_rules_attribute::apply`] function to emulate it. 29 | //! 30 | //! The following is equivalent to the previous example. 31 | //! 32 | //! ``` 33 | //! use macro_rules_attribute::apply; 34 | //! use smol_macros::main; 35 | //! 36 | //! #[apply(main!)] 37 | //! async fn main() { 38 | //! println!("Hello, world!"); 39 | //! } 40 | //! ``` 41 | //! 42 | //! ## Task-Based Executor 43 | //! 44 | //! This crate re-exports [`smol::Executor`]. If that is used as the first parameter in a 45 | //! function in [`main`], it will automatically create the executor. 46 | //! 47 | //! ``` 48 | //! use macro_rules_attribute::apply; 49 | //! use smol_macros::{main, Executor}; 50 | //! 51 | //! #[apply(main!)] 52 | //! async fn main(ex: &Executor<'_>) { 53 | //! ex.spawn(async { println!("Hello world!"); }).await; 54 | //! } 55 | //! ``` 56 | //! 57 | //! If the thread-safe [`smol::Executor`] is used here, a thread pool will be spawned to run 58 | //! the executor on multiple threads. For the thread-unsafe [`smol::LocalExecutor`], no threads 59 | //! will be spawned. 60 | //! 61 | //! See documentation for the [`main`] function for more details. 62 | //! 63 | //! ## Tests 64 | //! 65 | //! Use the [`test`] macro to set up test cases that run self-contained executors. 66 | //! 67 | //! ``` 68 | //! use macro_rules_attribute::apply; 69 | //! use smol_macros::{test, Executor}; 70 | //! 71 | //! #[apply(test!)] 72 | //! async fn do_test(ex: &Executor<'_>) { 73 | //! ex.spawn(async { 74 | //! assert_eq!(1 + 1, 2); 75 | //! }).await; 76 | //! } 77 | //! ``` 78 | //! 79 | //! [`smol`]: https://crates.io/crates/smol 80 | //! [`smol::Executor`]: https://docs.rs/smol/latest/smol/struct.Executor.html 81 | //! [`smol::LocalExecutor`]: https://docs.rs/smol/latest/smol/struct.LocalExecutor.html 82 | //! [`macro_rules_attribute::apply`]: https://docs.rs/macro_rules_attribute/latest/macro_rules_attribute/attr.apply.html 83 | 84 | #![forbid(unsafe_code)] 85 | 86 | #[doc(no_inline)] 87 | pub use async_executor::{Executor, LocalExecutor}; 88 | 89 | /// Turn a main function into one that runs inside of a self-contained executor. 90 | /// 91 | /// The function created by this macro spawns an executor, spawns threads to run that executor 92 | /// on (if applicable), and then blocks the current thread on the future. 93 | /// 94 | /// ## Examples 95 | /// 96 | /// Like [`tokio::main`], this function is not limited to wrapping the program's entry point. 97 | /// In a mostly synchronous program, it can wrap a self-contained `async` function in its 98 | /// own executor. 99 | /// 100 | /// ``` 101 | /// use macro_rules_attribute::apply; 102 | /// use smol_macros::{main, Executor}; 103 | /// 104 | /// fn do_something_sync() -> u32 { 105 | /// 1 + 1 106 | /// } 107 | /// 108 | /// #[apply(main!)] 109 | /// async fn do_something_async(ex: &Executor<'_>) -> u32 { 110 | /// ex.spawn(async { 1 + 1 }).await 111 | /// } 112 | /// 113 | /// fn main() { 114 | /// let x = do_something_sync(); 115 | /// let y = do_something_async(); 116 | /// assert_eq!(x + y, 4); 117 | /// } 118 | /// ``` 119 | /// 120 | /// The first parameter to the `main` function can be an executor. It can be one of the following: 121 | /// 122 | /// - Nothing. 123 | /// - `&`[`Executor`] 124 | /// - `&`[`LocalExecutor`] 125 | /// - `Arc<`[`Executor`]`>` 126 | /// - `Rc<`[`LocalExecutor`]`>` 127 | /// 128 | /// [`tokio::main`]: https://docs.rs/tokio/latest/tokio/attr.main.html 129 | /// [`Executor`]: https://docs.rs/smol/latest/smol/struct.Executor.html 130 | /// [`LocalExecutor`]: https://docs.rs/smol/latest/smol/struct.LocalExecutor.html 131 | #[macro_export] 132 | macro_rules! main { 133 | ( 134 | $(#[$attr:meta])* 135 | async fn $name:ident () $(-> $ret:ty)? $bl:block 136 | ) => { 137 | $(#[$attr])* 138 | fn $name () $(-> $ret)? { 139 | $crate::__private::block_on(async { 140 | $bl 141 | }) 142 | } 143 | }; 144 | 145 | ( 146 | $(#[$post_attr:meta])* 147 | async fn $name:ident ($ex:ident : & $exty:ty) 148 | $(-> $ret:ty)? $bl:block 149 | ) => { 150 | $(#[$post_attr])* 151 | fn $name () $(-> $ret)? { 152 | <$exty as $crate::__private::MainExecutor>::with_main(|ex| { 153 | $crate::__private::block_on(ex.run(async move { 154 | let $ex = ex; 155 | $bl 156 | })) 157 | }) 158 | } 159 | }; 160 | 161 | ( 162 | $(#[$post_attr:meta])* 163 | async fn $name:ident ($ex:ident : $exty:ty) 164 | $(-> $ret:ty)? $bl:block 165 | ) => { 166 | $crate::main! { 167 | $(#[$post_attr])* 168 | async fn $name(ex: &$exty) $(-> $ret)? { 169 | let $ex = ex.clone(); 170 | $bl 171 | } 172 | } 173 | } 174 | } 175 | 176 | /// Wrap a test in an asynchronous executor. 177 | /// 178 | /// This is equivalent to the [`main`] macro, but adds the `#[test]` attribute. 179 | /// 180 | /// ## Examples 181 | /// 182 | /// ``` 183 | /// use macro_rules_attribute::apply; 184 | /// use smol_macros::test; 185 | /// 186 | /// #[apply(test!)] 187 | /// async fn do_test() { 188 | /// assert_eq!(1 + 1, 2); 189 | /// } 190 | /// ``` 191 | #[macro_export] 192 | macro_rules! test { 193 | // Special case to get around bug in macro engine. 194 | ( 195 | $(#[$post_attr:meta])* 196 | async fn $name:ident ($exname:ident : & $exty:ty) 197 | $(-> $ret:ty)? $bl:block 198 | ) => { 199 | $crate::main! { 200 | $(#[$post_attr])* 201 | #[core::prelude::v1::test] 202 | async fn $name($exname: &$exty) $(-> $ret)? $bl 203 | } 204 | }; 205 | 206 | ( 207 | $(#[$post_attr:meta])* 208 | async fn $name:ident ($($pname:ident : $pty:ty),* $(,)?) 209 | $(-> $ret:ty)? $bl:block 210 | ) => { 211 | $crate::main! { 212 | $(#[$post_attr])* 213 | #[core::prelude::v1::test] 214 | async fn $name($($pname: $pty),*) $(-> $ret)? $bl 215 | } 216 | }; 217 | } 218 | 219 | #[doc(hidden)] 220 | pub mod __private { 221 | pub use async_io::block_on; 222 | pub use std::rc::Rc; 223 | 224 | use crate::{Executor, LocalExecutor}; 225 | use event_listener::Event; 226 | use std::sync::atomic::{AtomicBool, Ordering}; 227 | use std::sync::Arc; 228 | use std::thread; 229 | 230 | /// Something that can be set up as an executor. 231 | #[doc(hidden)] 232 | pub trait MainExecutor: Sized { 233 | /// Create this type and pass it into `main`. 234 | fn with_main T>(f: F) -> T; 235 | } 236 | 237 | impl MainExecutor for Arc> { 238 | #[inline] 239 | fn with_main T>(f: F) -> T { 240 | let ex = Arc::new(Executor::new()); 241 | with_thread_pool(&ex, || f(&ex)) 242 | } 243 | } 244 | 245 | impl MainExecutor for Executor<'_> { 246 | #[inline] 247 | fn with_main T>(f: F) -> T { 248 | let ex = Executor::new(); 249 | with_thread_pool(&ex, || f(&ex)) 250 | } 251 | } 252 | 253 | impl MainExecutor for Rc> { 254 | #[inline] 255 | fn with_main T>(f: F) -> T { 256 | f(&Rc::new(LocalExecutor::new())) 257 | } 258 | } 259 | 260 | impl MainExecutor for LocalExecutor<'_> { 261 | fn with_main T>(f: F) -> T { 262 | f(&LocalExecutor::new()) 263 | } 264 | } 265 | 266 | /// Run a function that takes an `Executor` inside of a thread pool. 267 | #[inline] 268 | fn with_thread_pool(ex: &Executor<'_>, f: impl FnOnce() -> T) -> T { 269 | let stopper = WaitForStop::new(); 270 | 271 | // Create a thread for each CPU. 272 | thread::scope(|scope| { 273 | let num_threads = thread::available_parallelism().map_or(1, |num| num.get()); 274 | for i in 0..num_threads { 275 | let ex = &ex; 276 | let stopper = &stopper; 277 | 278 | thread::Builder::new() 279 | .name(format!("smol-macros-{i}")) 280 | .spawn_scoped(scope, || { 281 | block_on(ex.run(stopper.wait())); 282 | }) 283 | .expect("failed to spawn thread"); 284 | } 285 | 286 | let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)); 287 | 288 | stopper.stop(); 289 | 290 | match result { 291 | Ok(value) => value, 292 | Err(err) => std::panic::resume_unwind(err), 293 | } 294 | }) 295 | } 296 | 297 | /// Wait for the executor to stop. 298 | struct WaitForStop { 299 | /// Whether or not we need to stop. 300 | stopped: AtomicBool, 301 | 302 | /// Wait for the stop. 303 | events: Event, 304 | } 305 | 306 | impl WaitForStop { 307 | /// Create a new wait for stop. 308 | #[inline] 309 | fn new() -> Self { 310 | Self { 311 | stopped: AtomicBool::new(false), 312 | events: Event::new(), 313 | } 314 | } 315 | 316 | /// Wait for the event to stop. 317 | #[inline] 318 | async fn wait(&self) { 319 | loop { 320 | if self.stopped.load(Ordering::Relaxed) { 321 | return; 322 | } 323 | 324 | event_listener::listener!(&self.events => listener); 325 | 326 | if self.stopped.load(Ordering::Acquire) { 327 | return; 328 | } 329 | 330 | listener.await; 331 | } 332 | } 333 | 334 | /// Stop the waiter. 335 | #[inline] 336 | fn stop(&self) { 337 | self.stopped.store(true, Ordering::SeqCst); 338 | self.events.notify_additional(usize::MAX); 339 | } 340 | } 341 | } 342 | -------------------------------------------------------------------------------- /tests/macro_usages.rs: -------------------------------------------------------------------------------- 1 | //! Testing the test macros. 2 | 3 | use async_lock::Barrier; 4 | use futures_lite::prelude::*; 5 | use macro_rules_attribute::apply; 6 | use smol_macros::{test, Executor, LocalExecutor}; 7 | 8 | use std::rc::Rc; 9 | use std::sync::Arc; 10 | use std::time::Duration; 11 | 12 | test! { 13 | async fn basic_test() { 14 | println!("test 1"); 15 | } 16 | } 17 | 18 | #[apply(test!)] 19 | async fn with_attribute() { 20 | println!("test 2"); 21 | } 22 | 23 | #[apply(test!)] 24 | async fn with_executor(ex: &Executor<'static>) { 25 | let barrier = Arc::new(Barrier::new(2)); 26 | ex.spawn({ 27 | let barrier = barrier.clone(); 28 | async move { 29 | barrier.wait().await; 30 | } 31 | }) 32 | .detach(); 33 | barrier 34 | .wait() 35 | .or(async { 36 | async_io::Timer::after(Duration::from_secs(5)).await; 37 | panic!("timed out") 38 | }) 39 | .await; 40 | } 41 | 42 | #[apply(test!)] 43 | async fn with_executor_arc(ex: Arc>) { 44 | let barrier = Arc::new(Barrier::new(2)); 45 | ex.spawn({ 46 | let barrier = barrier.clone(); 47 | async move { 48 | barrier.wait().await; 49 | } 50 | }) 51 | .detach(); 52 | barrier 53 | .wait() 54 | .or(async { 55 | async_io::Timer::after(Duration::from_secs(5)).await; 56 | panic!("timed out") 57 | }) 58 | .await; 59 | } 60 | 61 | #[apply(test!)] 62 | async fn with_executor_arcref(ex: &Arc>) { 63 | let barrier = Arc::new(Barrier::new(2)); 64 | ex.spawn({ 65 | let barrier = barrier.clone(); 66 | async move { 67 | barrier.wait().await; 68 | } 69 | }) 70 | .detach(); 71 | barrier 72 | .wait() 73 | .or(async { 74 | async_io::Timer::after(Duration::from_secs(5)).await; 75 | panic!("timed out") 76 | }) 77 | .await; 78 | } 79 | 80 | #[apply(test!)] 81 | async fn with_local(ex: &LocalExecutor<'_>) { 82 | let barrier = Rc::new(unsend::lock::Barrier::new(2)); 83 | ex.spawn({ 84 | let barrier = barrier.clone(); 85 | async move { 86 | barrier.wait().await; 87 | } 88 | }) 89 | .detach(); 90 | barrier 91 | .wait() 92 | .or(async { 93 | async_io::Timer::after(Duration::from_secs(5)).await; 94 | panic!("timed out") 95 | }) 96 | .await; 97 | } 98 | 99 | #[apply(test!)] 100 | async fn with_local_rc(ex: Rc>) { 101 | let barrier = Rc::new(unsend::lock::Barrier::new(2)); 102 | ex.spawn({ 103 | let barrier = barrier.clone(); 104 | async move { 105 | barrier.wait().await; 106 | } 107 | }) 108 | .detach(); 109 | barrier 110 | .wait() 111 | .or(async { 112 | async_io::Timer::after(Duration::from_secs(5)).await; 113 | panic!("timed out") 114 | }) 115 | .await; 116 | } 117 | 118 | #[apply(test!)] 119 | async fn with_local_rcref(ex: &Rc>) { 120 | let barrier = Rc::new(unsend::lock::Barrier::new(2)); 121 | ex.spawn({ 122 | let barrier = barrier.clone(); 123 | async move { 124 | barrier.wait().await; 125 | } 126 | }) 127 | .detach(); 128 | barrier 129 | .wait() 130 | .or(async { 131 | async_io::Timer::after(Duration::from_secs(5)).await; 132 | panic!("timed out") 133 | }) 134 | .await; 135 | } 136 | 137 | #[apply(test!)] 138 | async fn it_works(_ex: &Executor<'_>) -> Result<(), Box> { 139 | let _ = u32::try_from(20usize)?; 140 | Ok(()) 141 | } 142 | --------------------------------------------------------------------------------