task-local-extensions-0.1.4/.cargo_vcs_info.json0000644000000001360000000000100152650ustar { "git": { "sha1": "9a7d3c3000cb3de3c3283dbc2fc87087db984d23" }, "path_in_vcs": "" }task-local-extensions-0.1.4/.github/CODEOWNERS000064400000000000000000000000261046102023000170060ustar 00000000000000* @TrueLayer/rust-oss task-local-extensions-0.1.4/.github/ISSUE_TEMPLATE/bug_report.md000064400000000000000000000010311046102023000222650ustar 00000000000000--- name: Bug report about: Create a report to help us improve title: '' labels: bug assignees: '' --- ## Bug description ## To Reproduce ## Expected behavior ## Environment - OS: [e.g. Windows] - Rust version [e.g. 1.51.0] ## Additional context task-local-extensions-0.1.4/.github/ISSUE_TEMPLATE/config.yml000064400000000000000000000000331046102023000215640ustar 00000000000000blank_issues_enabled: true task-local-extensions-0.1.4/.github/ISSUE_TEMPLATE/feature_request.md000064400000000000000000000007441046102023000233320ustar 00000000000000--- name: Feature request about: Suggest an idea for this project title: '' labels: enhancement assignees: '' --- ## Motivations ## Solution ## Alternatives ## Additional context task-local-extensions-0.1.4/.github/PULL_REQUEST_TEMPLATE.md000064400000000000000000000007471046102023000212260ustar 00000000000000 task-local-extensions-0.1.4/.github/workflows/audit.yml000064400000000000000000000006201046102023000213010ustar 00000000000000name: Security audit on: schedule: # Runs at 00:00 UTC everyday - cron: '0 0 * * *' push: paths: - '**/Cargo.toml' - '**/Cargo.lock' pull_request: jobs: audit: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - uses: actions-rs/audit-check@v1 with: token: ${{ secrets.GITHUB_TOKEN }} task-local-extensions-0.1.4/.github/workflows/ci.yml000064400000000000000000000060131046102023000205700ustar 00000000000000on: push: branches: [main] pull_request: name: CI # Continuous Integration jobs: test: name: Test Suite runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install Rust uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal override: true - uses: actions-rs/cargo@v1 with: command: test args: --workspace --all-targets --all-features rustfmt: name: Rustfmt runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install Rust uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal override: true components: rustfmt - name: Check formatting uses: actions-rs/cargo@v1 with: command: fmt args: --all -- --check clippy: name: Clippy runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install Rust uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal override: true components: clippy - name: Clippy check uses: actions-rs/cargo@v1 with: command: clippy args: --all-targets --all-features --workspace -- -D warnings docs: name: Docs runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install Rust uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal override: true - name: Check documentation env: RUSTDOCFLAGS: -D warnings uses: actions-rs/cargo@v1 with: command: doc args: --no-deps --document-private-items --all-features --workspace publish-check: name: Publish dry run runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal override: true - uses: actions-rs/cargo@v1 with: command: publish args: --dry-run coverage: name: Code coverage runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install stable toolchain uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal override: true - name: Run cargo-tarpaulin uses: actions-rs/tarpaulin@v0.1 with: args: '--ignore-tests --out Lcov' - name: Upload to Coveralls # upload only if push if: ${{ github.event_name == 'push' }} uses: coverallsapp/github-action@master with: github-token: ${{ secrets.GITHUB_TOKEN }} path-to-lcov: './lcov.info' task-local-extensions-0.1.4/.gitignore000064400000000000000000000000311046102023000160370ustar 00000000000000target/ Cargo.lock .idea task-local-extensions-0.1.4/CHANGELOG.md000064400000000000000000000020761046102023000156730ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [0.1.4] - 2023-03-09 ### Changed - Switched out task-local impl from tokio to using a custom one. Allows for wasm32 compat now ## [0.1.3] - 2022-09-06 ### Changed - The internal representation of `Extensions` no longer uses an `IdHasher` and instead uses the default hasher in order to be safe in case the representation of `TypeId` changes in future ## [0.1.2] - 2022-08-30 ### Added - `with` method for builder pattern insertion - `append` method for combining two Extension sets ### Changed - The internal representation of `Extensions` to be a little more sensible ## [0.1.1] - 2021-08-31 ### Changed - Renamed going forward to `task-local-extensions` from `truelayer-extensions` ## [0.1.0] - 2021-08-11 ### Added - Initial version: `Extensions`, `with_extensions`, `get_local_item` and `set_local_item`. task-local-extensions-0.1.4/CODE_OF_CONDUCT.md000064400000000000000000000002121046102023000166470ustar 00000000000000# Code of Conduct This project adheres to the Rust Code of Conduct, which [can be found online](https://www.rust-lang.org/conduct.html). task-local-extensions-0.1.4/CONTRIBUTING.md000064400000000000000000000031471046102023000163130ustar 00000000000000# Contribution guidelines First off, thank you for considering contributing to task-local-extensions. If your contribution is not straightforward, please first discuss the change you wish to make by creating a new issue before making the change. ## Reporting issues Before reporting an issue on the [issue tracker](https://github.com/TrueLayer/task-local-extensions/issues), please check that it has not already been reported by searching for some related keywords. ## Pull requests Try to do one pull request per change. ### Updating the changelog Update the changes you have made in [CHANGELOG](https://github.com/TrueLayer/task-local-extensions/blob/master/CHANGELOG.md) file under the **Unreleased** section. Add the changes of your pull request to one of the following subsections, depending on the types of changes defined by [Keep a changelog](https://keepachangelog.com/en/1.0.0/): - `Added` for new features. - `Changed` for changes in existing functionality. - `Deprecated` for soon-to-be removed features. - `Removed` for now removed features. - `Fixed` for any bug fixes. - `Security` in case of vulnerabilities. If the required subsection does not exist yet under **Unreleased**, create it! ## Developing ### Set up This is no different than other Rust projects. ```shell git clone https://github.com/TrueLayer/task-local-extensions cd task-local-extensions cargo test ``` ### Useful Commands - Run Clippy: ```shell cargo clippy ``` - Check to see if there are code formatting issues ```shell cargo fmt --all -- --check ``` - Format the code in the project ```shell cargo fmt --all ``` task-local-extensions-0.1.4/Cargo.toml0000644000000017430000000000100132700ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "task-local-extensions" version = "0.1.4" authors = [ "Conrad Ludgate ", "Rodrigo Gryzinski ", ] description = "Task-local container for arbitrary data." readme = "README.md" keywords = [ "extensions", "typemap", ] license = "MIT OR Apache-2.0" repository = "https://github.com/TrueLayer/task-local-extensions" [dependencies.pin-utils] version = "0.1.0" [dev-dependencies.tokio] version = "1" features = ["full"] task-local-extensions-0.1.4/Cargo.toml.orig000064400000000000000000000007441046102023000167510ustar 00000000000000[package] name = "task-local-extensions" version = "0.1.4" authors = ["Conrad Ludgate ", "Rodrigo Gryzinski "] edition = "2018" description = "Task-local container for arbitrary data." repository = "https://github.com/TrueLayer/task-local-extensions" license = "MIT OR Apache-2.0" keywords = ["extensions", "typemap"] [dependencies] pin-utils = "0.1.0" [dev-dependencies] tokio = { version = "1", features = ["full"] } task-local-extensions-0.1.4/LICENSE-APACHE000064400000000000000000000227731046102023000160140ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS task-local-extensions-0.1.4/LICENSE-MIT000064400000000000000000000020521046102023000155100ustar 00000000000000MIT License Copyright (c) 2021 TrueLayer Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. task-local-extensions-0.1.4/README.md000064400000000000000000000043041046102023000153350ustar 00000000000000# task-local-extensions Provides a type-safe task-local container for arbitrary data keyed by types. [![Crates.io](https://img.shields.io/crates/v/task-local-extensions.svg)](https://crates.io/crates/task-local-extensions) [![Docs.rs](https://docs.rs/task-local-extensions/badge.svg)](https://docs.rs/task-local-extensions) [![CI](https://github.com/TrueLayer/task-local-extensions/workflows/CI/badge.svg)](https://github.com/TrueLayer/task-local-extensions/actions) [![Coverage Status](https://coveralls.io/repos/github/TrueLayer/task-local-extensions/badge.svg?branch=main&t=DdH5KB)](https://coveralls.io/github/TrueLayer/task-local-extensions?branch=main) ## How to install Add `task-local-extensions` to your dependencies ```toml [dependencies] # ... task-local-extensions = "0.1.0" ``` ## Usage [`Extensions`](https://docs.rs/task-local-extensions/latest/task_local_extensions/struct.Extensions.html) is a container that can store up to one value of each type, so you can insert and retrive values by their type: ```rust use task_local_extensions::Extensions; let a: i64 = 3; let mut ext = Extensions::new(); ext.insert(a); assert_eq!(ext.get::(), Some(&3)); ``` The crate also provides [`with_extensions`](https://docs.rs/task-local-extensions/latest/task_local_extensions/fn.with_extensions.html) so you set an `Extensions` instance while running a given task: ```rust use task_local_extensions::{get_local_item, set_local_item, with_extensions, Extensions}; async fn my_task() { let a: i64 = get_local_item().await.unwrap(0); let msg = format!("The value of a is: {}", a); set_local_item(msg).await; } let a: i64 = 3; let (out_ext, _) = with_extensions(Extensions::new().with(a), my_task()).await; let msg = out_ext.get::().unwrap(); assert_eq!(msg.as_str(), "The value of a is: 3"); ``` #### License Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. task-local-extensions-0.1.4/src/extensions.rs000064400000000000000000000073131046102023000174150ustar 00000000000000// Implementation is based on // - https://github.com/http-rs/http-types/blob/master/src/extensions.rs use std::any::{Any, TypeId}; use std::collections::HashMap; use std::fmt; /// `Extensions` is a type map: values are stored and retrieved using their /// [`TypeId`](https://doc.rust-lang.org/std/any/struct.TypeId.html). /// /// This allows storing arbitrary data that implements `Sync + Send + 'static`. This is /// useful when you need to share data between different middlewares in the middleware chain /// or make some values available from the handler to middlewares /// on the outgoing path (e.g. error class). #[derive(Default)] pub struct Extensions { map: HashMap>, } impl Extensions { /// Create an empty `Extensions`. pub fn new() -> Self { Self { map: HashMap::default(), } } /// Insert a value ino this [`Extensions`], returning self instead of any pre-inserted values. /// /// This is useful for any builder style patterns /// /// ``` /// # use task_local_extensions::Extensions; /// let ext = Extensions::new().with(true).with(5_i32); /// assert_eq!(ext.get(), Some(&true)); /// assert_eq!(ext.get(), Some(&5_i32)); /// ``` pub fn with(mut self, val: T) -> Self { self.insert(val); self } /// Removes the values from `other` and inserts them into `self`. pub fn append(&mut self, other: &mut Self) { self.map.extend(other.map.drain()) } /// Insert a value into this `Extensions`. /// /// If a value of this type already exists, it will be returned. pub fn insert(&mut self, val: T) -> Option { self.map .insert(TypeId::of::(), Box::new(val)) .and_then(|boxed| (boxed as Box).downcast().ok().map(|boxed| *boxed)) } /// Check if container contains value for type pub fn contains(&self) -> bool { self.map.get(&TypeId::of::()).is_some() } /// Get a reference to a value previously inserted on this `Extensions`. pub fn get(&self) -> Option<&T> { self.map .get(&TypeId::of::()) .and_then(|boxed| (&**boxed as &(dyn Any)).downcast_ref()) } /// Get a mutable reference to a value previously inserted on this `Extensions`. pub fn get_mut(&mut self) -> Option<&mut T> { self.map .get_mut(&TypeId::of::()) .and_then(|boxed| (&mut **boxed as &mut (dyn Any)).downcast_mut()) } /// Remove a value from this `Extensions`. /// /// If a value of this type exists, it will be returned. pub fn remove(&mut self) -> Option { self.map .remove(&TypeId::of::()) .and_then(|boxed| (boxed as Box).downcast().ok().map(|boxed| *boxed)) } /// Clear the `Extensions` of all inserted values. #[inline] pub fn clear(&mut self) { self.map.clear(); } } impl fmt::Debug for Extensions { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Extensions").finish() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_extensions() { #[derive(Debug, PartialEq)] struct MyType(i32); let mut map = Extensions::new(); map.insert(5i32); map.insert(MyType(10)); assert_eq!(map.get(), Some(&5i32)); assert_eq!(map.get_mut(), Some(&mut 5i32)); assert_eq!(map.remove::(), Some(5i32)); assert!(map.get::().is_none()); assert_eq!(map.get::(), None); assert_eq!(map.get(), Some(&MyType(10))); } } task-local-extensions-0.1.4/src/lib.rs000064400000000000000000000021461046102023000157630ustar 00000000000000//! A type map for storing data of arbritrary type. //! //! # Extensions //! [`Extensions`] is a container that can store up to one value of each type, so you can insert and retrive values by //! their type: //! //! ``` //! use task_local_extensions::Extensions; //! //! let a: i64 = 3; //! let mut ext = Extensions::new(); //! extensions.insert(a); //! assert_eq!(ext.get::(), Some(&3)); //! ``` //! //! # Task Local Extensions //! The crate also provides [`with_extensions`] so you set an [`Extensions`] instance while running a given task: //! //! ``` //! use task_local_extensions::{get_local_item, set_local_item, with_extensions, Extensions}; //! //! async fn my_task() { //! let a: i64 = get_local_item().await.unwrap(0); //! let msg = format!("The value of a is: {}", a); //! set_local_item(msg).await; //! } //! //! let a: i64 = 3; //! let (out_ext, _) = with_extensions(Extensions::new().with(a), my_task()).await; //! let msg = out_ext.get::().unwrap(); //! assert_eq!(msg.as_str(), "The value of a is: 3"); //! ``` mod extensions; mod task_local; pub use extensions::*; pub use task_local::*; task-local-extensions-0.1.4/src/task_local.rs000064400000000000000000000051761046102023000173370ustar 00000000000000// clippy bug wrongly flags the task_local macro as being bad. // a fix is already merged but hasn't made it upstream yet #![allow(clippy::declare_interior_mutable_const)] use crate::Extensions; use std::cell::RefCell; use std::future::Future; thread_local! { static EXTENSIONS: RefCell = RefCell::new(Extensions::new()); } /// Sets a task local to `Extensions` before `fut` is run, /// and fetches the contents of the task local Extensions after completion /// and returns it. pub async fn with_extensions( mut extensions: Extensions, fut: impl Future, ) -> (Extensions, T) { pin_utils::pin_mut!(fut); let res = std::future::poll_fn(|cx| { EXTENSIONS.with(|ext| { // swap in the extensions std::mem::swap(&mut extensions, &mut *ext.borrow_mut()); let res = fut.as_mut().poll(cx); // swap back std::mem::swap(&mut extensions, &mut *ext.borrow_mut()); res }) }) .await; (extensions, res) } /// Retrieve any item from task-local storage. // TODO: doesn't need to be async? pub async fn get_local_item() -> Option { EXTENSIONS .try_with(|e| e.borrow().get::().cloned()) .ok() .flatten() } /// Set an item in task-local storage. // TODO: doesn't need to be async? pub async fn set_local_item(item: T) { EXTENSIONS .try_with(|e| e.borrow_mut().insert(item)) .expect("Failed to set local item."); } #[cfg(test)] mod tests { use crate::{get_local_item, set_local_item, with_extensions, Extensions}; #[derive(Clone)] struct A; #[derive(Clone)] struct B; #[derive(Clone)] struct C; #[tokio::test] async fn works() { let mut a = Extensions::new(); a.insert(A); let (a, _) = with_extensions(a, async { let mut b = Extensions::new(); b.insert(B); let (b, _) = with_extensions(b, async { assert!(get_local_item::().await.is_none()); assert!(get_local_item::().await.is_some()); set_local_item(C).await; }) .await; // returned extension is correct assert!(b.get::().is_some()); assert!(b.get::().is_some()); assert!(get_local_item::().await.is_some()); assert!(get_local_item::().await.is_none()); assert!(get_local_item::().await.is_none()); }) .await; // returned extension is correct assert!(a.get::().is_some()); } }