├── .commitlintrc.yml ├── .github ├── dependabot.yml └── workflows │ ├── ci.yml │ ├── pr_title.yml │ └── release.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── deny.toml ├── macros ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src │ ├── desugar_if_async.rs │ └── lib.rs ├── release-plz.toml ├── rustfmt.toml └── tests ├── Cargo.toml └── src ├── lib.rs └── tests ├── fail ├── misuse-of-underscore-async.rs ├── misuse-of-underscore-async.stderr ├── no-async-fn.rs ├── no-async-fn.stderr ├── no-impl.rs ├── no-impl.stderr ├── no-macro-args.rs ├── no-macro-args.stderr ├── no-struct.rs ├── no-struct.stderr ├── no-trait.rs └── no-trait.stderr └── pass ├── fun-with-types.rs ├── generic-fn-with-visibility.rs ├── generic-fn.rs └── struct-method-generic.rs /.commitlintrc.yml: -------------------------------------------------------------------------------- 1 | rules: 2 | # Body may be empty 3 | body-empty: 4 | level: ignore 5 | 6 | # Description must not be empty 7 | description-empty: 8 | level: error 9 | 10 | # Description must start with a capital letter and must not end with a period or space 11 | description-format: 12 | level: error 13 | format: ^[A-Z0-9].*[^. ]$ 14 | 15 | # Description should be <70 chars 16 | description-max-length: 17 | level: warning 18 | length: 70 19 | 20 | # Scope is not allowed 21 | scope: 22 | level: error 23 | options: [] 24 | 25 | # Subject line should exist 26 | subject-empty: 27 | level: error 28 | 29 | # Type must be one of these options 30 | type: 31 | level: error 32 | options: 33 | - fix 34 | - feat 35 | - chore 36 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | updates: 4 | - package-ecosystem: "cargo" 5 | directory: "macros" 6 | schedule: 7 | interval: "daily" 8 | commit-message: 9 | prefix: "update" 10 | 11 | - package-ecosystem: "github-actions" 12 | directory: "/" 13 | schedule: 14 | interval: "weekly" 15 | commit-message: 16 | prefix: "chore" 17 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | workflow_dispatch: 5 | pull_request: 6 | types: 7 | - opened 8 | - reopened 9 | - synchronize 10 | push: 11 | branches: main 12 | schedule: 13 | - cron: "0 18 * * 1,4,6" # 1800 UTC every Monday, Thursday, Saturday 14 | 15 | jobs: 16 | tests: 17 | name: Unit tests 18 | runs-on: ${{ matrix.os }} 19 | 20 | strategy: 21 | fail-fast: false 22 | matrix: 23 | os: [ubuntu-latest] 24 | rust_version: [stable, 1.70.0] 25 | 26 | steps: 27 | - name: Checkout repository 28 | uses: actions/checkout@v4 29 | 30 | - name: Install Rust toolchain 31 | uses: dtolnay/rust-toolchain@master 32 | with: 33 | toolchain: ${{ matrix.rust_version }} 34 | 35 | - name: Cache Rust dependencies 36 | uses: Swatinem/rust-cache@v2 37 | 38 | - name: Run tests 39 | run: cargo test --all-targets --all-features 40 | 41 | clippy_check: 42 | name: Clippy 43 | runs-on: ubuntu-latest 44 | steps: 45 | - name: Checkout repository 46 | uses: actions/checkout@v4 47 | 48 | - name: Install Rust toolchain 49 | uses: dtolnay/rust-toolchain@stable 50 | with: 51 | components: clippy 52 | 53 | - name: Cache Rust dependencies 54 | uses: Swatinem/rust-cache@v2 55 | 56 | - name: Run Clippy 57 | run: cargo clippy --all-features --all-targets -- -Dwarnings 58 | 59 | cargo_fmt: 60 | name: Enforce Rust code format 61 | runs-on: ubuntu-latest 62 | steps: 63 | - name: Checkout repository 64 | uses: actions/checkout@v4 65 | 66 | - name: Install stable toolchain 67 | uses: dtolnay/rust-toolchain@nightly 68 | with: 69 | components: rustfmt 70 | 71 | - name: Check format 72 | run: cargo +nightly fmt --all -- --check 73 | 74 | docs_rs: 75 | name: Preflight docs.rs build 76 | runs-on: ubuntu-latest 77 | steps: 78 | - name: Checkout repository 79 | uses: actions/checkout@v4 80 | 81 | - name: Install nightly Rust toolchain 82 | # Nightly is used here because the docs.rs build 83 | # uses nightly and we use doc_cfg features that are 84 | # not in stable Rust as of this writing (Rust 1.72). 85 | uses: dtolnay/rust-toolchain@nightly 86 | 87 | - name: Run cargo docs 88 | # This is intended to mimic the docs.rs build 89 | # environment. The goal is to fail PR validation 90 | # if the subsequent release would result in a failed 91 | # documentation build on docs.rs. 92 | run: cargo +nightly doc --all-features --no-deps 93 | env: 94 | RUSTDOCFLAGS: --cfg docsrs 95 | DOCS_RS: 1 96 | 97 | cargo-deny: 98 | name: License / vulnerability audit 99 | runs-on: ubuntu-latest 100 | 101 | strategy: 102 | fail-fast: false 103 | matrix: 104 | checks: 105 | - advisories 106 | - bans licenses sources 107 | 108 | # Prevent sudden announcement of a new advisory from failing CI: 109 | continue-on-error: ${{ matrix.checks == 'advisories' }} 110 | 111 | steps: 112 | - name: Checkout repository 113 | uses: actions/checkout@v4 114 | 115 | - name: Audit crate dependencies 116 | uses: EmbarkStudios/cargo-deny-action@v2 117 | with: 118 | command: check ${{ matrix.checks }} 119 | 120 | unused_deps: 121 | name: Check for unused dependencies 122 | runs-on: ubuntu-latest 123 | steps: 124 | - name: Checkout repository 125 | uses: actions/checkout@v4 126 | 127 | - name: Install Rust toolchain 128 | uses: dtolnay/rust-toolchain@nightly 129 | 130 | - name: Run cargo-udeps 131 | uses: aig787/cargo-udeps-action@v1 132 | with: 133 | version: latest 134 | args: --all-targets --all-features 135 | -------------------------------------------------------------------------------- /.github/workflows/pr_title.yml: -------------------------------------------------------------------------------- 1 | name: PR title 2 | 3 | on: 4 | pull_request: 5 | types: [opened, synchronize, reopened, edited] 6 | 7 | jobs: 8 | title_cc_validation: 9 | name: Conventional commits validation 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - name: Checkout repository 14 | uses: actions/checkout@v4 15 | 16 | - name: Check PR title 17 | env: 18 | PR_TITLE: ${{ github.event.pull_request.title }} 19 | run: | 20 | # If this step fails, please expand this step for more information. 21 | # 22 | # You will need to revise this pull request's title to 23 | # match the "summary" (first) line of a Conventional Commit message. 24 | # This enables us to automatically generate a meaningful changelog. 25 | # 26 | # The summary line (and thus the PR title) must have this exact format 27 | # (including punctuation): 28 | # 29 | # type: description 30 | # 31 | # `type` describes the nature of changes you are making. This project 32 | # requires the type to be one of these exact names: 33 | # 34 | # * fix 35 | # * feat (will cause a minor version bump) 36 | # * chore (will be omitted from changelog) 37 | # 38 | # NOTE: Conventional Commits also defines a `(scope)` parameter 39 | # which can define a sub-area within the project where the change was 40 | # made. This project is configured to disallow the use of `scope`. 41 | # 42 | # `description` is a short human-readable summary of the changes being made. 43 | # 44 | # This project enforces a few rules over and above the Conventional 45 | # Commits definition of `description`: 46 | # 47 | # * The `description` must be non-empty. 48 | # * The `description` must start with a capital letter or number. 49 | # (Do not start `description` with a lower-case word.) 50 | # * The `description` must not end with a period. 51 | # 52 | # This project does not currently enforce the following items, but 53 | # we ask that you observe the following preferences in `description`: 54 | # 55 | # * The entire description should be written and capitalized as 56 | # an English-language sentence, except (as noted earlier) that 57 | # the trailing period must be omitted. 58 | # * Any acronyms such as JSON or YAML should be capitalized as per 59 | # commonusage in English-language sentences. 60 | # 61 | # After you edit the PR title, this task will run again and the 62 | # warning should go away if you have made acceptable changes. 63 | # 64 | # For more information on Conventional Commits, please see: 65 | # 66 | # https://www.conventionalcommits.org/en/v1.0.0/ 67 | # 68 | # ------------ (end of message) ------------ 69 | 70 | if echo "$PR_TITLE" | grep -E '^chore(\(.*\))?: release '; then 71 | echo "Exception / OK: chore release pattern" 72 | exit 0; 73 | fi 74 | 75 | if echo "$PR_TITLE" | grep -E '^chore(\(deps\))?: bump '; then 76 | echo "Exception / OK: Dependabot update pattern" 77 | exit 0; 78 | fi 79 | 80 | echo "Installing commitlint-rs. Please wait 30-40 seconds ..." 81 | cargo install --quiet commitlint-rs 82 | set -e 83 | 84 | echo   85 | echo   86 | echo --- commitlint results for PR title \"$PR_TITLE\" --- 87 | echo   88 | 89 | echo "$PR_TITLE" | commitlint -g .commitlintrc.yml 90 | 91 | echo "✅ PR title matches all enforced rules." 92 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release-plz 2 | 3 | permissions: 4 | pull-requests: write 5 | contents: write 6 | 7 | on: 8 | push: 9 | branches: 10 | - main 11 | 12 | jobs: 13 | release-plz: 14 | name: Release-plz 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - name: Checkout repository 19 | uses: actions/checkout@v4 20 | with: 21 | fetch-depth: 0 22 | token: ${{ secrets.RELEASE_PLZ_TOKEN }} 23 | 24 | - name: Install Rust toolchain 25 | uses: dtolnay/rust-toolchain@stable 26 | 27 | - name: Run release-plz 28 | uses: MarcoIeni/release-plz-action@v0.5 29 | env: 30 | GITHUB_TOKEN: ${{ secrets.RELEASE_PLZ_TOKEN }} 31 | CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | 3 | Cargo.lock 4 | 5 | **/*.rs.bk 6 | 7 | .DS_Store 8 | .idea 9 | .vscode 10 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html), except that – as is typical in the Rust community – the minimum supported Rust version may be increased without a major version increase. 6 | 7 | Since version 1.1.1, the format of this changelog is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). 8 | 9 | ## [1.1.2](https://github.com/scouten/async-generic/compare/async-generic-v1.1.1...async-generic-v1.1.2) 10 | _28 September 2024_ 11 | 12 | ### Fixed 13 | 14 | * Include license files in published crates ([#13](https://github.com/scouten/async-generic/pull/13)) 15 | 16 | ## [1.1.1](https://github.com/scouten/async-generic/compare/async-generic-v1.1.0...async-generic-v1.1.1) 17 | _30 August 2024_ 18 | 19 | ### Other 20 | * Start using [release-plz](https://release-plz.ieni.dev) to manage releases 21 | 22 | ## 1.1.0 23 | _29 March 2024_ 24 | 25 | * Bump MSRV to 1.70.0 ([#4](https://github.com/scouten/sync-generic/pull/4)) 26 | 27 | ## 1.0.0 28 | _26 December 2023_ 29 | 30 | * Prepare for 1.0 release ([#2](https://github.com/scouten/sync-generic/pull/2)) 31 | 32 | ## 0.1.2 33 | _28 September 2023_ 34 | 35 | * Set MSRV to 1.67.0 ([#1](https://github.com/scouten/sync-generic/pull/1)) 36 | 37 | ## 0.1.1 38 | _22 September 2023_ 39 | 40 | * Fix incorrect README 41 | 42 | ## 0.1.0 43 | _22 September 2023_ 44 | 45 | * Initial public release 46 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | resolver = "2" 3 | members = ["macros", "tests"] 4 | -------------------------------------------------------------------------------- /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 2023 Eric Scouten 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 | MIT License 2 | 3 | © Copyright 2023 Eric Scouten. All rights reserved. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # async-generic 2 | 3 | Write code that can be both async and synchronous without duplicating it. 4 | 5 | ## Why solve this problem now? 6 | 7 | This macro set is intended as an interim solution for the problem space that will eventually be covered by the Rust [Keyword Generic Initiative](https://blog.rust-lang.org/inside-rust/2022/07/27/keyword-generics.html). 8 | 9 | As of this writing (September 2023), the official [status of that project](https://github.com/rust-lang/keyword-generics-initiative) is listed as still in the "Experimental" stage, so deployment in the language is still likely many months away if not longer. 10 | 11 | So ... what do we do _now_ if we need async-generic code? We build our own, using proc macros. And that's exactly what this crate is. 12 | 13 | I'll happily mark this crate as deprecated when keyword generics land officially in the language. Until then, hopefully it solves some problems for you, too! 14 | 15 | IMPORTANT: This crate is quite simple, so I expect there will be few releases beyond the 1.0.0 release. If you encounter issues, pelase do file them here; I use this crate routinely in other projects and will be watching, even if I don't update it regularly. 16 | 17 | ## User's guide 18 | 19 | The `async_generic` crate introduces a single proc macro also named `async_generic` which can be applied as an attribute to any function (either inside a struct or not). 20 | 21 | The macro outputs _two_ versions of the function, one synchronous and one that's async. The functions are identical to each other, except as follows: 22 | 23 | * When writing the async flavor of the function, the macro inserts the `async` modifier for you and renames the function (to avoid a name collision) by adding an `_async` suffix to the existing function name. 24 | * The attribute macro _may_ contain an `async_signature` argument. If that exists, the async function's argument parameters are replaced. (See example below.) 25 | * You can write `if _sync` or `if _async` blocks inside this block. The contents of these blocks will only appear in the corresponding sync or async flavors of the functions. You _may_ specify an `else` clause, which will only appear in the opposite flavor of the function. You may not combine `_sync` or `_async` with any other expression. (These aren't _really_ variables in the function scope, and they will cause "undefined identifier" errors if you try that.) 26 | 27 | A simple example: 28 | 29 | ```rust 30 | use async_generic::async_generic; 31 | 32 | #[async_generic] 33 | fn do_stuff() -> String { 34 | // Also: async fn do_stuff_async() -> String {...} 35 | if _async { 36 | my_async_stuff().await 37 | } else { 38 | "not async".to_owned() 39 | } 40 | } 41 | 42 | async fn my_async_stuff() -> String { 43 | "async".to_owned() 44 | } 45 | 46 | #[async_std::main] 47 | async fn main() { 48 | println!("sync => {}", do_stuff()); 49 | println!("async => {}", do_stuff_async().await); 50 | } 51 | ``` 52 | 53 | An example with different function arguments in the sync and async flavors: 54 | 55 | ```rust 56 | use async_generic::async_generic; 57 | 58 | #[async_generic(async_signature(thing: &AsyncThing))] 59 | fn do_stuff(thing: &SyncThing) -> String { 60 | // Also: async fn do_stuff_async(thing: &AsyncThing) -> String {...} 61 | if _async { 62 | thing.do_stuff().await 63 | } else { 64 | thing.do_stuff() 65 | } 66 | } 67 | 68 | struct SyncThing {} 69 | 70 | impl SyncThing { 71 | fn do_stuff(&self) -> String { 72 | "sync".to_owned() 73 | } 74 | } 75 | 76 | struct AsyncThing {} 77 | 78 | impl AsyncThing { 79 | async fn do_stuff(&self) -> String { 80 | "async".to_owned() 81 | } 82 | } 83 | 84 | #[async_std::main] 85 | async fn main() { 86 | let st = SyncThing {}; 87 | let at = AsyncThing {}; 88 | 89 | println!("sync => {}", do_stuff(&st)); 90 | println!("async => {}", do_stuff_async(&at).await); 91 | } 92 | ``` 93 | 94 | ## Why not use `maybe-async`? 95 | 96 | This crate is loosely derived from the excellent work of the [`maybe-async`](https://crates.io/crates/maybe-async) crate, but is intended to solve a subtly different problem. 97 | 98 | Use `maybe-async` when you know at compile-time whether each crate in your dependency tree will be used in an async or synchronous fashion. In that model, you can't have both at once. 99 | 100 | Use `async-generic` when you wish to have both async and synchronous versions of an API at the same time and want to reuse most of the implementation. 101 | -------------------------------------------------------------------------------- /deny.toml: -------------------------------------------------------------------------------- 1 | # Configuration used for dependency checking with cargo-deny. 2 | # 3 | # For further details on all configuration options see: 4 | # https://embarkstudios.github.io/cargo-deny/checks/cfg.html 5 | 6 | [graph] 7 | targets = [ 8 | { triple = "x86_64-unknown-linux-gnu" }, 9 | { triple = "x86_64-apple-darwin" }, 10 | { triple = "x86_64-pc-windows-msvc" }, 11 | { triple = "aarch64-apple-darwin" }, 12 | { triple = "wasm32-unknown-unknown" }, 13 | ] 14 | 15 | [advisories] 16 | yanked = "deny" 17 | 18 | [bans] 19 | multiple-versions = "allow" # "deny" 20 | # async-std (used in examples) still depends on syn 1.x 21 | 22 | [licenses] 23 | allow = [ 24 | "Apache-2.0", 25 | # "BSD-2-Clause", 26 | "BSD-3-Clause", 27 | # "CC0-1.0", 28 | # "ISC", 29 | # "LicenseRef-ring", 30 | "MIT", 31 | # "MPL-2.0", 32 | "Unicode-DFS-2016", 33 | # "Zlib", 34 | ] 35 | confidence-threshold = 0.9 36 | 37 | [sources] 38 | unknown-git = "deny" 39 | unknown-registry = "deny" 40 | -------------------------------------------------------------------------------- /macros/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "async-generic" 3 | version = "1.1.2" 4 | description = "Write code that can be both async and synchronous without duplicating it." 5 | authors = ["Eric Scouten "] 6 | license = "MIT OR Apache-2.0" 7 | documentation = "https://docs.rs/async-generic" 8 | homepage = "https://github.com/scouten/async-generic" 9 | repository = "https://github.com/scouten/async-generic" 10 | readme = "../README.md" 11 | keywords = ["async", "generic", "futures", "macros", "proc_macro"] 12 | edition = "2021" 13 | rust-version = "1.70.0" 14 | 15 | [lib] 16 | proc-macro = true 17 | 18 | [package.metadata.cargo-udeps.ignore] 19 | development = ["async-std", "async-trait"] 20 | 21 | [dependencies] 22 | proc-macro2 = "1.0" 23 | quote = "1.0" 24 | syn = { version = "2.0", features = ["visit-mut", "full"] } 25 | 26 | [dev-dependencies] 27 | async-std = { version = "1.0", features = ["attributes"] } 28 | async-trait = "0.1" 29 | -------------------------------------------------------------------------------- /macros/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | ../LICENSE-APACHE -------------------------------------------------------------------------------- /macros/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | ../LICENSE-MIT -------------------------------------------------------------------------------- /macros/README.md: -------------------------------------------------------------------------------- 1 | # About this crate 2 | 3 | This crate is derived from the [`maybe-async` crate](https://github.com/fMeow/maybe-async-rs) as of September 2023. 4 | 5 | Many thanks to Guoli Lyu for their initial work on this problem space. 6 | -------------------------------------------------------------------------------- /macros/src/desugar_if_async.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::TokenStream; 2 | use quote::quote; 3 | use syn::{ 4 | parse_quote, 5 | visit_mut::{self, VisitMut}, 6 | Block, Expr, ExprBlock, File, 7 | }; 8 | 9 | pub struct DesugarIfAsync { 10 | pub is_async: bool, 11 | } 12 | 13 | impl DesugarIfAsync { 14 | pub fn desugar_if_async(&mut self, item: TokenStream) -> TokenStream { 15 | let mut syntax_tree: File = syn::parse(item.into()).unwrap(); 16 | self.visit_file_mut(&mut syntax_tree); 17 | quote!(#syntax_tree) 18 | } 19 | 20 | fn rewrite_if_async( 21 | &self, 22 | node: &mut Expr, 23 | then_branch: Block, 24 | else_branch: Option, 25 | expr_is_async: bool, 26 | ) { 27 | if expr_is_async == self.is_async { 28 | *node = Expr::Block(ExprBlock { 29 | attrs: vec![], 30 | label: None, 31 | block: then_branch, 32 | }); 33 | } else if let Some(else_expr) = else_branch { 34 | *node = else_expr; 35 | } else { 36 | *node = parse_quote! {{}}; 37 | } 38 | } 39 | } 40 | 41 | impl VisitMut for DesugarIfAsync { 42 | fn visit_expr_mut(&mut self, node: &mut Expr) { 43 | visit_mut::visit_expr_mut(self, node); 44 | 45 | if let Expr::If(expr_if) = &node { 46 | if let Expr::Path(ref var) = expr_if.cond.as_ref() { 47 | if let Some(first_segment) = var.path.segments.first() { 48 | if var.path.segments.len() == 1 { 49 | let name = first_segment.ident.to_string(); 50 | let then_branch = expr_if.then_branch.clone(); 51 | let else_branch = expr_if.else_branch.as_ref().map(|eb| *eb.1.clone()); 52 | match name.as_str() { 53 | "_async" => { 54 | self.rewrite_if_async(node, then_branch, else_branch, true); 55 | } 56 | "_sync" => { 57 | self.rewrite_if_async(node, then_branch, else_branch, false); 58 | } 59 | _ => {} 60 | } 61 | } 62 | } 63 | } 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /macros/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![deny(warnings)] 2 | #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg, doc_cfg_hide))] 3 | 4 | use proc_macro::{TokenStream, TokenTree}; 5 | use proc_macro2::{Ident, Span, TokenStream as TokenStream2, TokenTree as TokenTree2}; 6 | use quote::quote; 7 | use syn::{ 8 | parse::{Parse, ParseStream, Result}, 9 | parse_macro_input, Attribute, Error, ItemFn, Token, 10 | }; 11 | 12 | use crate::desugar_if_async::DesugarIfAsync; 13 | 14 | mod desugar_if_async; 15 | 16 | fn convert_sync_async( 17 | input: &mut Item, 18 | is_async: bool, 19 | alt_sig: Option, 20 | ) -> TokenStream2 { 21 | let item = &mut input.0; 22 | 23 | if is_async { 24 | item.sig.asyncness = Some(Token![async](Span::call_site())); 25 | item.sig.ident = Ident::new(&format!("{}_async", item.sig.ident), Span::call_site()); 26 | } 27 | 28 | let tokens = quote!(#item); 29 | 30 | let tokens = if let Some(alt_sig) = alt_sig { 31 | let mut found_fn = false; 32 | let mut found_args = false; 33 | 34 | let old_tokens = tokens.into_iter().map(|token| match &token { 35 | TokenTree2::Ident(i) => { 36 | found_fn = found_fn || &i.to_string() == "fn"; 37 | token 38 | } 39 | TokenTree2::Group(g) => { 40 | if found_fn && !found_args && g.delimiter() == proc_macro2::Delimiter::Parenthesis { 41 | found_args = true; 42 | return TokenTree2::Group(proc_macro2::Group::new( 43 | proc_macro2::Delimiter::Parenthesis, 44 | alt_sig.clone().into(), 45 | )); 46 | } 47 | token 48 | } 49 | _ => token, 50 | }); 51 | 52 | TokenStream2::from_iter(old_tokens) 53 | } else { 54 | tokens 55 | }; 56 | 57 | DesugarIfAsync { is_async }.desugar_if_async(tokens) 58 | } 59 | 60 | #[proc_macro_attribute] 61 | pub fn async_generic(args: TokenStream, input: TokenStream) -> TokenStream { 62 | let mut async_signature: Option = None; 63 | 64 | if !args.to_string().is_empty() { 65 | let mut atokens = args.into_iter(); 66 | loop { 67 | if let Some(TokenTree::Ident(i)) = atokens.next() { 68 | if i.to_string() != *"async_signature" { 69 | break; 70 | } 71 | } else { 72 | break; 73 | } 74 | 75 | if let Some(TokenTree::Group(g)) = atokens.next() { 76 | if atokens.next().is_none() && g.delimiter() == proc_macro::Delimiter::Parenthesis { 77 | async_signature = Some(g.stream()); 78 | } 79 | } 80 | } 81 | 82 | if async_signature.is_none() { 83 | return syn::Error::new( 84 | Span::call_site(), 85 | "async_generic can only take a async_signature argument", 86 | ) 87 | .to_compile_error() 88 | .into(); 89 | } 90 | }; 91 | 92 | let input_clone = input.clone(); 93 | let mut item = parse_macro_input!(input_clone as Item); 94 | let sync_tokens = convert_sync_async(&mut item, false, None); 95 | 96 | let mut item = parse_macro_input!(input as Item); 97 | let async_tokens = convert_sync_async(&mut item, true, async_signature); 98 | 99 | let mut tokens = sync_tokens; 100 | tokens.extend(async_tokens); 101 | tokens.into() 102 | } 103 | 104 | struct Item(ItemFn); 105 | 106 | impl Parse for Item { 107 | fn parse(input: ParseStream) -> Result { 108 | let attrs = input.call(Attribute::parse_outer)?; 109 | if let Ok(mut item) = input.parse::() { 110 | item.attrs = attrs; 111 | if item.sig.asyncness.is_some() { 112 | return Err(Error::new( 113 | Span::call_site(), 114 | "an async_generic function should not be declared as async", 115 | )); 116 | } 117 | Ok(Item(item)) 118 | } else { 119 | Err(Error::new( 120 | Span::call_site(), 121 | "async_generic can only be used with functions", 122 | )) 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /release-plz.toml: -------------------------------------------------------------------------------- 1 | [changelog] 2 | body = """ 3 | 4 | ## [{{ version | trim_start_matches(pat="v") }}]{%- if release_link -%}({{ release_link }}){% endif %} 5 | _{{ timestamp | date(format="%d %B %Y") }}_ 6 | {% for group, commits in commits | group_by(attribute="group") %} 7 | {% if group != "chore" -%} 8 | ### {{ group | upper_first }} 9 | 10 | {% for commit in commits -%} 11 | {%- if commit.scope and commit.scope != package -%} 12 | * *({{commit.scope}})* {% if commit.breaking %}[**breaking**] {% endif %}{{ commit.message | upper_first }}{%- if commit.links %} ({% for link in commit.links %}[{{link.text}}]({{link.href}}) {% endfor -%}){% endif %} 13 | {% else -%} 14 | * {% if commit.breaking %}[**breaking**] {% endif %}{{ commit.message | upper_first }} 15 | {% endif -%} 16 | {% endfor -%} 17 | {% endif -%} 18 | {% endfor -%} 19 | 20 | """ 21 | 22 | commit_parsers = [ 23 | { message = "^feat", group = "added" }, 24 | { message = "^changed", group = "changed" }, 25 | { message = "^deprecated", group = "deprecated" }, 26 | { message = "^fix", group = "fixed" }, 27 | { message = "^security", group = "security" }, 28 | { message = "^chore", group = "chore" }, 29 | { message = "^.*", group = "other" }, 30 | ] 31 | 32 | [workspace] 33 | dependencies_update = true 34 | features_always_increment_minor = true 35 | release_always = false 36 | release_commits = "^(feat|fix)[(:]" 37 | 38 | [[package]] 39 | name = "async-generic" 40 | changelog_path = "CHANGELOG.md" 41 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | # IMPORTANT: PR validation uses nightly version of 2 | # rustfmt. 3 | 4 | # Invoke by using: 5 | # 6 | # rustup toolchain add nightly 7 | # cargo +nightly fmt 8 | 9 | blank_lines_upper_bound = 1 10 | edition = "2021" 11 | empty_item_single_line = true 12 | format_code_in_doc_comments = true 13 | group_imports = "StdExternalCrate" 14 | hex_literal_case = "Lower" 15 | imports_granularity = "Crate" 16 | reorder_impl_items = true 17 | unstable_features = true 18 | wrap_comments = true 19 | -------------------------------------------------------------------------------- /tests/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tests" 3 | version = "0.1.0" 4 | edition = "2021" 5 | rust-version = "1.70.0" 6 | license = "MIT OR Apache-2.0" 7 | publish = false 8 | 9 | [lib] 10 | crate-type = ["lib"] 11 | 12 | [package.metadata.cargo-udeps.ignore] 13 | normal = [ 14 | "async-generic", 15 | "async-std", 16 | ] 17 | 18 | [dependencies] 19 | async-generic = { path = "../macros" } 20 | async-std = { version = "1.0", features = ["attributes"] } 21 | trybuild = { version = "1.0", features = ["diff"] } 22 | -------------------------------------------------------------------------------- /tests/src/lib.rs: -------------------------------------------------------------------------------- 1 | #[test] 2 | fn tests() { 3 | let t = trybuild::TestCases::new(); 4 | t.pass("src/tests/pass/fun-with-types.rs"); 5 | t.pass("src/tests/pass/generic-fn.rs"); 6 | t.pass("src/tests/pass/generic-fn-with-visibility.rs"); 7 | t.pass("src/tests/pass/struct-method-generic.rs"); 8 | 9 | t.compile_fail("src/tests/fail/misuse-of-underscore-async.rs"); 10 | t.compile_fail("src/tests/fail/no-async-fn.rs"); 11 | t.compile_fail("src/tests/fail/no-impl.rs"); 12 | t.compile_fail("src/tests/fail/no-macro-args.rs"); 13 | t.compile_fail("src/tests/fail/no-struct.rs"); 14 | t.compile_fail("src/tests/fail/no-trait.rs"); 15 | } 16 | -------------------------------------------------------------------------------- /tests/src/tests/fail/misuse-of-underscore-async.rs: -------------------------------------------------------------------------------- 1 | use async_generic::async_generic; 2 | 3 | #[async_generic] 4 | fn do_stuff() -> String { 5 | if _async && true { 6 | // ERROR: _async must stand alone in expression 7 | unreachable!(); 8 | } else { 9 | "not async".to_owned() 10 | } 11 | } 12 | 13 | async fn my_async_stuff() -> String { 14 | "async".to_owned() 15 | } 16 | 17 | fn main() {} 18 | -------------------------------------------------------------------------------- /tests/src/tests/fail/misuse-of-underscore-async.stderr: -------------------------------------------------------------------------------- 1 | error[E0425]: cannot find value `_async` in this scope 2 | --> src/tests/fail/misuse-of-underscore-async.rs:5:8 3 | | 4 | 5 | if _async && true { 5 | | ^^^^^^ not found in this scope 6 | -------------------------------------------------------------------------------- /tests/src/tests/fail/no-async-fn.rs: -------------------------------------------------------------------------------- 1 | use async_generic::async_generic; 2 | 3 | #[async_generic] 4 | async fn do_some_stuff() -> bool { 5 | // ERROR: async should not be specified on an async_generic fn. 6 | true 7 | } 8 | 9 | fn main() {} 10 | -------------------------------------------------------------------------------- /tests/src/tests/fail/no-async-fn.stderr: -------------------------------------------------------------------------------- 1 | error: an async_generic function should not be declared as async 2 | --> src/tests/fail/no-async-fn.rs:3:1 3 | | 4 | 3 | #[async_generic] 5 | | ^^^^^^^^^^^^^^^^ 6 | | 7 | = note: this error originates in the attribute macro `async_generic` (in Nightly builds, run with -Z macro-backtrace for more info) 8 | -------------------------------------------------------------------------------- /tests/src/tests/fail/no-impl.rs: -------------------------------------------------------------------------------- 1 | use async_generic::async_generic; 2 | 3 | trait Trait { 4 | // ERROR: async_generic can not be applied to traits 5 | fn do_stuff() {} 6 | } 7 | 8 | struct Struct {} 9 | 10 | #[async_generic] 11 | impl Trait for Struct {} 12 | 13 | fn main() {} 14 | -------------------------------------------------------------------------------- /tests/src/tests/fail/no-impl.stderr: -------------------------------------------------------------------------------- 1 | error: async_generic can only be used with functions 2 | --> src/tests/fail/no-impl.rs:10:1 3 | | 4 | 10 | #[async_generic] 5 | | ^^^^^^^^^^^^^^^^ 6 | | 7 | = note: this error originates in the attribute macro `async_generic` (in Nightly builds, run with -Z macro-backtrace for more info) 8 | -------------------------------------------------------------------------------- /tests/src/tests/fail/no-macro-args.rs: -------------------------------------------------------------------------------- 1 | use async_generic::async_generic; 2 | 3 | #[async_generic(Send)] 4 | fn do_stuff() -> String { 5 | if _async { 6 | my_async_stuff().await 7 | } else { 8 | "not async".to_owned() 9 | } 10 | } 11 | 12 | async fn my_async_stuff() -> String { 13 | "async".to_owned() 14 | } 15 | 16 | #[async_std::main] 17 | async fn main() {} 18 | -------------------------------------------------------------------------------- /tests/src/tests/fail/no-macro-args.stderr: -------------------------------------------------------------------------------- 1 | error: async_generic can only take a async_signature argument 2 | --> src/tests/fail/no-macro-args.rs:3:1 3 | | 4 | 3 | #[async_generic(Send)] 5 | | ^^^^^^^^^^^^^^^^^^^^^^ 6 | | 7 | = note: this error originates in the attribute macro `async_generic` (in Nightly builds, run with -Z macro-backtrace for more info) 8 | -------------------------------------------------------------------------------- /tests/src/tests/fail/no-struct.rs: -------------------------------------------------------------------------------- 1 | use async_generic::async_generic; 2 | 3 | #[async_generic] 4 | struct Struct {} 5 | 6 | fn main() {} 7 | -------------------------------------------------------------------------------- /tests/src/tests/fail/no-struct.stderr: -------------------------------------------------------------------------------- 1 | error: async_generic can only be used with functions 2 | --> src/tests/fail/no-struct.rs:3:1 3 | | 4 | 3 | #[async_generic] 5 | | ^^^^^^^^^^^^^^^^ 6 | | 7 | = note: this error originates in the attribute macro `async_generic` (in Nightly builds, run with -Z macro-backtrace for more info) 8 | -------------------------------------------------------------------------------- /tests/src/tests/fail/no-trait.rs: -------------------------------------------------------------------------------- 1 | use async_generic::async_generic; 2 | 3 | #[async_generic] 4 | trait Trait { 5 | // ERROR: async_generic can not be applied to traits 6 | fn do_stuff() {} 7 | } 8 | 9 | fn main() {} 10 | -------------------------------------------------------------------------------- /tests/src/tests/fail/no-trait.stderr: -------------------------------------------------------------------------------- 1 | error: async_generic can only be used with functions 2 | --> src/tests/fail/no-trait.rs:3:1 3 | | 4 | 3 | #[async_generic] 5 | | ^^^^^^^^^^^^^^^^ 6 | | 7 | = note: this error originates in the attribute macro `async_generic` (in Nightly builds, run with -Z macro-backtrace for more info) 8 | -------------------------------------------------------------------------------- /tests/src/tests/pass/fun-with-types.rs: -------------------------------------------------------------------------------- 1 | use async_generic::async_generic; 2 | 3 | #[async_generic(async_signature(thing: &AsyncThing))] 4 | fn do_stuff(thing: &SyncThing) -> String { 5 | if _async { 6 | thing.do_stuff().await 7 | } else { 8 | thing.do_stuff() 9 | } 10 | } 11 | 12 | struct SyncThing {} 13 | 14 | impl SyncThing { 15 | fn do_stuff(&self) -> String { 16 | "sync".to_owned() 17 | } 18 | } 19 | 20 | struct AsyncThing {} 21 | 22 | impl AsyncThing { 23 | async fn do_stuff(&self) -> String { 24 | "async".to_owned() 25 | } 26 | } 27 | 28 | #[async_std::main] 29 | async fn main() { 30 | let st = SyncThing {}; 31 | let at = AsyncThing {}; 32 | 33 | println!("sync => {}", do_stuff(&st)); 34 | println!("async => {}", do_stuff_async(&at).await); 35 | } 36 | -------------------------------------------------------------------------------- /tests/src/tests/pass/generic-fn-with-visibility.rs: -------------------------------------------------------------------------------- 1 | pub mod fun { 2 | use async_generic::async_generic; 3 | 4 | #[async_generic] 5 | pub fn do_stuff() -> String { 6 | if _async { 7 | my_async_stuff().await 8 | } else { 9 | "not async".to_owned() 10 | } 11 | } 12 | 13 | async fn my_async_stuff() -> String { 14 | "async".to_owned() 15 | } 16 | } 17 | 18 | mod test { 19 | pub async fn test() { 20 | println!("sync => {}", super::fun::do_stuff()); 21 | println!("async => {}", super::fun::do_stuff_async().await); 22 | } 23 | } 24 | 25 | #[async_std::main] 26 | async fn main() { 27 | test::test().await 28 | } 29 | -------------------------------------------------------------------------------- /tests/src/tests/pass/generic-fn.rs: -------------------------------------------------------------------------------- 1 | use async_generic::async_generic; 2 | 3 | #[async_generic] 4 | fn do_stuff() -> String { 5 | if _async { 6 | my_async_stuff().await 7 | } else { 8 | "not async".to_owned() 9 | } 10 | } 11 | 12 | async fn my_async_stuff() -> String { 13 | "async".to_owned() 14 | } 15 | 16 | #[async_std::main] 17 | async fn main() { 18 | println!("sync => {}", do_stuff()); 19 | println!("async => {}", do_stuff_async().await); 20 | } 21 | -------------------------------------------------------------------------------- /tests/src/tests/pass/struct-method-generic.rs: -------------------------------------------------------------------------------- 1 | use async_generic::async_generic; 2 | 3 | struct Struct {} 4 | 5 | impl Struct { 6 | #[async_generic] 7 | fn do_stuff(&self) -> String { 8 | if _async { 9 | self.my_async_stuff().await 10 | } else { 11 | "not async".to_owned() 12 | } 13 | } 14 | 15 | async fn my_async_stuff(&self) -> String { 16 | "async".to_owned() 17 | } 18 | } 19 | 20 | #[async_std::main] 21 | async fn main() { 22 | let s = Struct {}; 23 | println!("sync => {}", s.do_stuff()); 24 | println!("async => {}", s.do_stuff_async().await); 25 | } 26 | --------------------------------------------------------------------------------