diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index d2ef454..c881116 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -1,6 +1,20 @@ name: Rust -on: [push] +on: + push: + branches: + - master + paths: + - '**/*.rs' + - '**/Cargo.toml' + - '.github/workflows/rust.yml' + pull_request: + branches: + - master + paths: + - '**/*.rs' + - '**/Cargo.toml' + - '.github/workflows/rust.yml' jobs: build: @@ -9,7 +23,9 @@ jobs: steps: - uses: actions/checkout@v1 + - name: Setup Rust Toolchain + run: rustup toolchain install nightly - name: Build - run: cargo build --all-features --verbose + run: cargo +nightly build --all-features --verbose - name: Run tests - run: cargo test --all-features --verbose + run: cargo +nightly test --all-features --verbose diff --git a/.gitignore b/.gitignore index 6aa1064..91143dc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ /target/ **/*.rs.bk Cargo.lock +.vscode/ diff --git a/Cargo.toml b/Cargo.toml index 0b96a34..5b0705c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,8 +1,7 @@ [package] -name = "send_wrapper" -version = "0.6.0" -edition = "2018" -authors = ["Thomas Keh"] +name = "compio-send-wrapper" +version = "0.7.0" +edition = "2024" license = "MIT/Apache-2.0" description = """ This Rust library implements a wrapper type called SendWrapper which allows you to move around non-Send types @@ -11,13 +10,16 @@ make sure that the wrapper is dropped from within the original thread. If any of a panic occurs.""" keywords = ["send", "wrapper", "thread_local"] readme = "README.md" -repository = "https://github.com/thk1/send_wrapper" -documentation = "https://docs.rs/send_wrapper" +repository = "https://github.com/compio-rs/send_wrapper" +documentation = "https://docs.rs/compio-send-wrapper" categories = ["rust-patterns"] [features] futures = ["futures-core"] +current_thread_id = [] +nightly = ["current_thread_id"] + [dependencies] futures-core = { version = "0.3", optional = true } diff --git a/README.md b/README.md index 5842c00..cab8fbc 100644 --- a/README.md +++ b/README.md @@ -6,27 +6,14 @@ between threads, as long as you access the contained value only from within the make sure that the wrapper is dropped from within the original thread. If any of these constraints is violated, a panic occurs. -The idea for this crate was born in the context of a [`GTK+`]/[`gtk-rs`]-based application. [`GTK+`] applications -are strictly single-threaded. It is not allowed to call any [`GTK+`] method from a thread different to the main -thread. Consequently, all [`gtk-rs`] structs are non-[`Send`]. - -Sometimes you still want to do some work in background. It is possible to enqueue [`GTK+`] calls from there to be -executed in the main thread [using `Glib`]. This way you can know, that the [`gtk-rs`] structs involved are only -accessed in the main thread and will also be dropped there. This crate makes it possible for [`gtk-rs`] structs -to leave the main thread. - # Examples ```rust -use send_wrapper::SendWrapper; +use compio_send_wrapper::SendWrapper; use std::rc::Rc; use std::thread; use std::sync::mpsc::channel; -// This import is important. It allows you to unwrap the value using deref(), -// deref_mut() or Deref coercion. -use std::ops::{Deref, DerefMut}; - // Rc is a non-Send type. let value = Rc::new(42); @@ -38,8 +25,8 @@ let (sender, receiver) = channel(); let t = thread::spawn(move || { - // This would panic (because of dereferencing in wrong thread): - // let value = wrapped_value.deref(); + // This would panic (because of accessing in the wrong thread): + // let value = wrapped_value.get().unwrap(); // Move SendWrapper back to main thread, so it can be dropped from there. // If you leave this out the thread will panic because of dropping from wrong thread. @@ -50,16 +37,10 @@ let t = thread::spawn(move || { let wrapped_value = receiver.recv().unwrap(); // Now you can use the value again. -let value = wrapped_value.deref(); - -// alternatives for dereferencing: -// let value = *wrapped_value; -// let value: &NonSendType = &wrapped_value; +let value = wrapped_value.get().unwrap(); // alternatives for mutable dereferencing (value and wrapped_value must be mutable too, then): -// let mut value = wrapped_value.deref_mut(); -// let mut value = &mut *wrapped_value; -// let mut value: &mut NonSendType = &mut wrapped_value; +// let mut value = wrapped_value.get_mut().unwrap(); ``` @@ -67,13 +48,13 @@ let value = wrapped_value.deref(); To use `SendWrapper` on `Future`s or `Stream`s, you should enable the Cargo feature `futures` first: ```toml -send_wrapper = { version = "0.5", features = ["futures"] } +compio-send-wrapper = { version = "0.7", features = ["futures"] } ``` Then, you can transparently wrap your `Future` or `Stream`: ```rust use futures::{executor, future::{self, BoxFuture}}; -use send_wrapper::SendWrapper; +use compio_send_wrapper::SendWrapper; // `Rc` is a `!Send` type, let value = Rc::new(42); @@ -98,13 +79,10 @@ See [CHANGELOG.md](CHANGELOG.md) # License -`send_wrapper` is distributed under the terms of both the MIT license and the Apache License (Version 2.0). +`compio-send-wrapper` is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See LICENSE-APACHE, and LICENSE-MIT for details. [Rust]: https://www.rust-lang.org [`Send`]: https://doc.rust-lang.org/std/marker/trait.Send.html -[`gtk-rs`]: http://gtk-rs.org/ -[`GTK+`]: https://www.gtk.org/ -[using `Glib`]: http://gtk-rs.org/docs/glib/source/fn.idle_add.html diff --git a/rustfmt.toml b/rustfmt.toml index 218e203..c45153d 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1 +1,19 @@ -hard_tabs = true +unstable_features = true + +style_edition = "2024" + +group_imports = "StdExternalCrate" +imports_granularity = "Crate" +reorder_imports = true + +wrap_comments = true +normalize_comments = true + +reorder_impl_items = true +condense_wildcard_suffixes = true +enum_discrim_align_threshold = 20 +use_field_init_shorthand = true + +format_strings = true +format_code_in_doc_comments = true +format_macro_matchers = true diff --git a/src/futures.rs b/src/futures.rs index 7682816..8100f7e 100644 --- a/src/futures.rs +++ b/src/futures.rs @@ -1,99 +1,92 @@ //! [`Future`] and [`Stream`] support for [`SendWrapper`]. -use std::{ - future::Future, - ops::{Deref as _, DerefMut as _}, - pin::Pin, - task, -}; +use std::{future::Future, pin::Pin, task}; use futures_core::Stream; -use crate::SendWrapper; +use crate::{SendWrapper, invalid_deref, invalid_poll}; impl Future for SendWrapper { - type Output = F::Output; + type Output = F::Output; - /// Polls this [`SendWrapper`] [`Future`]. - /// - /// # Panics - /// - /// Polling panics if it is done from a different thread than the one the [`SendWrapper`] - /// instance has been created with. - #[track_caller] - fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll { - self.assert_valid_for_poll(); - // This is safe as `SendWrapper` itself points to the inner `Future`. - // So, as long as `SendWrapper` is pinned, the inner `Future` is pinned too. - unsafe { self.map_unchecked_mut(Self::deref_mut) }.poll(cx) - } + /// Polls this [`SendWrapper`] [`Future`]. + /// + /// # Panics + /// + /// Polling panics if it is done from a different thread than the one the + /// [`SendWrapper`] instance has been created with. + #[track_caller] + fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll { + self.get_pinned_mut() + .unwrap_or_else(|| invalid_poll()) + .poll(cx) + } } impl Stream for SendWrapper { - type Item = S::Item; + type Item = S::Item; - /// Polls this [`SendWrapper`] [`Stream`]. - /// - /// # Panics - /// - /// Polling panics if it is done from a different thread than the one the [`SendWrapper`] - /// instance has been created with. - #[track_caller] - fn poll_next( - self: Pin<&mut Self>, - cx: &mut task::Context<'_>, - ) -> task::Poll> { - self.assert_valid_for_poll(); - // This is safe as `SendWrapper` itself points to the inner `Stream`. - // So, as long as `SendWrapper` is pinned, the inner `Stream` is pinned too. - unsafe { self.map_unchecked_mut(Self::deref_mut) }.poll_next(cx) - } + /// Polls this [`SendWrapper`] [`Stream`]. + /// + /// # Panics + /// + /// Polling panics if it is done from a different thread than the one the + /// [`SendWrapper`] instance has been created with. + #[track_caller] + fn poll_next( + self: Pin<&mut Self>, + cx: &mut task::Context<'_>, + ) -> task::Poll> { + self.get_pinned_mut() + .unwrap_or_else(|| invalid_poll()) + .poll_next(cx) + } - #[inline] - fn size_hint(&self) -> (usize, Option) { - self.deref().size_hint() - } + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.get().unwrap_or_else(|| invalid_deref()).size_hint() + } } #[cfg(test)] mod tests { - use std::thread; + use std::thread; - use futures_executor as executor; - use futures_util::{future, stream, StreamExt}; + use futures_executor as executor; + use futures_util::{StreamExt, future, stream}; - use crate::SendWrapper; + use crate::SendWrapper; - #[test] - fn test_future() { - let w1 = SendWrapper::new(future::ready(42)); - let w2 = w1.clone(); - assert_eq!( - format!("{:?}", executor::block_on(w1)), - format!("{:?}", executor::block_on(w2)), - ); - } + #[test] + fn test_future() { + let w1 = SendWrapper::new(future::ready(42)); + let w2 = w1.clone(); + assert_eq!( + format!("{:?}", executor::block_on(w1)), + format!("{:?}", executor::block_on(w2)), + ); + } - #[test] - fn test_future_panic() { - let w = SendWrapper::new(future::ready(42)); - let t = thread::spawn(move || executor::block_on(w)); - assert!(t.join().is_err()); - } + #[test] + fn test_future_panic() { + let w = SendWrapper::new(future::ready(42)); + let t = thread::spawn(move || executor::block_on(w)); + assert!(t.join().is_err()); + } - #[test] - fn test_stream() { - let mut w1 = SendWrapper::new(stream::once(future::ready(42))); - let mut w2 = SendWrapper::new(stream::once(future::ready(42))); - assert_eq!( - format!("{:?}", executor::block_on(w1.next())), - format!("{:?}", executor::block_on(w2.next())), - ); - } + #[test] + fn test_stream() { + let mut w1 = SendWrapper::new(stream::once(future::ready(42))); + let mut w2 = SendWrapper::new(stream::once(future::ready(42))); + assert_eq!( + format!("{:?}", executor::block_on(w1.next())), + format!("{:?}", executor::block_on(w2.next())), + ); + } - #[test] - fn test_stream_panic() { - let mut w = SendWrapper::new(stream::once(future::ready(42))); - let t = thread::spawn(move || executor::block_on(w.next())); - assert!(t.join().is_err()); - } + #[test] + fn test_stream_panic() { + let mut w = SendWrapper::new(stream::once(future::ready(42))); + let t = thread::spawn(move || executor::block_on(w.next())); + assert!(t.join().is_err()); + } } diff --git a/src/lib.rs b/src/lib.rs index ff07dec..97eb464 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ // Copyright 2017 Thomas Keh. +// Copyright 2024 compio-rs // // Licensed under the Apache License, Version 2.0 or the MIT license @@ -6,31 +7,19 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! This [Rust] library implements a wrapper type called [`SendWrapper`] which allows you to move around non-[`Send`] types -//! between threads, as long as you access the contained value only from within the original thread. You also have to -//! make sure that the wrapper is dropped from within the original thread. If any of these constraints is violated, -//! a panic occurs. [`SendWrapper`] implements [`Send`] and [`Sync`] for any type `T`. -//! -//! The idea for this library was born in the context of a [`GTK+`]/[`gtk-rs`]-based application. [`GTK+`] applications -//! are strictly single-threaded. It is not allowed to call any [`GTK+`] method from a thread different to the main -//! thread. Consequently, all [`gtk-rs`] structs are non-[`Send`]. -//! -//! Sometimes you still want to do some work in background. It is possible to enqueue [`GTK+`] calls from there to be -//! executed in the main thread [using `Glib`]. This way you can know, that the [`gtk-rs`] structs involved are only -//! accessed in the main thread and will also be dropped there. This library makes it possible that [`gtk-rs`] structs -//! can leave the main thread at all. +//! This [Rust] library implements a wrapper type called [`SendWrapper`] which +//! allows you to move around non-[`Send`] types between threads, as long as you +//! access the contained value only from within the original thread. You also +//! have to make sure that the wrapper is dropped from within the original +//! thread. If any of these constraints is violated, a panic occurs. +//! [`SendWrapper`] implements [`Send`] and [`Sync`] for any type `T`. //! //! # Examples //! //! ```rust -//! use send_wrapper::SendWrapper; -//! use std::rc::Rc; -//! use std::thread; -//! use std::sync::mpsc::channel; +//! use std::{rc::Rc, sync::mpsc::channel, thread}; //! -//! // This import is important if you want to use deref() or -//! // deref_mut() instead of Deref coercion. -//! use std::ops::{Deref, DerefMut}; +//! use compio_send_wrapper::SendWrapper; //! //! // Rc is a non-Send type. //! let value = Rc::new(42); @@ -42,369 +31,511 @@ //! let (sender, receiver) = channel(); //! //! let t = thread::spawn(move || { +//! // This would panic (because of accessing in the wrong thread): +//! // let value = wrapped_value.get().unwrap(); //! -//! // This would panic (because of dereferencing in wrong thread): -//! // let value = wrapped_value.deref(); -//! -//! // Move SendWrapper back to main thread, so it can be dropped from there. -//! // If you leave this out the thread will panic because of dropping from wrong thread. -//! sender.send(wrapped_value).unwrap(); -//! +//! // Move SendWrapper back to main thread, so it can be dropped from there. +//! // If you leave this out the thread will panic because of dropping from wrong thread. +//! sender.send(wrapped_value).unwrap(); //! }); //! //! let wrapped_value = receiver.recv().unwrap(); //! //! // Now you can use the value again. -//! let value = wrapped_value.deref(); -//! -//! // alternatives for dereferencing: -//! let value = &*wrapped_value; -//! let value: &Rc<_> = &wrapped_value; +//! let value = wrapped_value.get().unwrap(); //! //! let mut wrapped_value = wrapped_value; -//! // alternatives for mutable dereferencing: -//! let value = wrapped_value.deref_mut(); -//! let value = &mut *wrapped_value; -//! let value: &mut Rc<_> = &mut wrapped_value; +//! +//! // You can also get a mutable reference to the value. +//! let value = wrapped_value.get_mut().unwrap(); //! ``` //! //! # Features //! -//! This crate has a single feature called `futures` that enables [`Future`] and [`Stream`] implementations for [`SendWrapper`]. -//! You can enable it in `Cargo.toml` like so: +//! This crate exposes several optional features: +//! +//! - `futures`: Enables [`Future`] and [`Stream`] implementations for +//! [`SendWrapper`]. +//! - `current_thread_id`: Uses the unstable [`std::thread::current_id`] API (on +//! nightly Rust) to track the originating thread more efficiently. +//! - `nightly`: Enables nightly-only, experimental functionality used by this +//! crate (including support for `current_thread_id` as configured in +//! `Cargo.toml`). +//! +//! You can enable them in `Cargo.toml` like so: //! //! ```toml -//! send_wrapper = { version = "...", features = ["futures"] } +//! compio-send-wrapper = { version = "...", features = ["futures"] } +//! # or, for example: +//! # compio-send-wrapper = { version = "...", features = ["futures", "current_thread_id"] } //! ``` //! //! # License //! -//! `send_wrapper` is distributed under the terms of both the MIT license and the Apache License (Version 2.0). +//! `compio-send-wrapper` is distributed under the terms of both the MIT license +//! and the Apache License (Version 2.0). //! //! See LICENSE-APACHE.txt, and LICENSE-MIT.txt for details. //! //! [Rust]: https://www.rust-lang.org -//! [`gtk-rs`]: http://gtk-rs.org/ -//! [`GTK+`]: https://www.gtk.org/ -//! [using `Glib`]: http://gtk-rs.org/docs/glib/source/fn.idle_add.html //! [`Future`]: std::future::Future //! [`Stream`]: futures_core::Stream // To build docs locally use `RUSTDOCFLAGS="--cfg docsrs" cargo doc --open --all-features` #![cfg_attr(docsrs, feature(doc_cfg))] +#![cfg_attr(feature = "current_thread_id", feature(current_thread_id))] +#![warn(missing_docs)] #[cfg(feature = "futures")] #[cfg_attr(docsrs, doc(cfg(feature = "futures")))] mod futures; -use std::fmt; -use std::mem::{self, ManuallyDrop}; -use std::ops::{Deref, DerefMut, Drop}; -use std::thread::{self, ThreadId}; +#[cfg(feature = "current_thread_id")] +use std::thread::current_id; +use std::{ + fmt, + mem::{self, ManuallyDrop}, + pin::Pin, + thread::{self, ThreadId}, +}; + +#[cfg(not(feature = "current_thread_id"))] +mod imp { + use std::{ + cell::Cell, + thread::{self, ThreadId}, + }; + thread_local! { + static THREAD_ID: Cell = Cell::new(thread::current().id()); + } + + pub fn current_id() -> ThreadId { + THREAD_ID.get() + } +} + +#[cfg(not(feature = "current_thread_id"))] +use imp::current_id; -/// A wrapper which allows you to move around non-[`Send`]-types between threads, as long as you access the contained -/// value only from within the original thread and make sure that it is dropped from within the original thread. +/// A wrapper which allows you to move around non-[`Send`]-types between +/// threads, as long as you access the contained value only from within the +/// original thread and make sure that it is dropped from within the original +/// thread. pub struct SendWrapper { - data: ManuallyDrop, - thread_id: ThreadId, + data: ManuallyDrop, + thread_id: ThreadId, } impl SendWrapper { - /// Create a `SendWrapper` wrapper around a value of type `T`. - /// The wrapper takes ownership of the value. - pub fn new(data: T) -> SendWrapper { - SendWrapper { - data: ManuallyDrop::new(data), - thread_id: thread::current().id(), - } - } - - /// Returns `true` if the value can be safely accessed from within the current thread. - pub fn valid(&self) -> bool { - self.thread_id == thread::current().id() - } - - /// Takes the value out of the `SendWrapper`. - /// - /// # Panics - /// - /// Panics if it is called from a different thread than the one the `SendWrapper` instance has - /// been created with. - #[track_caller] - pub fn take(self) -> T { - self.assert_valid_for_deref(); - - // Prevent drop() from being called, as it would drop `self.data` twice - let mut this = ManuallyDrop::new(self); - - // Safety: - // - We've just checked that it's valid to access `T` from the current thread - // - We only move out from `self.data` here and in drop, so `self.data` is present - unsafe { ManuallyDrop::take(&mut this.data) } - } - - #[track_caller] - fn assert_valid_for_deref(&self) { - if !self.valid() { - invalid_deref() - } - } - - #[track_caller] - fn assert_valid_for_poll(&self) { - if !self.valid() { - invalid_poll() - } - } + /// Create a `SendWrapper` wrapper around a value of type `T`. + /// The wrapper takes ownership of the value. + #[inline] + pub fn new(data: T) -> SendWrapper { + SendWrapper { + data: ManuallyDrop::new(data), + thread_id: current_id(), + } + } + + /// Returns `true` if the value can be safely accessed from within the + /// current thread. + #[inline] + pub fn valid(&self) -> bool { + self.thread_id == current_id() + } + + /// Takes the value out of the `SendWrapper`. + /// + /// # Safety + /// + /// The caller should be in the same thread as the creator. + pub unsafe fn take_unchecked(self) -> T { + // Prevent drop() from being called, as it would drop `self.data` twice + let mut this = ManuallyDrop::new(self); + + // Safety: + // - The caller of this unsafe function guarantees that it's valid to access `T` + // from the current thread (the safe `take` method enforces this precondition + // before calling `take_unchecked`). + // - We only move out from `self.data` here and in drop, so `self.data` is + // present + unsafe { ManuallyDrop::take(&mut this.data) } + } + + /// Takes the value out of the `SendWrapper`. + /// + /// # Panics + /// + /// Panics if it is called from a different thread than the one the + /// `SendWrapper` instance has been created with. + #[track_caller] + pub fn take(self) -> T { + if self.valid() { + // SAFETY: the same thread as the creator + unsafe { self.take_unchecked() } + } else { + invalid_deref() + } + } + + /// Returns a reference to the contained value. + /// + /// # Safety + /// + /// The caller should be in the same thread as the creator. + #[inline] + pub unsafe fn get_unchecked(&self) -> &T { + &self.data + } + + /// Returns a mutable reference to the contained value. + /// + /// # Safety + /// + /// The caller should be in the same thread as the creator. + #[inline] + pub unsafe fn get_unchecked_mut(&mut self) -> &mut T { + &mut self.data + } + + /// Returns a pinned reference to the contained value. + /// + /// # Safety + /// + /// The caller should be in the same thread as the creator. + #[inline] + pub unsafe fn get_unchecked_pinned(self: Pin<&Self>) -> Pin<&T> { + // SAFETY: as long as `SendWrapper` is pinned, the inner data is pinned too. + unsafe { self.map_unchecked(|s| &*s.data) } + } + + /// Returns a pinned mutable reference to the contained value. + /// + /// # Safety + /// + /// The caller should be in the same thread as the creator. + #[inline] + pub unsafe fn get_unchecked_pinned_mut(self: Pin<&mut Self>) -> Pin<&mut T> { + // SAFETY: as long as `SendWrapper` is pinned, the inner data is pinned too. + unsafe { self.map_unchecked_mut(|s| &mut *s.data) } + } + + /// Returns a reference to the contained value, if valid. + #[inline] + pub fn get(&self) -> Option<&T> { + if self.valid() { Some(&self.data) } else { None } + } + + /// Returns a mutable reference to the contained value, if valid. + #[inline] + pub fn get_mut(&mut self) -> Option<&mut T> { + if self.valid() { + Some(&mut self.data) + } else { + None + } + } + + /// Returns a pinned reference to the contained value, if valid. + #[inline] + pub fn get_pinned(self: Pin<&Self>) -> Option> { + if self.valid() { + // SAFETY: the same thread as the creator + Some(unsafe { self.get_unchecked_pinned() }) + } else { + None + } + } + + /// Returns a pinned mutable reference to the contained value, if valid. + #[inline] + pub fn get_pinned_mut(self: Pin<&mut Self>) -> Option> { + if self.valid() { + // SAFETY: the same thread as the creator + Some(unsafe { self.get_unchecked_pinned_mut() }) + } else { + None + } + } + + /// Returns a tracker that can be used to check if the current thread is + /// the same as the creator thread. + #[inline] + pub fn tracker(&self) -> SendWrapper<()> { + SendWrapper { + data: ManuallyDrop::new(()), + thread_id: self.thread_id, + } + } } unsafe impl Send for SendWrapper {} unsafe impl Sync for SendWrapper {} -impl Deref for SendWrapper { - type Target = T; - - /// Returns a reference to the contained value. - /// - /// # Panics - /// - /// Dereferencing panics if it is done from a different thread than the one the `SendWrapper` instance has been - /// created with. - #[track_caller] - fn deref(&self) -> &T { - self.assert_valid_for_deref(); - - // Access the value. - // - // Safety: We just checked that it is valid to access `T` on the current thread. - &*self.data - } -} - -impl DerefMut for SendWrapper { - /// Returns a mutable reference to the contained value. - /// - /// # Panics - /// - /// Dereferencing panics if it is done from a different thread than the one the `SendWrapper` instance has been - /// created with. - #[track_caller] - fn deref_mut(&mut self) -> &mut T { - self.assert_valid_for_deref(); - - // Access the value. - // - // Safety: We just checked that it is valid to access `T` on the current thread. - &mut *self.data - } -} - impl Drop for SendWrapper { - /// Drops the contained value. - /// - /// # Panics - /// - /// Dropping panics if it is done from a different thread than the one the `SendWrapper` instance has been - /// created with. - /// - /// Exceptions: - /// - There is no extra panic if the thread is already panicking/unwinding. - /// This is because otherwise there would be double panics (usually resulting in an abort) - /// when dereferencing from a wrong thread. - /// - If `T` has a trivial drop ([`needs_drop::()`] is false) then this method never panics. - /// - /// [`needs_drop::()`]: std::mem::needs_drop - #[track_caller] - fn drop(&mut self) { - // If the drop is trivial (`needs_drop` = false), then dropping `T` can't access it - // and so it can be safely dropped on any thread. - if !mem::needs_drop::() || self.valid() { - unsafe { - // Drop the inner value - // - // Safety: - // - We've just checked that it's valid to drop `T` on this thread - // - We only move out from `self.data` here and in drop, so `self.data` is present - ManuallyDrop::drop(&mut self.data); - } - } else { - invalid_drop() - } - } + /// Drops the contained value. + /// + /// # Panics + /// + /// Dropping panics if it is done from a different thread than the one the + /// `SendWrapper` instance has been created with. + /// + /// Exceptions: + /// - There is no extra panic if the thread is already panicking/unwinding. + /// This is because otherwise there would be double panics (usually + /// resulting in an abort) when dereferencing from a wrong thread. + /// - If `T` has a trivial drop ([`needs_drop::()`] is false) then this + /// method never panics. + /// + /// [`needs_drop::()`]: std::mem::needs_drop + #[track_caller] + fn drop(&mut self) { + // If the drop is trivial (`needs_drop` = false), then dropping `T` can't access + // it and so it can be safely dropped on any thread. + if !mem::needs_drop::() || self.valid() { + unsafe { + // Drop the inner value + // + // SAFETY: + // - We've just checked that it's valid to drop `T` on this thread + // - We only move out from `self.data` here and in drop, so `self.data` is + // present + ManuallyDrop::drop(&mut self.data); + } + } else { + invalid_drop() + } + } } impl fmt::Debug for SendWrapper { - /// Formats the value using the given formatter. - /// - /// # Panics - /// - /// Formatting panics if it is done from a different thread than the one - /// the `SendWrapper` instance has been created with. - #[track_caller] - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("SendWrapper") - .field("data", self.deref()) - .field("thread_id", &self.thread_id) - .finish() - } + /// Formats the value using the given formatter. + /// + /// If the `SendWrapper` is formatted from a different thread than the + /// one it was created on, the `data` field is shown as `""` + /// instead of causing a panic. + #[track_caller] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut f = f.debug_struct("SendWrapper"); + if let Some(data) = self.get() { + f.field("data", data); + } else { + f.field("data", &""); + } + f.field("thread_id", &self.thread_id).finish() + } } impl Clone for SendWrapper { - /// Returns a copy of the value. - /// - /// # Panics - /// - /// Cloning panics if it is done from a different thread than the one - /// the `SendWrapper` instance has been created with. - #[track_caller] - fn clone(&self) -> Self { - Self::new(self.deref().clone()) - } + /// Returns a copy of the value. + /// + /// # Panics + /// + /// Cloning panics if it is done from a different thread than the one + /// the `SendWrapper` instance has been created with. + #[track_caller] + fn clone(&self) -> Self { + Self::new(self.get().unwrap_or_else(|| invalid_deref()).clone()) + } } #[cold] #[inline(never)] #[track_caller] fn invalid_deref() -> ! { - const DEREF_ERROR: &'static str = "Dereferenced SendWrapper variable from a thread different to the one it has been created with."; + const DEREF_ERROR: &str = "Accessed SendWrapper variable from a thread different to the \ + one it has been created with."; - panic!("{}", DEREF_ERROR) + panic!("{}", DEREF_ERROR) } #[cold] #[inline(never)] #[track_caller] +#[cfg(feature = "futures")] fn invalid_poll() -> ! { - const POLL_ERROR: &'static str = "Polling SendWrapper variable from a thread different to the one it has been created with."; + const POLL_ERROR: &str = "Polling SendWrapper variable from a thread different to the one \ + it has been created with."; - panic!("{}", POLL_ERROR) + panic!("{}", POLL_ERROR) } #[cold] #[inline(never)] #[track_caller] fn invalid_drop() { - const DROP_ERROR: &'static str = "Dropped SendWrapper variable from a thread different to the one it has been created with."; - - if !std::thread::panicking() { - // panic because of dropping from wrong thread - // only do this while not unwinding (could be caused by deref from wrong thread) - panic!("{}", DROP_ERROR) - } + const DROP_ERROR: &str = "Dropped SendWrapper variable from a thread different to the one \ + it has been created with."; + + if !thread::panicking() { + // panic because of dropping from wrong thread + // only do this while not unwinding (could be caused by deref from wrong thread) + panic!("{}", DROP_ERROR) + } } #[cfg(test)] mod tests { - use std::ops::Deref; - use std::rc::Rc; - use std::sync::mpsc::channel; - use std::sync::Arc; - use std::thread; - - use super::SendWrapper; - - #[test] - fn test_deref() { - let (sender, receiver) = channel(); - let w = SendWrapper::new(Rc::new(42)); - { - let _x = w.deref(); - } - let t = thread::spawn(move || { - // move SendWrapper back to main thread, so it can be dropped from there - sender.send(w).unwrap(); - }); - let w2 = receiver.recv().unwrap(); - { - let _x = w2.deref(); - } - assert!(t.join().is_ok()); - } - - #[test] - fn test_deref_panic() { - let w = SendWrapper::new(Rc::new(42)); - let t = thread::spawn(move || { - let _x = w.deref(); - }); - let join_result = t.join(); - assert!(join_result.is_err()); - } - - #[test] - fn test_drop_panic() { - let w = SendWrapper::new(Rc::new(42)); - let t = thread::spawn(move || { - let _x = w; - }); - let join_result = t.join(); - assert!(join_result.is_err()); - } - - #[test] - fn test_valid() { - let w = SendWrapper::new(Rc::new(42)); - assert!(w.valid()); - thread::spawn(move || { - assert!(!w.valid()); - }); - } - - #[test] - fn test_take() { - let w = SendWrapper::new(Rc::new(42)); - let inner: Rc = w.take(); - assert_eq!(42, *inner); - } - - #[test] - fn test_take_panic() { - let w = SendWrapper::new(Rc::new(42)); - let t = thread::spawn(move || { - let _ = w.take(); - }); - assert!(t.join().is_err()); - } - - #[test] - fn test_sync() { - // Arc can only be sent to another thread if T Sync - let arc = Arc::new(SendWrapper::new(42)); - thread::spawn(move || { - let _ = arc; - }); - } - - #[test] - fn test_debug() { - let w = SendWrapper::new(Rc::new(42)); - let info = format!("{:?}", w); - assert!(info.contains("SendWrapper {")); - assert!(info.contains("data: 42,")); - assert!(info.contains("thread_id: ThreadId(")); - } - - #[test] - fn test_debug_panic() { - let w = SendWrapper::new(Rc::new(42)); - let t = thread::spawn(move || { - let _ = format!("{:?}", w); - }); - assert!(t.join().is_err()); - } - - #[test] - fn test_clone() { - let w1 = SendWrapper::new(Rc::new(42)); - let w2 = w1.clone(); - assert_eq!(format!("{:?}", w1), format!("{:?}", w2)); - } - - #[test] - fn test_clone_panic() { - let w = SendWrapper::new(Rc::new(42)); - let t = thread::spawn(move || { - let _ = w.clone(); - }); - assert!(t.join().is_err()); - } + use std::{ + pin::Pin, + rc::Rc, + sync::{Arc, mpsc::channel}, + thread, + }; + + use super::SendWrapper; + + #[test] + fn get_and_get_mut_on_creator_thread_and_pinned_variants() { + let mut wrapper = SendWrapper::new(1_i32); + + // On the creator thread, the plain accessors should return Some. + let r = wrapper.get(); + assert!(r.is_some()); + assert_eq!(*r.unwrap(), 1); + + let r_mut = wrapper.get_mut(); + assert!(r_mut.is_some()); + *r_mut.unwrap() = 2; + + // The change via get_mut should be visible via get as well. + let r_after = wrapper.get(); + assert!(r_after.is_some()); + assert_eq!(*r_after.unwrap(), 2); + + // Pinned shared reference should also succeed on the creator thread. + let pinned = Pin::new(&wrapper); + let pinned_ref = pinned.get_pinned(); + assert!(pinned_ref.is_some()); + assert_eq!(*pinned_ref.unwrap(), 2); + + // Pinned mutable reference should succeed and allow mutation. + let mut wrapper2 = SendWrapper::new(10_i32); + let pinned_mut = Pin::new(&mut wrapper2); + let pinned_mut_ref = pinned_mut.get_pinned_mut(); + assert!(pinned_mut_ref.is_some()); + *pinned_mut_ref.unwrap() = 11; + + let after_mut = wrapper2.get(); + assert!(after_mut.is_some()); + assert_eq!(*after_mut.unwrap(), 11); + } + + #[test] + fn accessors_return_none_on_non_creator_thread() { + let mut wrapper = SendWrapper::new(123_i32); + + // Move the wrapper to another thread; that thread is not the creator. + let handle = thread::spawn(move || { + // Plain accessors should return None on non-creator thread. + assert!(wrapper.get().is_none()); + assert!(wrapper.get_mut().is_none()); + + // Pinned accessors should also return None on non-creator thread. + let pinned = Pin::new(&wrapper); + assert!(pinned.get_pinned().is_none()); + + let mut wrapper = wrapper; + let pinned_mut = Pin::new(&mut wrapper); + assert!(pinned_mut.get_pinned_mut().is_none()); + }); + + handle.join().unwrap(); + } + + #[test] + fn test_valid() { + let (sender, receiver) = channel(); + let w = SendWrapper::new(Rc::new(42)); + assert!(w.valid()); + let t = thread::spawn(move || { + // move SendWrapper back to main thread, so it can be dropped from there + sender.send(w).unwrap(); + }); + let w2 = receiver.recv().unwrap(); + assert!(w2.valid()); + assert!(t.join().is_ok()); + } + + #[test] + fn test_invalid() { + let w = SendWrapper::new(Rc::new(42)); + let t = thread::spawn(move || { + assert!(!w.valid()); + w + }); + let join_result = t.join(); + assert!(join_result.is_ok()); + } + + #[test] + fn test_drop_panic() { + let w = SendWrapper::new(Rc::new(42)); + let t = thread::spawn(move || { + drop(w); + }); + let join_result = t.join(); + assert!(join_result.is_err()); + } + + #[test] + fn test_take() { + let w = SendWrapper::new(Rc::new(42)); + let inner: Rc = w.take(); + assert_eq!(42, *inner); + } + + #[test] + fn test_take_panic() { + let w = SendWrapper::new(Rc::new(42)); + let t = thread::spawn(move || { + let _ = w.take(); + }); + assert!(t.join().is_err()); + } + #[test] + fn test_sync() { + // Arc can only be sent to another thread if T Sync + let arc = Arc::new(SendWrapper::new(42)); + thread::spawn(move || { + let _ = arc; + }); + } + + #[test] + fn test_debug() { + let w = SendWrapper::new(Rc::new(42)); + let info = format!("{:?}", w); + assert!(info.contains("SendWrapper {")); + assert!(info.contains("data: 42,")); + assert!(info.contains("thread_id: ThreadId(")); + } + + #[test] + fn test_debug_invalid() { + let w = SendWrapper::new(Rc::new(42)); + let t = thread::spawn(move || { + let info = format!("{:?}", w); + assert!(info.contains("SendWrapper {")); + assert!(info.contains("data: \"\",")); + assert!(info.contains("thread_id: ThreadId(")); + w + }); + assert!(t.join().is_ok()); + } + + #[test] + fn test_clone() { + let w1 = SendWrapper::new(Rc::new(42)); + let w2 = w1.clone(); + assert_eq!(format!("{:?}", w1), format!("{:?}", w2)); + } + + #[test] + fn test_clone_panic() { + let w = SendWrapper::new(Rc::new(42)); + let t = thread::spawn(move || { + let _ = w.clone(); + }); + assert!(t.join().is_err()); + } }