├── .github ├── FUNDING.yml └── workflows │ ├── clippy.yml │ ├── rustfmt.yml │ └── tests.yml ├── .gitignore ├── .vscode └── settings.json ├── CHANGELOG.md ├── Cargo.lock.msrv ├── Cargo.toml ├── LICENSE ├── Makefile ├── README.md ├── examples ├── basic-fragile.rs └── basic-sticky.rs └── src ├── errors.rs ├── fragile.rs ├── futures.rs ├── lib.rs ├── registry.rs ├── semisticky.rs ├── sticky.rs └── thread_id.rs /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [mitsuhiko] 2 | -------------------------------------------------------------------------------- /.github/workflows/clippy.yml: -------------------------------------------------------------------------------- 1 | name: Clippy 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - uses: actions/checkout@v3 11 | - uses: dtolnay/rust-toolchain@master 12 | with: 13 | toolchain: stable 14 | components: clippy, rustfmt 15 | - name: Run clippy 16 | run: make lint 17 | -------------------------------------------------------------------------------- /.github/workflows/rustfmt.yml: -------------------------------------------------------------------------------- 1 | name: Rustfmt 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - uses: actions/checkout@v3 11 | - uses: dtolnay/rust-toolchain@master 12 | with: 13 | toolchain: stable 14 | components: clippy, rustfmt 15 | - name: Run rustfmt 16 | run: make format-check 17 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: [push] 4 | 5 | jobs: 6 | test-latest: 7 | name: Test on Latest 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v3 12 | - uses: dtolnay/rust-toolchain@master 13 | with: 14 | toolchain: stable 15 | - name: Test 16 | run: make test 17 | 18 | test-stable: 19 | name: Test on 1.56.0 20 | runs-on: ubuntu-latest 21 | 22 | steps: 23 | - uses: actions/checkout@v3 24 | - uses: dtolnay/rust-toolchain@master 25 | with: 26 | toolchain: 1.56.0 27 | - name: Restore Cargo.lock 28 | run: cp Cargo.lock.msrv Cargo.lock 29 | - name: Test 30 | run: make test 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /target 3 | **/*.rs.bk 4 | Cargo.lock 5 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "rust-analyzer.checkOnSave.command": "clippy" 3 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to similar are documented here. 4 | 5 | ## 2.1.0 6 | 7 | * Implement `Future` and `Stream` for `Fragile`, `Sticky` and `SemiSticky`. 8 | [#38](https://github.com/mitsuhiko/fragile/pull/38), [#40](https://github.com/mitsuhiko/fragile/pull/40) 9 | * Better panic error reporting by adding `#[track_caller]`. 10 | * Fragile now internally uses the stdlib's thread IDs instead of its own counter. [#39](https://github.com/mitsuhiko/fragile/pull/39) 11 | 12 | ## 2.0.1 13 | 14 | * Fixed a soundness issue with `Sticky` if the `slab` variant was enabled. 15 | This caused a use after free if the type was freed in the wrong thread. 16 | [#37](https://github.com/mitsuhiko/fragile/pull/37) 17 | 18 | ## 2.0.0 19 | 20 | * `Fragile` no longer boxes internally. 21 | * `Sticky` and `SemiSticky` now require the use of stack tokens. 22 | For more information see [#26](https://github.com/mitsuhiko/fragile/issues/26) 23 | * `Sticky` now tries to drop entries from the thread local registry eagerly 24 | if it's dropped on the right thread. 25 | 26 | ## 1.2.1 27 | 28 | * Fixed non slab versions only allowing a single sticky. 29 | 30 | ## 1.2.0 31 | 32 | Note on safety: the `Sticky` and `SemiSticky` types allow data to live 33 | longer than the wrapper type which is why they are now requiring a `'static` 34 | bound. Previously it was possible to create a sticky containing a bare 35 | reference which permitted unsafe access. 36 | 37 | * `Sticky` now requires `'static`. 38 | * Added the `slab` feature for an internal optimization for `Sticky` to use 39 | a slab instead of a `HashMap`. 40 | 41 | ## Older Releases 42 | 43 | Older releases were yanked due to the insufficient trait bound on `Sticky`. 44 | -------------------------------------------------------------------------------- /Cargo.lock.msrv: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "autocfg" 7 | version = "1.4.0" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" 10 | 11 | [[package]] 12 | name = "fragile" 13 | version = "2.0.1" 14 | dependencies = [ 15 | "futures-core", 16 | "futures-executor", 17 | "futures-util", 18 | "slab", 19 | ] 20 | 21 | [[package]] 22 | name = "futures-core" 23 | version = "0.3.31" 24 | source = "registry+https://github.com/rust-lang/crates.io-index" 25 | checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" 26 | 27 | [[package]] 28 | name = "futures-executor" 29 | version = "0.3.31" 30 | source = "registry+https://github.com/rust-lang/crates.io-index" 31 | checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" 32 | dependencies = [ 33 | "futures-core", 34 | "futures-task", 35 | "futures-util", 36 | ] 37 | 38 | [[package]] 39 | name = "futures-macro" 40 | version = "0.3.31" 41 | source = "registry+https://github.com/rust-lang/crates.io-index" 42 | checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" 43 | dependencies = [ 44 | "proc-macro2", 45 | "quote", 46 | "syn", 47 | ] 48 | 49 | [[package]] 50 | name = "futures-task" 51 | version = "0.3.31" 52 | source = "registry+https://github.com/rust-lang/crates.io-index" 53 | checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" 54 | 55 | [[package]] 56 | name = "futures-util" 57 | version = "0.3.31" 58 | source = "registry+https://github.com/rust-lang/crates.io-index" 59 | checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" 60 | dependencies = [ 61 | "futures-core", 62 | "futures-macro", 63 | "futures-task", 64 | "pin-project-lite", 65 | "pin-utils", 66 | "slab", 67 | ] 68 | 69 | [[package]] 70 | name = "pin-project-lite" 71 | version = "0.2.16" 72 | source = "registry+https://github.com/rust-lang/crates.io-index" 73 | checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" 74 | 75 | [[package]] 76 | name = "pin-utils" 77 | version = "0.1.0" 78 | source = "registry+https://github.com/rust-lang/crates.io-index" 79 | checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" 80 | 81 | [[package]] 82 | name = "proc-macro2" 83 | version = "1.0.94" 84 | source = "registry+https://github.com/rust-lang/crates.io-index" 85 | checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" 86 | dependencies = [ 87 | "unicode-ident", 88 | ] 89 | 90 | [[package]] 91 | name = "quote" 92 | version = "1.0.40" 93 | source = "registry+https://github.com/rust-lang/crates.io-index" 94 | checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" 95 | dependencies = [ 96 | "proc-macro2", 97 | ] 98 | 99 | [[package]] 100 | name = "slab" 101 | version = "0.4.9" 102 | source = "registry+https://github.com/rust-lang/crates.io-index" 103 | checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" 104 | dependencies = [ 105 | "autocfg", 106 | ] 107 | 108 | [[package]] 109 | name = "syn" 110 | version = "2.0.56" 111 | source = "registry+https://github.com/rust-lang/crates.io-index" 112 | checksum = "6e2415488199887523e74fd9a5f7be804dfd42d868ae0eca382e3917094d210e" 113 | dependencies = [ 114 | "proc-macro2", 115 | "quote", 116 | "unicode-ident", 117 | ] 118 | 119 | [[package]] 120 | name = "unicode-ident" 121 | version = "1.0.18" 122 | source = "registry+https://github.com/rust-lang/crates.io-index" 123 | checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" 124 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "fragile" 3 | version = "2.0.1" 4 | license = "Apache-2.0" 5 | description = "Provides wrapper types for sending non-send values to other threads." 6 | readme = "README.md" 7 | authors = ["Armin Ronacher "] 8 | repository = "https://github.com/mitsuhiko/fragile" 9 | homepage = "https://github.com/mitsuhiko/fragile" 10 | keywords = ["send", "cell", "non-send", "send-wrapper", "failure"] 11 | edition = "2018" 12 | rust-version = "1.56.0" 13 | 14 | [features] 15 | default = ["stream"] 16 | future = [] 17 | stream = ["future", "futures-core"] 18 | 19 | [dependencies] 20 | futures-core = { version = "0.3.11", optional = true } 21 | slab = { version = "0.4.5", optional = true } 22 | 23 | [dev-dependencies] 24 | futures-executor = "0.3.11" 25 | futures-util = "0.3.11" 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | all: build test 2 | 3 | build: 4 | @cargo build 5 | 6 | check: 7 | @cargo check 8 | 9 | doc: 10 | @cargo doc 11 | 12 | test: 13 | @cargo test 14 | @cargo test --all-features 15 | 16 | format: 17 | @rustup component add rustfmt 2> /dev/null 18 | @cargo fmt --all 19 | 20 | format-check: 21 | @rustup component add rustfmt 2> /dev/null 22 | @cargo fmt --all -- --check 23 | 24 | lint: 25 | @rustup component add clippy 2> /dev/null 26 | @cargo clippy 27 | 28 | .PHONY: all check doc test format format-check lint 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Fragile 2 | 3 | [![Crates.io](https://img.shields.io/crates/d/fragile.svg)](https://crates.io/crates/fragile) 4 | [![License](https://img.shields.io/github/license/mitsuhiko/fragile)](https://github.com/mitsuhiko/fragile/blob/master/LICENSE) 5 | [![Documentation](https://docs.rs/fragile/badge.svg)](https://docs.rs/fragile) 6 | 7 | This library provides wrapper types that permit sending non Send types to other 8 | threads and use runtime checks to ensure safety. 9 | 10 | It provides the `Fragile`, `Sticky` and `SemiSticky` types which are 11 | similar in nature but have different behaviors with regards to how destructors 12 | are executed. The `Fragile` will panic if the destructor is called in another 13 | thread, `Sticky` will temporarily leak the object until the thread shuts down. 14 | `SemiSticky` is a compromise of the two. It behaves like `Sticky` but it 15 | avoids the use of thread local storage if the type does not need `Drop`. 16 | 17 | ## Example 18 | 19 | ```rust 20 | use std::thread; 21 | 22 | // creating and using a fragile object in the same thread works 23 | let val = Fragile::new(true); 24 | assert_eq!(*val.get(), true); 25 | assert!(val.try_get().is_ok()); 26 | 27 | // once send to another thread it stops working 28 | thread::spawn(move || { 29 | assert!(val.try_get().is_err()); 30 | }).join() 31 | .unwrap(); 32 | ``` 33 | 34 | ## License and Links 35 | 36 | - [Documentation](https://docs.rs/fragile/) 37 | - [Issue Tracker](https://github.com/mitsuhiko/fragile/issues) 38 | - License: [Apache 2.0](https://github.com/mitsuhiko/fragile/blob/master/LICENSE) 39 | -------------------------------------------------------------------------------- /examples/basic-fragile.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | 3 | use fragile::Fragile; 4 | 5 | fn main() { 6 | // creating and using a fragile object in the same thread works 7 | let val = Fragile::new(true); 8 | println!("debug print in same thread: {:?}", &val); 9 | println!("try_get in same thread: {:?}", val.try_get()); 10 | 11 | // once send to another thread it stops working 12 | thread::spawn(move || { 13 | println!("debug print in other thread: {:?}", &val); 14 | println!("try_get in other thread: {:?}", val.try_get()); 15 | }) 16 | .join() 17 | .unwrap(); 18 | } 19 | -------------------------------------------------------------------------------- /examples/basic-sticky.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | 3 | use fragile::Sticky; 4 | 5 | fn main() { 6 | fragile::stack_token!(tok); 7 | 8 | // creating and using a fragile object in the same thread works 9 | let val = Sticky::new(true); 10 | println!("debug print in same thread: {:?}", &val); 11 | println!("try_get in same thread: {:?}", val.try_get(tok)); 12 | 13 | // once send to another thread it stops working 14 | thread::spawn(move || { 15 | fragile::stack_token!(tok); 16 | println!("debug print in other thread: {:?}", &val); 17 | println!("try_get in other thread: {:?}", val.try_get(tok)); 18 | }) 19 | .join() 20 | .unwrap(); 21 | } 22 | -------------------------------------------------------------------------------- /src/errors.rs: -------------------------------------------------------------------------------- 1 | use std::error; 2 | use std::fmt; 3 | 4 | /// Returned when borrowing fails. 5 | #[derive(Debug)] 6 | pub struct InvalidThreadAccess; 7 | 8 | impl fmt::Display for InvalidThreadAccess { 9 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 10 | write!(f, "fragile value accessed from foreign thread") 11 | } 12 | } 13 | 14 | impl error::Error for InvalidThreadAccess {} 15 | -------------------------------------------------------------------------------- /src/fragile.rs: -------------------------------------------------------------------------------- 1 | use std::cmp; 2 | use std::fmt; 3 | use std::mem; 4 | use std::thread; 5 | use std::thread::ThreadId; 6 | 7 | use crate::errors::InvalidThreadAccess; 8 | use std::mem::ManuallyDrop; 9 | 10 | /// A [`Fragile`] wraps a non sendable `T` to be safely send to other threads. 11 | /// 12 | /// Once the value has been wrapped it can be sent to other threads but access 13 | /// to the value on those threads will fail. 14 | /// 15 | /// If the value needs destruction and the fragile wrapper is on another thread 16 | /// the destructor will panic. Alternatively you can use 17 | /// [`Sticky`](crate::Sticky) which is not going to panic but might temporarily 18 | /// leak the value. 19 | pub struct Fragile { 20 | // ManuallyDrop is necessary because we need to move out of here without running the 21 | // Drop code in functions like `into_inner`. 22 | value: ManuallyDrop, 23 | // we can use ThreadId because Rust guarnatees it to be unique for the duration of a process. 24 | thread_id: ThreadId, 25 | } 26 | 27 | impl Fragile { 28 | /// Creates a new [`Fragile`] wrapping a `value`. 29 | /// 30 | /// The value that is moved into the [`Fragile`] can be non `Send` and 31 | /// will be anchored to the thread that created the object. If the 32 | /// fragile wrapper type ends up being send from thread to thread 33 | /// only the original thread can interact with the value. 34 | pub fn new(value: T) -> Self { 35 | Fragile { 36 | value: ManuallyDrop::new(value), 37 | thread_id: thread::current().id(), 38 | } 39 | } 40 | 41 | /// Returns `true` if the access is valid. 42 | /// 43 | /// This will be `false` if the value was sent to another thread. 44 | pub fn is_valid(&self) -> bool { 45 | thread::current().id() == self.thread_id 46 | } 47 | 48 | #[inline(always)] 49 | #[track_caller] 50 | fn assert_thread(&self) { 51 | if !self.is_valid() { 52 | panic!("trying to access wrapped value in fragile container from incorrect thread."); 53 | } 54 | } 55 | 56 | /// Consumes the `Fragile`, returning the wrapped value. 57 | /// 58 | /// # Panics 59 | /// 60 | /// Panics if called from a different thread than the one where the 61 | /// original value was created. 62 | #[track_caller] 63 | pub fn into_inner(self) -> T { 64 | self.assert_thread(); 65 | 66 | let mut this = ManuallyDrop::new(self); 67 | 68 | // SAFETY: `this` is not accessed beyond this point, and because it's in a ManuallyDrop its 69 | // destructor is not run. 70 | unsafe { ManuallyDrop::take(&mut this.value) } 71 | } 72 | 73 | /// Consumes the `Fragile`, returning the wrapped value if successful. 74 | /// 75 | /// The wrapped value is returned if this is called from the same thread 76 | /// as the one where the original value was created, otherwise the 77 | /// [`Fragile`] is returned as `Err(self)`. 78 | pub fn try_into_inner(self) -> Result { 79 | if self.is_valid() { 80 | Ok(self.into_inner()) 81 | } else { 82 | Err(self) 83 | } 84 | } 85 | 86 | /// Immutably borrows the wrapped value. 87 | /// 88 | /// # Panics 89 | /// 90 | /// Panics if the calling thread is not the one that wrapped the value. 91 | /// For a non-panicking variant, use [`try_get`](Self::try_get). 92 | #[track_caller] 93 | pub fn get(&self) -> &T { 94 | self.assert_thread(); 95 | &self.value 96 | } 97 | 98 | /// Mutably borrows the wrapped value. 99 | /// 100 | /// # Panics 101 | /// 102 | /// Panics if the calling thread is not the one that wrapped the value. 103 | /// For a non-panicking variant, use [`try_get_mut`](Self::try_get_mut). 104 | #[track_caller] 105 | pub fn get_mut(&mut self) -> &mut T { 106 | self.assert_thread(); 107 | &mut self.value 108 | } 109 | 110 | /// Tries to immutably borrow the wrapped value. 111 | /// 112 | /// Returns `None` if the calling thread is not the one that wrapped the value. 113 | pub fn try_get(&self) -> Result<&T, InvalidThreadAccess> { 114 | if self.is_valid() { 115 | Ok(&*self.value) 116 | } else { 117 | Err(InvalidThreadAccess) 118 | } 119 | } 120 | 121 | /// Tries to mutably borrow the wrapped value. 122 | /// 123 | /// Returns `None` if the calling thread is not the one that wrapped the value. 124 | pub fn try_get_mut(&mut self) -> Result<&mut T, InvalidThreadAccess> { 125 | if self.is_valid() { 126 | Ok(&mut *self.value) 127 | } else { 128 | Err(InvalidThreadAccess) 129 | } 130 | } 131 | } 132 | 133 | impl Drop for Fragile { 134 | #[track_caller] 135 | fn drop(&mut self) { 136 | if mem::needs_drop::() { 137 | if self.is_valid() { 138 | // SAFETY: `ManuallyDrop::drop` cannot be called after this point. 139 | unsafe { ManuallyDrop::drop(&mut self.value) }; 140 | } else { 141 | panic!("destructor of fragile object ran on wrong thread"); 142 | } 143 | } 144 | } 145 | } 146 | 147 | impl From for Fragile { 148 | #[inline] 149 | fn from(t: T) -> Fragile { 150 | Fragile::new(t) 151 | } 152 | } 153 | 154 | impl Clone for Fragile { 155 | #[inline] 156 | #[track_caller] 157 | fn clone(&self) -> Fragile { 158 | Fragile::new(self.get().clone()) 159 | } 160 | } 161 | 162 | impl Default for Fragile { 163 | #[inline] 164 | fn default() -> Fragile { 165 | Fragile::new(T::default()) 166 | } 167 | } 168 | 169 | impl PartialEq for Fragile { 170 | #[inline] 171 | #[track_caller] 172 | fn eq(&self, other: &Fragile) -> bool { 173 | *self.get() == *other.get() 174 | } 175 | } 176 | 177 | impl Eq for Fragile {} 178 | 179 | impl PartialOrd for Fragile { 180 | #[inline] 181 | #[track_caller] 182 | fn partial_cmp(&self, other: &Fragile) -> Option { 183 | self.get().partial_cmp(other.get()) 184 | } 185 | 186 | #[inline] 187 | #[track_caller] 188 | fn lt(&self, other: &Fragile) -> bool { 189 | *self.get() < *other.get() 190 | } 191 | 192 | #[inline] 193 | #[track_caller] 194 | fn le(&self, other: &Fragile) -> bool { 195 | *self.get() <= *other.get() 196 | } 197 | 198 | #[inline] 199 | #[track_caller] 200 | fn gt(&self, other: &Fragile) -> bool { 201 | *self.get() > *other.get() 202 | } 203 | 204 | #[inline] 205 | #[track_caller] 206 | fn ge(&self, other: &Fragile) -> bool { 207 | *self.get() >= *other.get() 208 | } 209 | } 210 | 211 | impl Ord for Fragile { 212 | #[inline] 213 | #[track_caller] 214 | fn cmp(&self, other: &Fragile) -> cmp::Ordering { 215 | self.get().cmp(other.get()) 216 | } 217 | } 218 | 219 | impl fmt::Display for Fragile { 220 | #[track_caller] 221 | fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { 222 | fmt::Display::fmt(self.get(), f) 223 | } 224 | } 225 | 226 | impl fmt::Debug for Fragile { 227 | fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { 228 | match self.try_get() { 229 | Ok(value) => f.debug_struct("Fragile").field("value", value).finish(), 230 | Err(..) => { 231 | struct InvalidPlaceholder; 232 | impl fmt::Debug for InvalidPlaceholder { 233 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 234 | f.write_str("") 235 | } 236 | } 237 | 238 | f.debug_struct("Fragile") 239 | .field("value", &InvalidPlaceholder) 240 | .finish() 241 | } 242 | } 243 | } 244 | } 245 | 246 | // this type is sync because access can only ever happy from the same thread 247 | // that created it originally. All other threads will be able to safely 248 | // call some basic operations on the reference and they will fail. 249 | unsafe impl Sync for Fragile {} 250 | 251 | // The entire point of this type is to be Send 252 | #[allow(clippy::non_send_fields_in_send_ty)] 253 | unsafe impl Send for Fragile {} 254 | 255 | #[test] 256 | fn test_basic() { 257 | use std::thread; 258 | let val = Fragile::new(true); 259 | assert_eq!(val.to_string(), "true"); 260 | assert_eq!(val.get(), &true); 261 | assert!(val.try_get().is_ok()); 262 | thread::spawn(move || { 263 | assert!(val.try_get().is_err()); 264 | }) 265 | .join() 266 | .unwrap(); 267 | } 268 | 269 | #[test] 270 | fn test_mut() { 271 | let mut val = Fragile::new(true); 272 | *val.get_mut() = false; 273 | assert_eq!(val.to_string(), "false"); 274 | assert_eq!(val.get(), &false); 275 | } 276 | 277 | #[test] 278 | #[should_panic] 279 | fn test_access_other_thread() { 280 | use std::thread; 281 | let val = Fragile::new(true); 282 | thread::spawn(move || { 283 | val.get(); 284 | }) 285 | .join() 286 | .unwrap(); 287 | } 288 | 289 | #[test] 290 | fn test_noop_drop_elsewhere() { 291 | use std::thread; 292 | let val = Fragile::new(true); 293 | thread::spawn(move || { 294 | // force the move 295 | val.try_get().ok(); 296 | }) 297 | .join() 298 | .unwrap(); 299 | } 300 | 301 | #[test] 302 | fn test_panic_on_drop_elsewhere() { 303 | use std::sync::atomic::{AtomicBool, Ordering}; 304 | use std::sync::Arc; 305 | use std::thread; 306 | let was_called = Arc::new(AtomicBool::new(false)); 307 | struct X(Arc); 308 | impl Drop for X { 309 | fn drop(&mut self) { 310 | self.0.store(true, Ordering::SeqCst); 311 | } 312 | } 313 | let val = Fragile::new(X(was_called.clone())); 314 | assert!(thread::spawn(move || { 315 | val.try_get().ok(); 316 | }) 317 | .join() 318 | .is_err()); 319 | assert!(!was_called.load(Ordering::SeqCst)); 320 | } 321 | 322 | #[test] 323 | fn test_rc_sending() { 324 | use std::rc::Rc; 325 | use std::sync::mpsc::channel; 326 | use std::thread; 327 | 328 | let val = Fragile::new(Rc::new(true)); 329 | let (tx, rx) = channel(); 330 | 331 | let thread = thread::spawn(move || { 332 | assert!(val.try_get().is_err()); 333 | let here = val; 334 | tx.send(here).unwrap(); 335 | }); 336 | 337 | let rv = rx.recv().unwrap(); 338 | assert!(**rv.get()); 339 | 340 | thread.join().unwrap(); 341 | } 342 | -------------------------------------------------------------------------------- /src/futures.rs: -------------------------------------------------------------------------------- 1 | use std::future::Future; 2 | use std::pin::Pin; 3 | use std::task::{Context, Poll}; 4 | 5 | use crate::{stack_token, Fragile, SemiSticky, Sticky}; 6 | 7 | impl Future for Fragile { 8 | type Output = F::Output; 9 | 10 | #[track_caller] 11 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 12 | unsafe { self.map_unchecked_mut(|s| s.get_mut()) }.poll(cx) 13 | } 14 | } 15 | 16 | impl Future for Sticky { 17 | type Output = F::Output; 18 | 19 | #[track_caller] 20 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 21 | stack_token!(tok); 22 | unsafe { Pin::new_unchecked(Sticky::get_mut(&mut self, tok)) }.poll(cx) 23 | } 24 | } 25 | 26 | impl Future for SemiSticky { 27 | type Output = F::Output; 28 | 29 | #[track_caller] 30 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 31 | stack_token!(tok); 32 | unsafe { Pin::new_unchecked(SemiSticky::get_mut(&mut self, tok)) }.poll(cx) 33 | } 34 | } 35 | 36 | #[cfg(feature = "stream")] 37 | mod stream { 38 | use super::*; 39 | use futures_core::Stream; 40 | 41 | impl Stream for Fragile { 42 | type Item = S::Item; 43 | 44 | #[track_caller] 45 | fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 46 | unsafe { self.map_unchecked_mut(|s| s.get_mut()) }.poll_next(cx) 47 | } 48 | 49 | #[inline] 50 | fn size_hint(&self) -> (usize, Option) { 51 | match self.try_get() { 52 | Ok(x) => x.size_hint(), 53 | Err(_) => (0, None), 54 | } 55 | } 56 | } 57 | 58 | impl Stream for Sticky { 59 | type Item = S::Item; 60 | 61 | #[track_caller] 62 | fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 63 | stack_token!(tok); 64 | unsafe { Pin::new_unchecked(Sticky::get_mut(&mut self, tok)) }.poll_next(cx) 65 | } 66 | 67 | #[inline] 68 | fn size_hint(&self) -> (usize, Option) { 69 | stack_token!(tok); 70 | match Sticky::try_get(self, tok) { 71 | Ok(x) => x.size_hint(), 72 | Err(_) => (0, None), 73 | } 74 | } 75 | } 76 | 77 | impl Stream for SemiSticky { 78 | type Item = S::Item; 79 | 80 | #[track_caller] 81 | fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 82 | stack_token!(tok); 83 | unsafe { Pin::new_unchecked(SemiSticky::get_mut(&mut self, tok)) }.poll_next(cx) 84 | } 85 | 86 | #[inline] 87 | fn size_hint(&self) -> (usize, Option) { 88 | stack_token!(tok); 89 | match SemiSticky::try_get(self, tok) { 90 | Ok(x) => x.size_hint(), 91 | Err(_) => (0, None), 92 | } 93 | } 94 | } 95 | 96 | #[test] 97 | fn test_stream() { 98 | use futures_executor as executor; 99 | use futures_util::{future, stream, StreamExt}; 100 | let mut w1 = Fragile::new(stream::once(future::ready(42))); 101 | let mut w2 = Fragile::new(stream::once(future::ready(42))); 102 | assert_eq!( 103 | format!("{:?}", executor::block_on(w1.next())), 104 | format!("{:?}", executor::block_on(w2.next())), 105 | ); 106 | 107 | let mut w1 = Sticky::new(stream::once(future::ready(42))); 108 | let mut w2 = Sticky::new(stream::once(future::ready(42))); 109 | assert_eq!( 110 | format!("{:?}", executor::block_on(w1.next())), 111 | format!("{:?}", executor::block_on(w2.next())), 112 | ); 113 | 114 | let mut w1 = SemiSticky::new(stream::once(future::ready(42))); 115 | let mut w2 = SemiSticky::new(stream::once(future::ready(42))); 116 | assert_eq!( 117 | format!("{:?}", executor::block_on(w1.next())), 118 | format!("{:?}", executor::block_on(w2.next())), 119 | ); 120 | } 121 | 122 | #[test] 123 | fn test_stream_panic() { 124 | use futures_executor as executor; 125 | use futures_util::{future, stream, StreamExt}; 126 | 127 | let mut w = Fragile::new(stream::once(future::ready(42))); 128 | let t = std::thread::spawn(move || executor::block_on(w.next())); 129 | assert!(t.join().is_err()); 130 | 131 | let mut w = Sticky::new(stream::once(future::ready(42))); 132 | let t = std::thread::spawn(move || executor::block_on(w.next())); 133 | assert!(t.join().is_err()); 134 | 135 | let mut w = SemiSticky::new(stream::once(future::ready(42))); 136 | let t = std::thread::spawn(move || executor::block_on(w.next())); 137 | assert!(t.join().is_err()); 138 | } 139 | } 140 | 141 | #[test] 142 | fn test_future() { 143 | use futures_executor as executor; 144 | use futures_util::future; 145 | let w1 = Fragile::new(future::ready(42)); 146 | let w2 = w1.clone(); 147 | assert_eq!( 148 | format!("{:?}", executor::block_on(w1)), 149 | format!("{:?}", executor::block_on(w2)), 150 | ); 151 | 152 | let w1 = Sticky::new(future::ready(42)); 153 | let w2 = w1.clone(); 154 | assert_eq!( 155 | format!("{:?}", executor::block_on(w1)), 156 | format!("{:?}", executor::block_on(w2)), 157 | ); 158 | 159 | let w1 = SemiSticky::new(future::ready(42)); 160 | let w2 = w1.clone(); 161 | assert_eq!( 162 | format!("{:?}", executor::block_on(w1)), 163 | format!("{:?}", executor::block_on(w2)), 164 | ); 165 | } 166 | 167 | #[test] 168 | fn test_future_panic() { 169 | use futures_executor as executor; 170 | use futures_util::future; 171 | let w = Fragile::new(future::ready(42)); 172 | let t = std::thread::spawn(move || executor::block_on(w)); 173 | assert!(t.join().is_err()); 174 | 175 | let w = Sticky::new(future::ready(42)); 176 | let t = std::thread::spawn(move || executor::block_on(w)); 177 | assert!(t.join().is_err()); 178 | 179 | let w = SemiSticky::new(future::ready(42)); 180 | let t = std::thread::spawn(move || executor::block_on(w)); 181 | assert!(t.join().is_err()); 182 | } 183 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This library provides wrapper types that permit sending non `Send` types to 2 | //! other threads and use runtime checks to ensure safety. 3 | //! 4 | //! It provides three types: [`Fragile`] and [`Sticky`] which are similar in nature 5 | //! but have different behaviors with regards to how destructors are executed and 6 | //! the extra [`SemiSticky`] type which uses [`Sticky`] if the value has a 7 | //! destructor and [`Fragile`] if it does not. 8 | //! 9 | //! All three types wrap a value and provide a `Send` bound. Neither of the types permit 10 | //! access to the enclosed value unless the thread that wrapped the value is attempting 11 | //! to access it. The difference between the types starts playing a role once 12 | //! destructors are involved. 13 | //! 14 | //! A [`Fragile`] will actually send the `T` from thread to thread but will only 15 | //! permit the original thread to invoke the destructor. If the value gets dropped 16 | //! in a different thread, the destructor will panic. 17 | //! 18 | //! A [`Sticky`] on the other hand does not actually send the `T` around but keeps 19 | //! it stored in the original thread's thread local storage. If it gets dropped 20 | //! in the originating thread it gets cleaned up immediately, otherwise it leaks 21 | //! until the thread shuts down naturally. [`Sticky`] because it borrows into the 22 | //! TLS also requires you to "prove" that you are not doing any funny business with 23 | //! the borrowed value that lives for longer than the current stack frame which 24 | //! results in a slightly more complex API. 25 | //! 26 | //! There is a third typed called [`SemiSticky`] which shares the API with [`Sticky`] 27 | //! but internally uses a boxed [`Fragile`] if the type does not actually need a dtor 28 | //! in which case [`Fragile`] is preferred. 29 | //! 30 | //! # Fragile Usage 31 | //! 32 | //! [`Fragile`] is the easiest type to use. It works almost like a cell. 33 | //! 34 | //! ``` 35 | //! use std::thread; 36 | //! use fragile::Fragile; 37 | //! 38 | //! // creating and using a fragile object in the same thread works 39 | //! let val = Fragile::new(true); 40 | //! assert_eq!(*val.get(), true); 41 | //! assert!(val.try_get().is_ok()); 42 | //! 43 | //! // once send to another thread it stops working 44 | //! thread::spawn(move || { 45 | //! assert!(val.try_get().is_err()); 46 | //! }).join() 47 | //! .unwrap(); 48 | //! ``` 49 | //! 50 | //! # Sticky Usage 51 | //! 52 | //! [`Sticky`] is similar to [`Fragile`] but because it places the value in the 53 | //! thread local storage it comes with some extra restrictions to make it sound. 54 | //! The advantage is it can be dropped from any thread but it comes with extra 55 | //! restrictions. In particular it requires that values placed in it are `'static` 56 | //! and that [`StackToken`]s are used to restrict lifetimes. 57 | //! 58 | //! ``` 59 | //! use std::thread; 60 | //! use fragile::Sticky; 61 | //! 62 | //! // creating and using a fragile object in the same thread works 63 | //! fragile::stack_token!(tok); 64 | //! let val = Sticky::new(true); 65 | //! assert_eq!(*val.get(tok), true); 66 | //! assert!(val.try_get(tok).is_ok()); 67 | //! 68 | //! // once send to another thread it stops working 69 | //! thread::spawn(move || { 70 | //! fragile::stack_token!(tok); 71 | //! assert!(val.try_get(tok).is_err()); 72 | //! }).join() 73 | //! .unwrap(); 74 | //! ``` 75 | //! 76 | //! # Why? 77 | //! 78 | //! Most of the time trying to use this crate is going to indicate some code smell. But 79 | //! there are situations where this is useful. For instance you might have a bunch of 80 | //! non `Send` types but want to work with a `Send` error type. In that case the non 81 | //! sendable extra information can be contained within the error and in cases where the 82 | //! error did not cross a thread boundary yet extra information can be obtained. 83 | //! 84 | //! # Drop / Cleanup Behavior 85 | //! 86 | //! All types will try to eagerly drop a value if they are dropped on the right thread. 87 | //! [`Sticky`] and [`SemiSticky`] will however temporarily leak memory until a thread 88 | //! shuts down if the value is dropped on the wrong thread. The benefit however is that 89 | //! if you have that type of situation, and you can live with the consequences, the 90 | //! type is not panicking. A [`Fragile`] dropped in the wrong thread will not just panic, 91 | //! it will effectively also tear down the process because panicking in destructors is 92 | //! non recoverable. 93 | //! 94 | //! # Features 95 | //! 96 | //! By default the crate has no dependencies. Optionally the `slab` feature can 97 | //! be enabled which optimizes the internal storage of the [`Sticky`] type to 98 | //! make it use a [`slab`](https://docs.rs/slab/latest/slab/) instead. 99 | //! 100 | //! When turning on the `future` feature, then the containers implement the 101 | //! [`Future`](std::future::Future) crate from the standard library to 102 | //! automatically wrap futures. The `stream` crate does the same for the 103 | //! `future_core::Stream` type. 104 | mod errors; 105 | mod fragile; 106 | mod registry; 107 | mod semisticky; 108 | mod sticky; 109 | 110 | #[cfg(feature = "future")] 111 | mod futures; 112 | 113 | use std::marker::PhantomData; 114 | 115 | pub use crate::errors::InvalidThreadAccess; 116 | pub use crate::fragile::Fragile; 117 | pub use crate::semisticky::SemiSticky; 118 | pub use crate::sticky::Sticky; 119 | 120 | /// A token that is placed to the stack to constrain lifetimes. 121 | /// 122 | /// For more information about how these work see the documentation of 123 | /// [`stack_token!`] which is the only way to create this token. 124 | pub struct StackToken(PhantomData<*const ()>); 125 | 126 | impl StackToken { 127 | /// Stack tokens must only be created on the stack. 128 | #[doc(hidden)] 129 | pub unsafe fn __private_new() -> StackToken { 130 | // we place a const pointer in there to get a type 131 | // that is neither Send nor Sync. 132 | StackToken(PhantomData) 133 | } 134 | } 135 | 136 | /// Crates a token on the stack with a certain name for semi-sticky. 137 | /// 138 | /// The argument to the macro is the target name of a local variable 139 | /// which holds a reference to a stack token. Because this is the 140 | /// only way to create such a token, it acts as a proof to [`Sticky`] 141 | /// or [`SemiSticky`] that can be used to constrain the lifetime of the 142 | /// return values to the stack frame. 143 | /// 144 | /// This is necessary as otherwise a [`Sticky`] placed in a [`Box`] and 145 | /// leaked with [`Box::leak`] (which creates a static lifetime) would 146 | /// otherwise create a reference with `'static` lifetime. This is incorrect 147 | /// as the actual lifetime is constrained to the lifetime of the thread. 148 | /// For more information see [`issue 26`](https://github.com/mitsuhiko/fragile/issues/26). 149 | /// 150 | /// ```rust 151 | /// let sticky = fragile::Sticky::new(true); 152 | /// 153 | /// // this places a token on the stack. 154 | /// fragile::stack_token!(my_token); 155 | /// 156 | /// // the token needs to be passed to `get` and others. 157 | /// let _ = sticky.get(my_token); 158 | /// ``` 159 | #[macro_export] 160 | macro_rules! stack_token { 161 | ($name:ident) => { 162 | let $name = &unsafe { $crate::StackToken::__private_new() }; 163 | }; 164 | } 165 | -------------------------------------------------------------------------------- /src/registry.rs: -------------------------------------------------------------------------------- 1 | pub struct Entry { 2 | /// The pointer to the object stored in the registry. This is a type-erased 3 | /// `Box`. 4 | pub ptr: *mut (), 5 | /// The function that can be called on the above pointer to drop the object 6 | /// and free its allocation. 7 | pub drop: unsafe fn(*mut ()), 8 | } 9 | 10 | #[cfg(feature = "slab")] 11 | mod slab_impl { 12 | use std::cell::UnsafeCell; 13 | 14 | use super::Entry; 15 | 16 | pub struct Registry(pub slab::Slab); 17 | 18 | thread_local!(static REGISTRY: UnsafeCell = UnsafeCell::new(Registry(slab::Slab::new()))); 19 | 20 | pub use usize as ItemId; 21 | 22 | pub fn insert(entry: Entry) -> ItemId { 23 | REGISTRY.with(|registry| unsafe { (*registry.get()).0.insert(entry) }) 24 | } 25 | 26 | pub fn with R>(item_id: ItemId, f: F) -> R { 27 | REGISTRY.with(|registry| f(unsafe { &*registry.get() }.0.get(item_id).unwrap())) 28 | } 29 | 30 | pub fn try_remove(item_id: ItemId) -> Option { 31 | REGISTRY.with(|registry| unsafe { (*registry.get()).0.try_remove(item_id) }) 32 | } 33 | } 34 | 35 | #[cfg(not(feature = "slab"))] 36 | mod map_impl { 37 | use std::cell::UnsafeCell; 38 | use std::num::NonZeroUsize; 39 | use std::sync::atomic::{AtomicUsize, Ordering}; 40 | 41 | use super::Entry; 42 | 43 | pub struct Registry(pub std::collections::HashMap); 44 | 45 | thread_local!(static REGISTRY: UnsafeCell = UnsafeCell::new(Registry(Default::default()))); 46 | 47 | pub type ItemId = NonZeroUsize; 48 | 49 | fn next_item_id() -> NonZeroUsize { 50 | static COUNTER: AtomicUsize = AtomicUsize::new(1); 51 | NonZeroUsize::new(COUNTER.fetch_add(1, Ordering::Relaxed)) 52 | .expect("more than usize::MAX items") 53 | } 54 | 55 | pub fn insert(entry: Entry) -> ItemId { 56 | let item_id = next_item_id(); 57 | REGISTRY.with(|registry| unsafe { (*registry.get()).0.insert(item_id, entry) }); 58 | item_id 59 | } 60 | 61 | pub fn with R>(item_id: ItemId, f: F) -> R { 62 | REGISTRY.with(|registry| f(unsafe { &*registry.get() }.0.get(&item_id).unwrap())) 63 | } 64 | 65 | pub fn try_remove(item_id: ItemId) -> Option { 66 | REGISTRY.with(|registry| unsafe { (*registry.get()).0.remove(&item_id) }) 67 | } 68 | } 69 | 70 | #[cfg(feature = "slab")] 71 | pub use self::slab_impl::*; 72 | 73 | #[cfg(not(feature = "slab"))] 74 | pub use self::map_impl::*; 75 | 76 | impl Drop for Registry { 77 | fn drop(&mut self) { 78 | for (_, value) in self.0.iter() { 79 | // SAFETY: This function is only called once, and is called with the 80 | // pointer it was created with. 81 | unsafe { (value.drop)(value.ptr) }; 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/semisticky.rs: -------------------------------------------------------------------------------- 1 | use std::cmp; 2 | use std::fmt; 3 | use std::mem; 4 | 5 | use crate::errors::InvalidThreadAccess; 6 | use crate::fragile::Fragile; 7 | use crate::sticky::Sticky; 8 | use crate::StackToken; 9 | 10 | enum SemiStickyImpl { 11 | Fragile(Box>), 12 | Sticky(Sticky), 13 | } 14 | 15 | /// A [`SemiSticky`] keeps a value T stored in a thread if it has a drop. 16 | /// 17 | /// This is a combined version of [`Fragile`] and [`Sticky`]. If the type 18 | /// does not have a drop it will effectively be a [`Fragile`], otherwise it 19 | /// will be internally behave like a [`Sticky`]. 20 | /// 21 | /// This type requires `T: 'static` for the same reasons as [`Sticky`] and 22 | /// also uses [`StackToken`]s. 23 | pub struct SemiSticky { 24 | inner: SemiStickyImpl, 25 | } 26 | 27 | impl SemiSticky { 28 | /// Creates a new [`SemiSticky`] wrapping a `value`. 29 | /// 30 | /// The value that is moved into the `SemiSticky` can be non `Send` and 31 | /// will be anchored to the thread that created the object. If the 32 | /// sticky wrapper type ends up being send from thread to thread 33 | /// only the original thread can interact with the value. In case the 34 | /// value does not have `Drop` it will be stored in the [`Fragile`] 35 | /// instead. 36 | pub fn new(value: T) -> Self { 37 | SemiSticky { 38 | inner: if mem::needs_drop::() { 39 | SemiStickyImpl::Sticky(Sticky::new(value)) 40 | } else { 41 | SemiStickyImpl::Fragile(Box::new(Fragile::new(value))) 42 | }, 43 | } 44 | } 45 | 46 | /// Returns `true` if the access is valid. 47 | /// 48 | /// This will be `false` if the value was sent to another thread. 49 | pub fn is_valid(&self) -> bool { 50 | match self.inner { 51 | SemiStickyImpl::Fragile(ref inner) => inner.is_valid(), 52 | SemiStickyImpl::Sticky(ref inner) => inner.is_valid(), 53 | } 54 | } 55 | 56 | /// Consumes the [`SemiSticky`], returning the wrapped value. 57 | /// 58 | /// # Panics 59 | /// 60 | /// Panics if called from a different thread than the one where the 61 | /// original value was created. 62 | #[track_caller] 63 | pub fn into_inner(self) -> T { 64 | match self.inner { 65 | SemiStickyImpl::Fragile(inner) => inner.into_inner(), 66 | SemiStickyImpl::Sticky(inner) => inner.into_inner(), 67 | } 68 | } 69 | 70 | /// Consumes the [`SemiSticky`], returning the wrapped value if successful. 71 | /// 72 | /// The wrapped value is returned if this is called from the same thread 73 | /// as the one where the original value was created, otherwise the 74 | /// [`SemiSticky`] is returned as `Err(self)`. 75 | pub fn try_into_inner(self) -> Result { 76 | match self.inner { 77 | SemiStickyImpl::Fragile(inner) => inner.try_into_inner().map_err(|inner| SemiSticky { 78 | inner: SemiStickyImpl::Fragile(Box::new(inner)), 79 | }), 80 | SemiStickyImpl::Sticky(inner) => inner.try_into_inner().map_err(|inner| SemiSticky { 81 | inner: SemiStickyImpl::Sticky(inner), 82 | }), 83 | } 84 | } 85 | 86 | /// Immutably borrows the wrapped value. 87 | /// 88 | /// # Panics 89 | /// 90 | /// Panics if the calling thread is not the one that wrapped the value. 91 | /// For a non-panicking variant, use [`try_get`](Self::try_get). 92 | #[track_caller] 93 | pub fn get<'stack>(&'stack self, _proof: &'stack StackToken) -> &'stack T { 94 | match self.inner { 95 | SemiStickyImpl::Fragile(ref inner) => inner.get(), 96 | SemiStickyImpl::Sticky(ref inner) => inner.get(_proof), 97 | } 98 | } 99 | 100 | /// Mutably borrows the wrapped value. 101 | /// 102 | /// # Panics 103 | /// 104 | /// Panics if the calling thread is not the one that wrapped the value. 105 | /// For a non-panicking variant, use [`try_get_mut`](Self::try_get_mut). 106 | #[track_caller] 107 | pub fn get_mut<'stack>(&'stack mut self, _proof: &'stack StackToken) -> &'stack mut T { 108 | match self.inner { 109 | SemiStickyImpl::Fragile(ref mut inner) => inner.get_mut(), 110 | SemiStickyImpl::Sticky(ref mut inner) => inner.get_mut(_proof), 111 | } 112 | } 113 | 114 | /// Tries to immutably borrow the wrapped value. 115 | /// 116 | /// Returns `None` if the calling thread is not the one that wrapped the value. 117 | pub fn try_get<'stack>( 118 | &'stack self, 119 | _proof: &'stack StackToken, 120 | ) -> Result<&'stack T, InvalidThreadAccess> { 121 | match self.inner { 122 | SemiStickyImpl::Fragile(ref inner) => inner.try_get(), 123 | SemiStickyImpl::Sticky(ref inner) => inner.try_get(_proof), 124 | } 125 | } 126 | 127 | /// Tries to mutably borrow the wrapped value. 128 | /// 129 | /// Returns `None` if the calling thread is not the one that wrapped the value. 130 | pub fn try_get_mut<'stack>( 131 | &'stack mut self, 132 | _proof: &'stack StackToken, 133 | ) -> Result<&'stack mut T, InvalidThreadAccess> { 134 | match self.inner { 135 | SemiStickyImpl::Fragile(ref mut inner) => inner.try_get_mut(), 136 | SemiStickyImpl::Sticky(ref mut inner) => inner.try_get_mut(_proof), 137 | } 138 | } 139 | } 140 | 141 | impl From for SemiSticky { 142 | #[inline] 143 | fn from(t: T) -> SemiSticky { 144 | SemiSticky::new(t) 145 | } 146 | } 147 | 148 | impl Clone for SemiSticky { 149 | #[inline] 150 | #[track_caller] 151 | fn clone(&self) -> SemiSticky { 152 | crate::stack_token!(tok); 153 | SemiSticky::new(self.get(tok).clone()) 154 | } 155 | } 156 | 157 | impl Default for SemiSticky { 158 | #[inline] 159 | fn default() -> SemiSticky { 160 | SemiSticky::new(T::default()) 161 | } 162 | } 163 | 164 | impl PartialEq for SemiSticky { 165 | #[inline] 166 | #[track_caller] 167 | fn eq(&self, other: &SemiSticky) -> bool { 168 | crate::stack_token!(tok); 169 | *self.get(tok) == *other.get(tok) 170 | } 171 | } 172 | 173 | impl Eq for SemiSticky {} 174 | 175 | impl PartialOrd for SemiSticky { 176 | #[inline] 177 | #[track_caller] 178 | fn partial_cmp(&self, other: &SemiSticky) -> Option { 179 | crate::stack_token!(tok); 180 | self.get(tok).partial_cmp(other.get(tok)) 181 | } 182 | 183 | #[inline] 184 | #[track_caller] 185 | fn lt(&self, other: &SemiSticky) -> bool { 186 | crate::stack_token!(tok); 187 | *self.get(tok) < *other.get(tok) 188 | } 189 | 190 | #[inline] 191 | #[track_caller] 192 | fn le(&self, other: &SemiSticky) -> bool { 193 | crate::stack_token!(tok); 194 | *self.get(tok) <= *other.get(tok) 195 | } 196 | 197 | #[inline] 198 | #[track_caller] 199 | fn gt(&self, other: &SemiSticky) -> bool { 200 | crate::stack_token!(tok); 201 | *self.get(tok) > *other.get(tok) 202 | } 203 | 204 | #[inline] 205 | #[track_caller] 206 | fn ge(&self, other: &SemiSticky) -> bool { 207 | crate::stack_token!(tok); 208 | *self.get(tok) >= *other.get(tok) 209 | } 210 | } 211 | 212 | impl Ord for SemiSticky { 213 | #[inline] 214 | #[track_caller] 215 | fn cmp(&self, other: &SemiSticky) -> cmp::Ordering { 216 | crate::stack_token!(tok); 217 | self.get(tok).cmp(other.get(tok)) 218 | } 219 | } 220 | 221 | impl fmt::Display for SemiSticky { 222 | #[track_caller] 223 | fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { 224 | crate::stack_token!(tok); 225 | fmt::Display::fmt(self.get(tok), f) 226 | } 227 | } 228 | 229 | impl fmt::Debug for SemiSticky { 230 | fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { 231 | crate::stack_token!(tok); 232 | match self.try_get(tok) { 233 | Ok(value) => f.debug_struct("SemiSticky").field("value", value).finish(), 234 | Err(..) => { 235 | struct InvalidPlaceholder; 236 | impl fmt::Debug for InvalidPlaceholder { 237 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 238 | f.write_str("") 239 | } 240 | } 241 | 242 | f.debug_struct("SemiSticky") 243 | .field("value", &InvalidPlaceholder) 244 | .finish() 245 | } 246 | } 247 | } 248 | } 249 | 250 | #[test] 251 | fn test_basic() { 252 | use std::thread; 253 | let val = SemiSticky::new(true); 254 | crate::stack_token!(tok); 255 | assert_eq!(val.to_string(), "true"); 256 | assert_eq!(val.get(tok), &true); 257 | assert!(val.try_get(tok).is_ok()); 258 | thread::spawn(move || { 259 | crate::stack_token!(tok); 260 | assert!(val.try_get(tok).is_err()); 261 | }) 262 | .join() 263 | .unwrap(); 264 | } 265 | 266 | #[test] 267 | fn test_mut() { 268 | let mut val = SemiSticky::new(true); 269 | crate::stack_token!(tok); 270 | *val.get_mut(tok) = false; 271 | assert_eq!(val.to_string(), "false"); 272 | assert_eq!(val.get(tok), &false); 273 | } 274 | 275 | #[test] 276 | #[should_panic] 277 | fn test_access_other_thread() { 278 | use std::thread; 279 | let val = SemiSticky::new(true); 280 | thread::spawn(move || { 281 | crate::stack_token!(tok); 282 | val.get(tok); 283 | }) 284 | .join() 285 | .unwrap(); 286 | } 287 | 288 | #[test] 289 | fn test_drop_same_thread() { 290 | use std::sync::atomic::{AtomicBool, Ordering}; 291 | use std::sync::Arc; 292 | let was_called = Arc::new(AtomicBool::new(false)); 293 | struct X(Arc); 294 | impl Drop for X { 295 | fn drop(&mut self) { 296 | self.0.store(true, Ordering::SeqCst); 297 | } 298 | } 299 | let val = SemiSticky::new(X(was_called.clone())); 300 | mem::drop(val); 301 | assert!(was_called.load(Ordering::SeqCst)); 302 | } 303 | 304 | #[test] 305 | fn test_noop_drop_elsewhere() { 306 | use std::sync::atomic::{AtomicBool, Ordering}; 307 | use std::sync::Arc; 308 | use std::thread; 309 | 310 | let was_called = Arc::new(AtomicBool::new(false)); 311 | 312 | { 313 | let was_called = was_called.clone(); 314 | thread::spawn(move || { 315 | struct X(Arc); 316 | impl Drop for X { 317 | fn drop(&mut self) { 318 | self.0.store(true, Ordering::SeqCst); 319 | } 320 | } 321 | 322 | let val = SemiSticky::new(X(was_called.clone())); 323 | assert!(thread::spawn(move || { 324 | // moves it here but do not deallocate 325 | crate::stack_token!(tok); 326 | val.try_get(tok).ok(); 327 | }) 328 | .join() 329 | .is_ok()); 330 | 331 | assert!(!was_called.load(Ordering::SeqCst)); 332 | }) 333 | .join() 334 | .unwrap(); 335 | } 336 | 337 | assert!(was_called.load(Ordering::SeqCst)); 338 | } 339 | 340 | #[test] 341 | fn test_rc_sending() { 342 | use std::rc::Rc; 343 | use std::thread; 344 | let val = SemiSticky::new(Rc::new(true)); 345 | thread::spawn(move || { 346 | crate::stack_token!(tok); 347 | assert!(val.try_get(tok).is_err()); 348 | }) 349 | .join() 350 | .unwrap(); 351 | } 352 | -------------------------------------------------------------------------------- /src/sticky.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::unit_arg)] 2 | 3 | use std::cmp; 4 | use std::fmt; 5 | use std::marker::PhantomData; 6 | use std::mem; 7 | use std::thread; 8 | use std::thread::ThreadId; 9 | 10 | use crate::errors::InvalidThreadAccess; 11 | use crate::registry; 12 | use crate::StackToken; 13 | 14 | /// A [`Sticky`] keeps a value T stored in a thread. 15 | /// 16 | /// This type works similar in nature to [`Fragile`](crate::Fragile) and exposes a 17 | /// similar interface. The difference is that whereas [`Fragile`](crate::Fragile) has 18 | /// its destructor called in the thread where the value was sent, a 19 | /// [`Sticky`] that is moved to another thread will have the internal 20 | /// destructor called when the originating thread tears down. 21 | /// 22 | /// Because [`Sticky`] allows values to be kept alive for longer than the 23 | /// [`Sticky`] itself, it requires all its contents to be `'static` for 24 | /// soundness. More importantly it also requires the use of [`StackToken`]s. 25 | /// For information about how to use stack tokens and why they are needed, 26 | /// refer to [`stack_token!`](crate::stack_token). 27 | /// 28 | /// As this uses TLS internally the general rules about the platform limitations 29 | /// of destructors for TLS apply. 30 | pub struct Sticky { 31 | item_id: registry::ItemId, 32 | thread_id: ThreadId, 33 | _marker: PhantomData<*mut T>, 34 | } 35 | 36 | impl Drop for Sticky { 37 | #[track_caller] 38 | fn drop(&mut self) { 39 | // if the type needs dropping we can only do so on the right thread. 40 | // worst case we leak the value until the thread dies when drop will be 41 | // called by the registry. 42 | if mem::needs_drop::() { 43 | unsafe { 44 | if self.is_valid() { 45 | self.unsafe_take_value(); 46 | } 47 | } 48 | } 49 | } 50 | } 51 | 52 | impl Sticky { 53 | /// Creates a new [`Sticky`] wrapping a `value`. 54 | /// 55 | /// The value that is moved into the [`Sticky`] can be non `Send` and 56 | /// will be anchored to the thread that created the object. If the 57 | /// sticky wrapper type ends up being send from thread to thread 58 | /// only the original thread can interact with the value. 59 | pub fn new(value: T) -> Self { 60 | let entry = registry::Entry { 61 | ptr: Box::into_raw(Box::new(value)).cast(), 62 | drop: |ptr| { 63 | let ptr = ptr.cast::(); 64 | // SAFETY: This callback will only be called once, with the 65 | // above pointer. 66 | drop(unsafe { Box::from_raw(ptr) }); 67 | }, 68 | }; 69 | 70 | let thread_id = thread::current().id(); 71 | let item_id = registry::insert(entry); 72 | 73 | Sticky { 74 | item_id, 75 | thread_id, 76 | _marker: PhantomData, 77 | } 78 | } 79 | 80 | #[inline(always)] 81 | #[track_caller] 82 | fn with_value R, R>(&self, f: F) -> R { 83 | self.assert_thread(); 84 | 85 | registry::with(self.item_id, |entry| f(entry.ptr.cast::())) 86 | } 87 | 88 | /// Returns `true` if the access is valid. 89 | /// 90 | /// This will be `false` if the value was sent to another thread. 91 | #[inline(always)] 92 | pub fn is_valid(&self) -> bool { 93 | thread::current().id() == self.thread_id 94 | } 95 | 96 | #[inline(always)] 97 | #[track_caller] 98 | fn assert_thread(&self) { 99 | if !self.is_valid() { 100 | panic!("trying to access wrapped value in sticky container from incorrect thread."); 101 | } 102 | } 103 | 104 | /// Consumes the `Sticky`, returning the wrapped value. 105 | /// 106 | /// # Panics 107 | /// 108 | /// Panics if called from a different thread than the one where the 109 | /// original value was created. 110 | #[track_caller] 111 | pub fn into_inner(mut self) -> T { 112 | self.assert_thread(); 113 | unsafe { 114 | let rv = self.unsafe_take_value(); 115 | mem::forget(self); 116 | rv 117 | } 118 | } 119 | 120 | unsafe fn unsafe_take_value(&mut self) -> T { 121 | let ptr = registry::try_remove(self.item_id).unwrap().ptr.cast::(); 122 | *Box::from_raw(ptr) 123 | } 124 | 125 | /// Consumes the `Sticky`, returning the wrapped value if successful. 126 | /// 127 | /// The wrapped value is returned if this is called from the same thread 128 | /// as the one where the original value was created, otherwise the 129 | /// `Sticky` is returned as `Err(self)`. 130 | pub fn try_into_inner(self) -> Result { 131 | if self.is_valid() { 132 | Ok(self.into_inner()) 133 | } else { 134 | Err(self) 135 | } 136 | } 137 | 138 | /// Immutably borrows the wrapped value. 139 | /// 140 | /// # Panics 141 | /// 142 | /// Panics if the calling thread is not the one that wrapped the value. 143 | /// For a non-panicking variant, use [`try_get`](#method.try_get`). 144 | #[track_caller] 145 | pub fn get<'stack>(&'stack self, _proof: &'stack StackToken) -> &'stack T { 146 | self.with_value(|value| unsafe { &*value }) 147 | } 148 | 149 | /// Mutably borrows the wrapped value. 150 | /// 151 | /// # Panics 152 | /// 153 | /// Panics if the calling thread is not the one that wrapped the value. 154 | /// For a non-panicking variant, use [`try_get_mut`](#method.try_get_mut`). 155 | #[track_caller] 156 | pub fn get_mut<'stack>(&'stack mut self, _proof: &'stack StackToken) -> &'stack mut T { 157 | self.with_value(|value| unsafe { &mut *value }) 158 | } 159 | 160 | /// Tries to immutably borrow the wrapped value. 161 | /// 162 | /// Returns `None` if the calling thread is not the one that wrapped the value. 163 | pub fn try_get<'stack>( 164 | &'stack self, 165 | _proof: &'stack StackToken, 166 | ) -> Result<&'stack T, InvalidThreadAccess> { 167 | if self.is_valid() { 168 | Ok(self.with_value(|value| unsafe { &*value })) 169 | } else { 170 | Err(InvalidThreadAccess) 171 | } 172 | } 173 | 174 | /// Tries to mutably borrow the wrapped value. 175 | /// 176 | /// Returns `None` if the calling thread is not the one that wrapped the value. 177 | pub fn try_get_mut<'stack>( 178 | &'stack mut self, 179 | _proof: &'stack StackToken, 180 | ) -> Result<&'stack mut T, InvalidThreadAccess> { 181 | if self.is_valid() { 182 | Ok(self.with_value(|value| unsafe { &mut *value })) 183 | } else { 184 | Err(InvalidThreadAccess) 185 | } 186 | } 187 | } 188 | 189 | impl From for Sticky { 190 | #[inline] 191 | fn from(t: T) -> Sticky { 192 | Sticky::new(t) 193 | } 194 | } 195 | 196 | impl Clone for Sticky { 197 | #[inline] 198 | #[track_caller] 199 | fn clone(&self) -> Sticky { 200 | crate::stack_token!(tok); 201 | Sticky::new(self.get(tok).clone()) 202 | } 203 | } 204 | 205 | impl Default for Sticky { 206 | #[inline] 207 | fn default() -> Sticky { 208 | Sticky::new(T::default()) 209 | } 210 | } 211 | 212 | impl PartialEq for Sticky { 213 | #[inline] 214 | #[track_caller] 215 | fn eq(&self, other: &Sticky) -> bool { 216 | crate::stack_token!(tok); 217 | *self.get(tok) == *other.get(tok) 218 | } 219 | } 220 | 221 | impl Eq for Sticky {} 222 | 223 | impl PartialOrd for Sticky { 224 | #[inline] 225 | #[track_caller] 226 | fn partial_cmp(&self, other: &Sticky) -> Option { 227 | crate::stack_token!(tok); 228 | self.get(tok).partial_cmp(other.get(tok)) 229 | } 230 | 231 | #[inline] 232 | #[track_caller] 233 | fn lt(&self, other: &Sticky) -> bool { 234 | crate::stack_token!(tok); 235 | *self.get(tok) < *other.get(tok) 236 | } 237 | 238 | #[inline] 239 | #[track_caller] 240 | fn le(&self, other: &Sticky) -> bool { 241 | crate::stack_token!(tok); 242 | *self.get(tok) <= *other.get(tok) 243 | } 244 | 245 | #[inline] 246 | #[track_caller] 247 | fn gt(&self, other: &Sticky) -> bool { 248 | crate::stack_token!(tok); 249 | *self.get(tok) > *other.get(tok) 250 | } 251 | 252 | #[inline] 253 | #[track_caller] 254 | fn ge(&self, other: &Sticky) -> bool { 255 | crate::stack_token!(tok); 256 | *self.get(tok) >= *other.get(tok) 257 | } 258 | } 259 | 260 | impl Ord for Sticky { 261 | #[inline] 262 | #[track_caller] 263 | fn cmp(&self, other: &Sticky) -> cmp::Ordering { 264 | crate::stack_token!(tok); 265 | self.get(tok).cmp(other.get(tok)) 266 | } 267 | } 268 | 269 | impl fmt::Display for Sticky { 270 | #[track_caller] 271 | fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { 272 | crate::stack_token!(tok); 273 | fmt::Display::fmt(self.get(tok), f) 274 | } 275 | } 276 | 277 | impl fmt::Debug for Sticky { 278 | fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { 279 | crate::stack_token!(tok); 280 | match self.try_get(tok) { 281 | Ok(value) => f.debug_struct("Sticky").field("value", value).finish(), 282 | Err(..) => { 283 | struct InvalidPlaceholder; 284 | impl fmt::Debug for InvalidPlaceholder { 285 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 286 | f.write_str("") 287 | } 288 | } 289 | 290 | f.debug_struct("Sticky") 291 | .field("value", &InvalidPlaceholder) 292 | .finish() 293 | } 294 | } 295 | } 296 | } 297 | 298 | // similar as for fragile the type is sync because it only accesses TLS data 299 | // which is thread local. There is nothing that needs to be synchronized. 300 | unsafe impl Sync for Sticky {} 301 | 302 | // The entire point of this type is to be Send 303 | unsafe impl Send for Sticky {} 304 | 305 | #[test] 306 | fn test_basic() { 307 | use std::thread; 308 | let val = Sticky::new(true); 309 | crate::stack_token!(tok); 310 | assert_eq!(val.to_string(), "true"); 311 | assert_eq!(val.get(tok), &true); 312 | assert!(val.try_get(tok).is_ok()); 313 | thread::spawn(move || { 314 | crate::stack_token!(tok); 315 | assert!(val.try_get(tok).is_err()); 316 | }) 317 | .join() 318 | .unwrap(); 319 | } 320 | 321 | #[test] 322 | fn test_mut() { 323 | let mut val = Sticky::new(true); 324 | crate::stack_token!(tok); 325 | *val.get_mut(tok) = false; 326 | assert_eq!(val.to_string(), "false"); 327 | assert_eq!(val.get(tok), &false); 328 | } 329 | 330 | #[test] 331 | #[should_panic] 332 | fn test_access_other_thread() { 333 | use std::thread; 334 | let val = Sticky::new(true); 335 | thread::spawn(move || { 336 | crate::stack_token!(tok); 337 | val.get(tok); 338 | }) 339 | .join() 340 | .unwrap(); 341 | } 342 | 343 | #[test] 344 | fn test_drop_same_thread() { 345 | use std::sync::atomic::{AtomicBool, Ordering}; 346 | use std::sync::Arc; 347 | let was_called = Arc::new(AtomicBool::new(false)); 348 | struct X(Arc); 349 | impl Drop for X { 350 | fn drop(&mut self) { 351 | self.0.store(true, Ordering::SeqCst); 352 | } 353 | } 354 | let val = Sticky::new(X(was_called.clone())); 355 | mem::drop(val); 356 | assert!(was_called.load(Ordering::SeqCst)); 357 | } 358 | 359 | #[test] 360 | fn test_noop_drop_elsewhere() { 361 | use std::sync::atomic::{AtomicBool, Ordering}; 362 | use std::sync::Arc; 363 | use std::thread; 364 | 365 | let was_called = Arc::new(AtomicBool::new(false)); 366 | 367 | { 368 | let was_called = was_called.clone(); 369 | thread::spawn(move || { 370 | struct X(Arc); 371 | impl Drop for X { 372 | fn drop(&mut self) { 373 | self.0.store(true, Ordering::SeqCst); 374 | } 375 | } 376 | 377 | let val = Sticky::new(X(was_called.clone())); 378 | assert!(thread::spawn(move || { 379 | // moves it here but do not deallocate 380 | crate::stack_token!(tok); 381 | val.try_get(tok).ok(); 382 | }) 383 | .join() 384 | .is_ok()); 385 | 386 | assert!(!was_called.load(Ordering::SeqCst)); 387 | }) 388 | .join() 389 | .unwrap(); 390 | } 391 | 392 | assert!(was_called.load(Ordering::SeqCst)); 393 | } 394 | 395 | #[test] 396 | fn test_rc_sending() { 397 | use std::rc::Rc; 398 | use std::thread; 399 | let val = Sticky::new(Rc::new(true)); 400 | thread::spawn(move || { 401 | crate::stack_token!(tok); 402 | assert!(val.try_get(tok).is_err()); 403 | }) 404 | .join() 405 | .unwrap(); 406 | } 407 | 408 | #[test] 409 | fn test_two_stickies() { 410 | struct Wat; 411 | 412 | impl Drop for Wat { 413 | fn drop(&mut self) { 414 | // do nothing 415 | } 416 | } 417 | 418 | let s1 = Sticky::new(Wat); 419 | let s2 = Sticky::new(Wat); 420 | 421 | // make sure all is well 422 | 423 | drop(s1); 424 | drop(s2); 425 | } 426 | 427 | #[test] 428 | fn test_thread_spawn() { 429 | use crate::{stack_token, Sticky}; 430 | use std::{mem::ManuallyDrop, thread}; 431 | 432 | let dummy_sticky = thread::spawn(|| Sticky::new(())).join().unwrap(); 433 | let sticky_string = ManuallyDrop::new(Sticky::new(String::from("Hello World"))); 434 | stack_token!(t); 435 | 436 | let hello: &str = sticky_string.get(t); 437 | 438 | assert_eq!(hello, "Hello World"); 439 | drop(dummy_sticky); 440 | assert_eq!(hello, "Hello World"); 441 | } 442 | -------------------------------------------------------------------------------- /src/thread_id.rs: -------------------------------------------------------------------------------- 1 | use std::num::NonZeroUsize; 2 | use std::sync::atomic::{AtomicUsize, Ordering}; 3 | 4 | fn next() -> NonZeroUsize { 5 | static COUNTER: AtomicUsize = AtomicUsize::new(1); 6 | NonZeroUsize::new(COUNTER.fetch_add(1, Ordering::Relaxed)) 7 | .expect("more than usize::MAX threads") 8 | } 9 | 10 | pub(crate) fn get() -> NonZeroUsize { 11 | thread_local!(static THREAD_ID: NonZeroUsize = next()); 12 | THREAD_ID.with(|&x| x) 13 | } 14 | --------------------------------------------------------------------------------