fragile-0.3.0/.gitignore010064400007650000024000000000371333720506600133370ustar0000000000000000 /target **/*.rs.bk Cargo.lock fragile-0.3.0/Cargo.toml.orig010064400007650000024000000006341333721523300142360ustar0000000000000000[package] name = "fragile" version = "0.3.0" license = "Apache-2.0" description = "Provides wrapper types for sending non-send values to other threads." readme = "README.md" authors = ["Armin Ronacher "] repository = "https://github.com/mitsuhiko/rust-fragile" homepage = "https://github.com/mitsuhiko/rust-fragile" keywords = ["send", "cell", "non-send", "send-wrapper", "failure"] fragile-0.3.0/Cargo.toml0000644000000016500000000000000105040ustar00# 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "fragile" version = "0.3.0" authors = ["Armin Ronacher "] description = "Provides wrapper types for sending non-send values to other threads." homepage = "https://github.com/mitsuhiko/rust-fragile" readme = "README.md" keywords = ["send", "cell", "non-send", "send-wrapper", "failure"] license = "Apache-2.0" repository = "https://github.com/mitsuhiko/rust-fragile" fragile-0.3.0/LICENSE010064400007650000024000000261361330426507700123660ustar0000000000000000 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. fragile-0.3.0/README.md010064400007650000024000000013711333720506600126300ustar0000000000000000# Fragile This library provides wrapper types that permit sending non Send types to other threads and use runtime checks to ensure safety. It provides two types: `Fragile` and `Sticky` which are similar in nature but have different behaviors with regards to how destructors are executed. The former will panic if the destructor is called in another thread, the latter will temporarily leak the object until the thread shuts down. ```rust use std::thread; // creating and using a fragile object in the same thread works let val = Fragile::new(true); assert_eq!(*val.get(), true); assert!(val.try_get().is_ok()); // once send to another thread it stops working thread::spawn(move || { assert!(val.try_get().is_err()); }).join() .unwrap(); ``` fragile-0.3.0/src/errors.rs010064400007650000024000000006571333720506600140300ustar0000000000000000use std::error; use std::fmt; /// Returned when borrowing fails. #[derive(Debug)] pub struct InvalidThreadAccess; impl fmt::Display for InvalidThreadAccess { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(error::Error::description(self), f) } } impl error::Error for InvalidThreadAccess { fn description(&self) -> &str { "fragile value accessed from foreign thread" } } fragile-0.3.0/src/fragile.rs010064400007650000024000000215601333720506600141210ustar0000000000000000use std::cell::UnsafeCell; use std::cmp; use std::fmt; use std::mem; use std::mem::ManuallyDrop; use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use errors::InvalidThreadAccess; fn next_thread_id() -> usize { static mut COUNTER: AtomicUsize = ATOMIC_USIZE_INIT; unsafe { COUNTER.fetch_add(1, Ordering::SeqCst) } } pub(crate) fn get_thread_id() -> usize { thread_local!(static THREAD_ID: usize = next_thread_id()); THREAD_ID.with(|&x| x) } /// A `Fragile` wraps a non sendable `T` to be safely send to other threads. /// /// Once the value has been wrapped it can be sent to other threads but access /// to the value on those threads will fail. /// /// If the value needs destruction and the fragile wrapper is on another thread /// the destructor will panic. Alternatively you can use `Sticky` which is /// not going to panic but might temporarily leak the value. pub struct Fragile { value: ManuallyDrop>>, thread_id: usize, } impl Fragile { /// Creates a new `Fragile` wrapping a `value`. /// /// The value that is moved into the `Fragile` can be non `Send` and /// will be anchored to the thread that created the object. If the /// fragile wrapper type ends up being send from thread to thread /// only the original thread can interact with the value. pub fn new(value: T) -> Self { Fragile { value: ManuallyDrop::new(UnsafeCell::new(Box::new(value))), thread_id: get_thread_id(), } } /// Returns `true` if the access is valid. /// /// This will be `false` if the value was sent to another thread. pub fn is_valid(&self) -> bool { get_thread_id() == self.thread_id } #[inline(always)] fn assert_thread(&self) { if !self.is_valid() { panic!("trying to access wrapped value in fragile container from incorrect thread."); } } /// Consumes the `Fragile`, returning the wrapped value. /// /// # Panics /// /// Panics if called from a different thread than the one where the /// original value was created. pub fn into_inner(mut self) -> T { self.assert_thread(); unsafe { let value = mem::replace(&mut self.value, mem::uninitialized()); mem::forget(self); *ManuallyDrop::into_inner(value).into_inner() } } /// Consumes the `Fragile`, returning the wrapped value if successful. /// /// The wrapped value is returned if this is called from the same thread /// as the one where the original value was created, otherwise the /// `Fragile` is returned as `Err(self)`. pub fn try_into_inner(self) -> Result { if get_thread_id() == self.thread_id { Ok(self.into_inner()) } else { Err(self) } } /// Immutably borrows the wrapped value. /// /// # Panics /// /// Panics if the calling thread is not the one that wrapped the value. /// For a non-panicking variant, use [`try_get`](#method.try_get`). pub fn get(&self) -> &T { self.assert_thread(); unsafe { &*self.value.get() } } /// Mutably borrows the wrapped value. /// /// # Panics /// /// Panics if the calling thread is not the one that wrapped the value. /// For a non-panicking variant, use [`try_get_mut`](#method.try_get_mut`). pub fn get_mut(&mut self) -> &mut T { self.assert_thread(); unsafe { &mut *self.value.get() } } /// Tries to immutably borrow the wrapped value. /// /// Returns `None` if the calling thread is not the one that wrapped the value. pub fn try_get(&self) -> Result<&T, InvalidThreadAccess> { if get_thread_id() == self.thread_id { unsafe { Ok(&*self.value.get()) } } else { Err(InvalidThreadAccess) } } /// Tries to mutably borrow the wrapped value. /// /// Returns `None` if the calling thread is not the one that wrapped the value. pub fn try_get_mut(&mut self) -> Result<&mut T, InvalidThreadAccess> { if get_thread_id() == self.thread_id { unsafe { Ok(&mut *self.value.get()) } } else { Err(InvalidThreadAccess) } } } impl Drop for Fragile { fn drop(&mut self) { if mem::needs_drop::() { if get_thread_id() == self.thread_id { unsafe { ManuallyDrop::drop(&mut self.value) } } else { panic!("destructor of fragile object ran on wrong thread"); } } } } impl From for Fragile { #[inline] fn from(t: T) -> Fragile { Fragile::new(t) } } impl Clone for Fragile { #[inline] fn clone(&self) -> Fragile { Fragile::new(self.get().clone()) } } impl Default for Fragile { #[inline] fn default() -> Fragile { Fragile::new(T::default()) } } impl PartialEq for Fragile { #[inline] fn eq(&self, other: &Fragile) -> bool { *self.get() == *other.get() } } impl Eq for Fragile {} impl PartialOrd for Fragile { #[inline] fn partial_cmp(&self, other: &Fragile) -> Option { self.get().partial_cmp(&*other.get()) } #[inline] fn lt(&self, other: &Fragile) -> bool { *self.get() < *other.get() } #[inline] fn le(&self, other: &Fragile) -> bool { *self.get() <= *other.get() } #[inline] fn gt(&self, other: &Fragile) -> bool { *self.get() > *other.get() } #[inline] fn ge(&self, other: &Fragile) -> bool { *self.get() >= *other.get() } } impl Ord for Fragile { #[inline] fn cmp(&self, other: &Fragile) -> cmp::Ordering { self.get().cmp(&*other.get()) } } impl fmt::Display for Fragile { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { fmt::Display::fmt(self.get(), f) } } impl fmt::Debug for Fragile { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self.try_get() { Ok(value) => f.debug_struct("Fragile").field("value", value).finish(), Err(..) => { struct InvalidPlaceholder; impl fmt::Debug for InvalidPlaceholder { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("") } } f.debug_struct("Fragile") .field("value", &InvalidPlaceholder) .finish() } } } } // this type is sync because access can only ever happy from the same thread // that created it originally. All other threads will be able to safely // call some basic operations on the reference and they will fail. unsafe impl Sync for Fragile {} // The entire point of this type is to be Send unsafe impl Send for Fragile {} #[test] fn test_basic() { use std::thread; let val = Fragile::new(true); assert_eq!(val.to_string(), "true"); assert_eq!(val.get(), &true); assert!(val.try_get().is_ok()); thread::spawn(move || { assert!(val.try_get().is_err()); }).join() .unwrap(); } #[test] fn test_mut() { let mut val = Fragile::new(true); *val.get_mut() = false; assert_eq!(val.to_string(), "false"); assert_eq!(val.get(), &false); } #[test] #[should_panic] fn test_access_other_thread() { use std::thread; let val = Fragile::new(true); thread::spawn(move || { val.get(); }).join() .unwrap(); } #[test] fn test_noop_drop_elsewhere() { use std::thread; let val = Fragile::new(true); thread::spawn(move || { // force the move val.try_get().ok(); }).join() .unwrap(); } #[test] fn test_panic_on_drop_elsewhere() { use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread; let was_called = Arc::new(AtomicBool::new(false)); struct X(Arc); impl Drop for X { fn drop(&mut self) { self.0.store(true, Ordering::SeqCst); } } let val = Fragile::new(X(was_called.clone())); assert!( thread::spawn(move || { val.try_get().ok(); }).join() .is_err() ); assert_eq!(was_called.load(Ordering::SeqCst), false); } #[test] fn test_rc_sending() { use std::rc::Rc; use std::thread; use std::sync::mpsc::channel; let val = Fragile::new(Rc::new(true)); let (tx, rx) = channel(); let thread = thread::spawn(move || { assert!(val.try_get().is_err()); let here = val; tx.send(here).unwrap(); }); let rv = rx.recv().unwrap(); assert!(**rv.get()); thread.join().unwrap(); } fragile-0.3.0/src/lib.rs010064400007650000024000000043631333720506600132600ustar0000000000000000//! This library provides wrapper types that permit sending non `Send` types to //! other threads and use runtime checks to ensure safety. //! //! It provides three types: `Fragile` and `Sticky` which are similar in nature //! but have different behaviors with regards to how destructors are executed and //! the extra `SemiSticky` type which uses `Sticky` if the value has a //! destructor and `Fragile` if it does not. //! //! Both types wrap a value and provide a `Send` bound. Neither of the types permit //! access to the enclosed value unless the thread that wrapped the value is attempting //! to access it. The difference between the two types starts playing a role once //! destructors are involved. //! //! A `Fragile` will actually send the `T` from thread to thread but will only //! permit the original thread to invoke the destructor. If the value gets dropped //! in a different thread, the destructor will panic. //! //! A `Sticky` on the other hand does not actually send the `T` around but keeps //! it stored in the original thread's thread local storage. If it gets dropped //! in the originating thread it gets cleaned up immediately, otherwise it leaks //! until the thread shuts down naturally. //! //! # Example usage //! //! ``` //! use std::thread; //! use fragile::Fragile; //! //! // creating and using a fragile object in the same thread works //! let val = Fragile::new(true); //! assert_eq!(*val.get(), true); //! assert!(val.try_get().is_ok()); //! //! // once send to another thread it stops working //! thread::spawn(move || { //! assert!(val.try_get().is_err()); //! }).join() //! .unwrap(); //! ``` //! //! # Why? //! //! Most of the time trying to use this crate is going to indicate some code smell. But //! there are situations where this is useful. For instance you might have a bunch of //! non `Send` types but want to work with a `Send` error type. In that case the non //! sendable extra information can be contained within the error and in cases where the //! error did not cross a thread boundary yet extra information can be obtained. mod errors; mod fragile; mod semisticky; mod sticky; pub use errors::InvalidThreadAccess; pub use fragile::Fragile; pub use semisticky::SemiSticky; pub use sticky::Sticky; fragile-0.3.0/src/semisticky.rs010064400007650000024000000214141333720506600146720ustar0000000000000000use std::cmp; use std::fmt; use errors::InvalidThreadAccess; use fragile::Fragile; use std::mem; use sticky::Sticky; enum SemiStickyImpl { Fragile(Fragile), Sticky(Sticky), } /// A `SemiSticky` keeps a value T stored in a thread if it has a drop. /// /// This is a combined version of `Fragile` and `Sticky`. If the type /// does not have a drop it will effectively be a `Fragile`, otherwise it /// will be internally behave like a `Sticky`. pub struct SemiSticky { inner: SemiStickyImpl, } impl SemiSticky { /// Creates a new `SemiSticky` wrapping a `value`. /// /// The value that is moved into the `SemiSticky` can be non `Send` and /// will be anchored to the thread that created the object. If the /// sticky wrapper type ends up being send from thread to thread /// only the original thread can interact with the value. In case the /// value does not have `Drop` it will be stored in the `SemiSticky` /// instead. pub fn new(value: T) -> Self { SemiSticky { inner: if mem::needs_drop::() { SemiStickyImpl::Sticky(Sticky::new(value)) } else { SemiStickyImpl::Fragile(Fragile::new(value)) }, } } /// Returns `true` if the access is valid. /// /// This will be `false` if the value was sent to another thread. pub fn is_valid(&self) -> bool { match self.inner { SemiStickyImpl::Fragile(ref inner) => inner.is_valid(), SemiStickyImpl::Sticky(ref inner) => inner.is_valid(), } } /// Consumes the `SemiSticky`, returning the wrapped value. /// /// # Panics /// /// Panics if called from a different thread than the one where the /// original value was created. pub fn into_inner(self) -> T { match self.inner { SemiStickyImpl::Fragile(inner) => inner.into_inner(), SemiStickyImpl::Sticky(inner) => inner.into_inner(), } } /// Consumes the `SemiSticky`, returning the wrapped value if successful. /// /// The wrapped value is returned if this is called from the same thread /// as the one where the original value was created, otherwise the /// `SemiSticky` is returned as `Err(self)`. pub fn try_into_inner(self) -> Result { match self.inner { SemiStickyImpl::Fragile(inner) => inner.try_into_inner().map_err(|inner| SemiSticky { inner: SemiStickyImpl::Fragile(inner), }), SemiStickyImpl::Sticky(inner) => inner.try_into_inner().map_err(|inner| SemiSticky { inner: SemiStickyImpl::Sticky(inner), }), } } /// Immutably borrows the wrapped value. /// /// # Panics /// /// Panics if the calling thread is not the one that wrapped the value. /// For a non-panicking variant, use [`try_get`](#method.try_get`). pub fn get(&self) -> &T { match self.inner { SemiStickyImpl::Fragile(ref inner) => inner.get(), SemiStickyImpl::Sticky(ref inner) => inner.get(), } } /// Mutably borrows the wrapped value. /// /// # Panics /// /// Panics if the calling thread is not the one that wrapped the value. /// For a non-panicking variant, use [`try_get_mut`](#method.try_get_mut`). pub fn get_mut(&mut self) -> &mut T { match self.inner { SemiStickyImpl::Fragile(ref mut inner) => inner.get_mut(), SemiStickyImpl::Sticky(ref mut inner) => inner.get_mut(), } } /// Tries to immutably borrow the wrapped value. /// /// Returns `None` if the calling thread is not the one that wrapped the value. pub fn try_get(&self) -> Result<&T, InvalidThreadAccess> { match self.inner { SemiStickyImpl::Fragile(ref inner) => inner.try_get(), SemiStickyImpl::Sticky(ref inner) => inner.try_get(), } } /// Tries to mutably borrow the wrapped value. /// /// Returns `None` if the calling thread is not the one that wrapped the value. pub fn try_get_mut(&mut self) -> Result<&mut T, InvalidThreadAccess> { match self.inner { SemiStickyImpl::Fragile(ref mut inner) => inner.try_get_mut(), SemiStickyImpl::Sticky(ref mut inner) => inner.try_get_mut(), } } } impl From for SemiSticky { #[inline] fn from(t: T) -> SemiSticky { SemiSticky::new(t) } } impl Clone for SemiSticky { #[inline] fn clone(&self) -> SemiSticky { SemiSticky::new(self.get().clone()) } } impl Default for SemiSticky { #[inline] fn default() -> SemiSticky { SemiSticky::new(T::default()) } } impl PartialEq for SemiSticky { #[inline] fn eq(&self, other: &SemiSticky) -> bool { *self.get() == *other.get() } } impl Eq for SemiSticky {} impl PartialOrd for SemiSticky { #[inline] fn partial_cmp(&self, other: &SemiSticky) -> Option { self.get().partial_cmp(&*other.get()) } #[inline] fn lt(&self, other: &SemiSticky) -> bool { *self.get() < *other.get() } #[inline] fn le(&self, other: &SemiSticky) -> bool { *self.get() <= *other.get() } #[inline] fn gt(&self, other: &SemiSticky) -> bool { *self.get() > *other.get() } #[inline] fn ge(&self, other: &SemiSticky) -> bool { *self.get() >= *other.get() } } impl Ord for SemiSticky { #[inline] fn cmp(&self, other: &SemiSticky) -> cmp::Ordering { self.get().cmp(&*other.get()) } } impl fmt::Display for SemiSticky { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { fmt::Display::fmt(self.get(), f) } } impl fmt::Debug for SemiSticky { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self.try_get() { Ok(value) => f.debug_struct("SemiSticky").field("value", value).finish(), Err(..) => { struct InvalidPlaceholder; impl fmt::Debug for InvalidPlaceholder { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("") } } f.debug_struct("SemiSticky") .field("value", &InvalidPlaceholder) .finish() } } } } #[test] fn test_basic() { use std::thread; let val = SemiSticky::new(true); assert_eq!(val.to_string(), "true"); assert_eq!(val.get(), &true); assert!(val.try_get().is_ok()); thread::spawn(move || { assert!(val.try_get().is_err()); }).join() .unwrap(); } #[test] fn test_mut() { let mut val = SemiSticky::new(true); *val.get_mut() = false; assert_eq!(val.to_string(), "false"); assert_eq!(val.get(), &false); } #[test] #[should_panic] fn test_access_other_thread() { use std::thread; let val = SemiSticky::new(true); thread::spawn(move || { val.get(); }).join() .unwrap(); } #[test] fn test_drop_same_thread() { use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; let was_called = Arc::new(AtomicBool::new(false)); struct X(Arc); impl Drop for X { fn drop(&mut self) { self.0.store(true, Ordering::SeqCst); } } let val = SemiSticky::new(X(was_called.clone())); mem::drop(val); assert_eq!(was_called.load(Ordering::SeqCst), true); } #[test] fn test_noop_drop_elsewhere() { use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread; let was_called = Arc::new(AtomicBool::new(false)); { let was_called = was_called.clone(); thread::spawn(move || { struct X(Arc); impl Drop for X { fn drop(&mut self) { self.0.store(true, Ordering::SeqCst); } } let val = SemiSticky::new(X(was_called.clone())); assert!( thread::spawn(move || { // moves it here but do not deallocate val.try_get().ok(); }).join() .is_ok() ); assert_eq!(was_called.load(Ordering::SeqCst), false); }).join() .unwrap(); } assert_eq!(was_called.load(Ordering::SeqCst), true); } #[test] fn test_rc_sending() { use std::rc::Rc; use std::thread; let val = SemiSticky::new(Rc::new(true)); thread::spawn(move || { assert!(val.try_get().is_err()); }).join().unwrap(); } fragile-0.3.0/src/sticky.rs010064400007650000024000000250411333721007300140060ustar0000000000000000use std::cell::UnsafeCell; use std::cmp; use std::collections::HashMap; use std::fmt; use std::marker::PhantomData; use std::mem; use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use errors::InvalidThreadAccess; fn next_item_id() -> usize { static mut COUNTER: AtomicUsize = ATOMIC_USIZE_INIT; unsafe { COUNTER.fetch_add(1, Ordering::SeqCst) } } struct Registry(HashMap, Box)>)>); impl Drop for Registry { fn drop(&mut self) { for (_, value) in self.0.iter() { (value.1)(&value.0); } } } thread_local!(static REGISTRY: UnsafeCell = UnsafeCell::new(Registry(Default::default()))); /// A `Sticky` keeps a value T stored in a thread. /// /// This type works similar in nature to `Fragile` and exposes the /// same interface. The difference is that whereas `Fragile` has /// its destructor called in the thread where the value was sent, a /// `Sticky` that is moved to another thread will have the internal /// destructor called when the originating thread tears down. /// /// As this uses TLS internally the general rules about the platform limitations /// of destructors for TLS apply. pub struct Sticky { item_id: usize, _marker: PhantomData<*mut T>, } impl Drop for Sticky { fn drop(&mut self) { if mem::needs_drop::() { unsafe { if self.is_valid() { self.unsafe_take_value(); } } } } } impl Sticky { /// Creates a new `Sticky` wrapping a `value`. /// /// The value that is moved into the `Sticky` can be non `Send` and /// will be anchored to the thread that created the object. If the /// sticky wrapper type ends up being send from thread to thread /// only the original thread can interact with the value. pub fn new(value: T) -> Self { let item_id = next_item_id(); REGISTRY.with(|registry| unsafe { (*registry.get()).0.insert( item_id, ( UnsafeCell::new(Box::into_raw(Box::new(value)) as *mut _), Box::new(|cell| { let b: Box = Box::from_raw(*(cell.get() as *mut *mut T)); mem::drop(b); }), ), ); }); Sticky { item_id: item_id, _marker: PhantomData, } } #[inline(always)] fn with_value>) -> R, R>(&self, f: F) -> R { REGISTRY.with(|registry| unsafe { let reg = &(*(*registry).get()).0; if let Some(item) = reg.get(&self.item_id) { f(mem::transmute(&item.0)) } else { panic!("trying to access wrapped value in sticky container from incorrect thread."); } }) } /// Returns `true` if the access is valid. /// /// This will be `false` if the value was sent to another thread. #[inline(always)] pub fn is_valid(&self) -> bool { // We use `try-with` here to avoid crashing if the TLS is already tearing down. unsafe { REGISTRY.try_with(|registry| (*registry.get()).0.contains_key(&self.item_id)).unwrap_or(false) } } #[inline(always)] fn assert_thread(&self) { if !self.is_valid() { panic!("trying to access wrapped value in sticky container from incorrect thread."); } } /// Consumes the `Sticky`, returning the wrapped value. /// /// # Panics /// /// Panics if called from a different thread than the one where the /// original value was created. pub fn into_inner(mut self) -> T { self.assert_thread(); unsafe { let rv = self.unsafe_take_value(); mem::forget(self); rv } } unsafe fn unsafe_take_value(&mut self) -> T { let ptr = REGISTRY .with(|registry| (*registry.get()).0.remove(&self.item_id)) .unwrap() .0 .into_inner(); let rv = Box::from_raw(ptr as *mut T); *rv } /// Consumes the `Sticky`, returning the wrapped value if successful. /// /// The wrapped value is returned if this is called from the same thread /// as the one where the original value was created, otherwise the /// `Sticky` is returned as `Err(self)`. pub fn try_into_inner(self) -> Result { if self.is_valid() { Ok(self.into_inner()) } else { Err(self) } } /// Immutably borrows the wrapped value. /// /// # Panics /// /// Panics if the calling thread is not the one that wrapped the value. /// For a non-panicking variant, use [`try_get`](#method.try_get`). pub fn get(&self) -> &T { self.with_value(|value| unsafe { &*value.get() }) } /// Mutably borrows the wrapped value. /// /// # Panics /// /// Panics if the calling thread is not the one that wrapped the value. /// For a non-panicking variant, use [`try_get_mut`](#method.try_get_mut`). pub fn get_mut(&mut self) -> &mut T { self.with_value(|value| unsafe { &mut *value.get() }) } /// Tries to immutably borrow the wrapped value. /// /// Returns `None` if the calling thread is not the one that wrapped the value. pub fn try_get(&self) -> Result<&T, InvalidThreadAccess> { if self.is_valid() { unsafe { Ok(self.with_value(|value| &*value.get())) } } else { Err(InvalidThreadAccess) } } /// Tries to mutably borrow the wrapped value. /// /// Returns `None` if the calling thread is not the one that wrapped the value. pub fn try_get_mut(&mut self) -> Result<&mut T, InvalidThreadAccess> { if self.is_valid() { unsafe { Ok(self.with_value(|value| &mut *value.get())) } } else { Err(InvalidThreadAccess) } } } impl From for Sticky { #[inline] fn from(t: T) -> Sticky { Sticky::new(t) } } impl Clone for Sticky { #[inline] fn clone(&self) -> Sticky { Sticky::new(self.get().clone()) } } impl Default for Sticky { #[inline] fn default() -> Sticky { Sticky::new(T::default()) } } impl PartialEq for Sticky { #[inline] fn eq(&self, other: &Sticky) -> bool { *self.get() == *other.get() } } impl Eq for Sticky {} impl PartialOrd for Sticky { #[inline] fn partial_cmp(&self, other: &Sticky) -> Option { self.get().partial_cmp(&*other.get()) } #[inline] fn lt(&self, other: &Sticky) -> bool { *self.get() < *other.get() } #[inline] fn le(&self, other: &Sticky) -> bool { *self.get() <= *other.get() } #[inline] fn gt(&self, other: &Sticky) -> bool { *self.get() > *other.get() } #[inline] fn ge(&self, other: &Sticky) -> bool { *self.get() >= *other.get() } } impl Ord for Sticky { #[inline] fn cmp(&self, other: &Sticky) -> cmp::Ordering { self.get().cmp(&*other.get()) } } impl fmt::Display for Sticky { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { fmt::Display::fmt(self.get(), f) } } impl fmt::Debug for Sticky { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self.try_get() { Ok(value) => f.debug_struct("Sticky").field("value", value).finish(), Err(..) => { struct InvalidPlaceholder; impl fmt::Debug for InvalidPlaceholder { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("") } } f.debug_struct("Sticky") .field("value", &InvalidPlaceholder) .finish() } } } } // similar as for fragile ths type is sync because it only accesses TLS data // which is thread local. There is nothing that needs to be synchronized. unsafe impl Sync for Sticky {} // The entire point of this type is to be Send unsafe impl Send for Sticky {} #[test] fn test_basic() { use std::thread; let val = Sticky::new(true); assert_eq!(val.to_string(), "true"); assert_eq!(val.get(), &true); assert!(val.try_get().is_ok()); thread::spawn(move || { assert!(val.try_get().is_err()); }).join() .unwrap(); } #[test] fn test_mut() { let mut val = Sticky::new(true); *val.get_mut() = false; assert_eq!(val.to_string(), "false"); assert_eq!(val.get(), &false); } #[test] #[should_panic] fn test_access_other_thread() { use std::thread; let val = Sticky::new(true); thread::spawn(move || { val.get(); }).join() .unwrap(); } #[test] fn test_drop_same_thread() { use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; let was_called = Arc::new(AtomicBool::new(false)); struct X(Arc); impl Drop for X { fn drop(&mut self) { self.0.store(true, Ordering::SeqCst); } } let val = Sticky::new(X(was_called.clone())); mem::drop(val); assert_eq!(was_called.load(Ordering::SeqCst), true); } #[test] fn test_noop_drop_elsewhere() { use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread; let was_called = Arc::new(AtomicBool::new(false)); { let was_called = was_called.clone(); thread::spawn(move || { struct X(Arc); impl Drop for X { fn drop(&mut self) { self.0.store(true, Ordering::SeqCst); } } let val = Sticky::new(X(was_called.clone())); assert!( thread::spawn(move || { // moves it here but do not deallocate val.try_get().ok(); }).join() .is_ok() ); assert_eq!(was_called.load(Ordering::SeqCst), false); }).join() .unwrap(); } assert_eq!(was_called.load(Ordering::SeqCst), true); } #[test] fn test_rc_sending() { use std::rc::Rc; use std::thread; let val = Sticky::new(Rc::new(true)); thread::spawn(move || { assert!(val.try_get().is_err()); }).join().unwrap(); }