Import send_wrapper 0.6.0 upstream upstream/0.6.0
authorDongHun Kwak <dh0128.kwak@samsung.com>
Thu, 20 Apr 2023 00:46:47 +0000 (09:46 +0900)
committerDongHun Kwak <dh0128.kwak@samsung.com>
Thu, 20 Apr 2023 00:46:47 +0000 (09:46 +0900)
13 files changed:
.cargo_vcs_info.json [new file with mode: 0644]
.editorconfig [new file with mode: 0644]
.github/workflows/rust.yml [new file with mode: 0644]
.gitignore [new file with mode: 0644]
CHANGELOG.md [new file with mode: 0644]
Cargo.toml [new file with mode: 0644]
Cargo.toml.orig [new file with mode: 0644]
LICENSE-APACHE.txt [new file with mode: 0644]
LICENSE-MIT.txt [new file with mode: 0644]
README.md [new file with mode: 0644]
rustfmt.toml [new file with mode: 0644]
src/futures.rs [new file with mode: 0644]
src/lib.rs [new file with mode: 0644]

diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json
new file mode 100644 (file)
index 0000000..829efc4
--- /dev/null
@@ -0,0 +1,5 @@
+{
+  "git": {
+    "sha1": "1d005016d15a301af42e5a3fdc1369d9badb1f23"
+  }
+}
diff --git a/.editorconfig b/.editorconfig
new file mode 100644 (file)
index 0000000..455ebb0
--- /dev/null
@@ -0,0 +1,10 @@
+# EditorConfig
+# http://EditorConfig.org
+
+root = true
+
+[*]
+end_of_line = lf
+indent_style = tab
+charset = utf-8
+trim_trailing_whitespace = true
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml
new file mode 100644 (file)
index 0000000..d2ef454
--- /dev/null
@@ -0,0 +1,15 @@
+name: Rust
+
+on: [push]
+
+jobs:
+  build:
+
+    runs-on: ubuntu-latest
+
+    steps:
+    - uses: actions/checkout@v1
+    - name: Build
+      run: cargo build --all-features --verbose
+    - name: Run tests
+      run: cargo test --all-features --verbose
diff --git a/.gitignore b/.gitignore
new file mode 100644 (file)
index 0000000..6aa1064
--- /dev/null
@@ -0,0 +1,3 @@
+/target/
+**/*.rs.bk
+Cargo.lock
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644 (file)
index 0000000..0de9bc2
--- /dev/null
@@ -0,0 +1,16 @@
+# Changelog
+
+## [0.5.0] - 2020-10-14
+- add transparent wrapping of `Future` and `Stream` types via new cargo feature `futures`
+
+## [0.4.0] - 2019-11-18
+- add `Clone` and `Debug` implementations
+
+## [0.3.0] - 2019-10-16
+- implement `Sync` marker trait
+
+## [0.2.0] - 2017-10-04
+- add `take()` method
+
+## [0.1.0] - 2017-09-07
+- initial release
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644 (file)
index 0000000..1a240fc
--- /dev/null
@@ -0,0 +1,38 @@
+# 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]
+edition = "2018"
+name = "send_wrapper"
+version = "0.6.0"
+authors = ["Thomas Keh"]
+description = "This Rust library implements a wrapper type called SendWrapper which allows you to move around non-Send types\nbetween threads, as long as you access the contained value only from within the original thread. You also have to\nmake sure that the wrapper is dropped from within the original thread. If any of these constraints is violated,\na panic occurs."
+documentation = "https://docs.rs/send_wrapper"
+readme = "README.md"
+keywords = ["send", "wrapper", "thread_local"]
+categories = ["rust-patterns"]
+license = "MIT/Apache-2.0"
+repository = "https://github.com/thk1/send_wrapper"
+[package.metadata.docs.rs]
+all-features = true
+rustdoc-args = ["--cfg", "docsrs"]
+[dependencies.futures-core]
+version = "0.3"
+optional = true
+[dev-dependencies.futures-executor]
+version = "0.3"
+
+[dev-dependencies.futures-util]
+version = "0.3"
+
+[features]
+futures = ["futures-core"]
diff --git a/Cargo.toml.orig b/Cargo.toml.orig
new file mode 100644 (file)
index 0000000..0b96a34
--- /dev/null
@@ -0,0 +1,31 @@
+[package]
+name = "send_wrapper"
+version = "0.6.0"
+edition = "2018"
+authors = ["Thomas Keh"]
+license = "MIT/Apache-2.0"
+description = """
+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."""
+keywords = ["send", "wrapper", "thread_local"]
+readme = "README.md"
+repository = "https://github.com/thk1/send_wrapper"
+documentation = "https://docs.rs/send_wrapper"
+categories = ["rust-patterns"]
+
+[features]
+futures = ["futures-core"]
+
+[dependencies]
+futures-core = { version = "0.3", optional = true }
+
+[dev-dependencies]
+futures-executor = "0.3"
+futures-util = "0.3"
+
+[package.metadata.docs.rs]
+all-features = true
+# Needed to add "Available on crate feature `futures` only." messages to docs
+rustdoc-args = ["--cfg", "docsrs"]
diff --git a/LICENSE-APACHE.txt b/LICENSE-APACHE.txt
new file mode 100644 (file)
index 0000000..16fe87b
--- /dev/null
@@ -0,0 +1,201 @@
+                              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.
diff --git a/LICENSE-MIT.txt b/LICENSE-MIT.txt
new file mode 100644 (file)
index 0000000..31aa793
--- /dev/null
@@ -0,0 +1,23 @@
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644 (file)
index 0000000..5842c00
--- /dev/null
+++ b/README.md
@@ -0,0 +1,110 @@
+SendWrapper
+===========
+
+This [Rust] crate 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.
+
+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 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);
+
+// We now wrap the value with `SendWrapper` (value is moved inside).
+let wrapped_value = SendWrapper::new(value);
+
+// A channel allows us to move the wrapped value between threads.
+let (sender, receiver) = channel();
+
+let t = thread::spawn(move || {
+
+       // 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();
+
+});
+
+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;
+
+// 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;
+```
+
+
+## Wrapping `Future`s and `Stream`s
+
+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"] }
+```
+
+Then, you can transparently wrap your `Future` or `Stream`:
+```rust
+use futures::{executor, future::{self, BoxFuture}};
+use send_wrapper::SendWrapper;
+
+// `Rc` is a `!Send` type,
+let value = Rc::new(42);
+// so this `Future` is `!Send` too as increments `Rc`'s inner counter.
+let future = future::lazy(|_| value.clone());
+
+// We now wrap the `future` with `SendWrapper` (value is moved inside),
+let wrapped_future = SendWrapper::new(future);
+// so now it's `Send` + `Sync` (`BoxFuture` trait object contains `Send` requirement).
+let boxed_future: BoxFuture<_> = Box::pin(wrapped_future);
+
+let t = thread::spawn(move || {
+       // This would panic (because `future` is polled in wrong thread):
+       // executor::block_on(boxed_future)
+});
+```
+
+
+# Changelog
+
+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).
+
+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
new file mode 100644 (file)
index 0000000..218e203
--- /dev/null
@@ -0,0 +1 @@
+hard_tabs = true
diff --git a/src/futures.rs b/src/futures.rs
new file mode 100644 (file)
index 0000000..7682816
--- /dev/null
@@ -0,0 +1,99 @@
+//! [`Future`] and [`Stream`] support for [`SendWrapper`].
+use std::{
+       future::Future,
+       ops::{Deref as _, DerefMut as _},
+       pin::Pin,
+       task,
+};
+
+use futures_core::Stream;
+
+use crate::SendWrapper;
+
+impl<F: Future> Future for SendWrapper<F> {
+       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::Output> {
+               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)
+       }
+}
+
+impl<S: Stream> Stream for SendWrapper<S> {
+       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<Option<Self::Item>> {
+               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)
+       }
+
+       #[inline]
+       fn size_hint(&self) -> (usize, Option<usize>) {
+               self.deref().size_hint()
+       }
+}
+
+#[cfg(test)]
+mod tests {
+       use std::thread;
+
+       use futures_executor as executor;
+       use futures_util::{future, stream, StreamExt};
+
+       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_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_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
new file mode 100644 (file)
index 0000000..ff07dec
--- /dev/null
@@ -0,0 +1,410 @@
+// Copyright 2017 Thomas Keh.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// 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<T>`] 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.
+//!
+//! # Examples
+//!
+//! ```rust
+//! use send_wrapper::SendWrapper;
+//! use std::rc::Rc;
+//! use std::thread;
+//! use std::sync::mpsc::channel;
+//!
+//! // This import is important if you want to use deref() or
+//! // deref_mut() instead of Deref coercion.
+//! use std::ops::{Deref, DerefMut};
+//!
+//! // Rc is a non-Send type.
+//! let value = Rc::new(42);
+//!
+//! // We now wrap the value with `SendWrapper` (value is moved inside).
+//! let wrapped_value = SendWrapper::new(value);
+//!
+//! // A channel allows us to move the wrapped value between threads.
+//! let (sender, receiver) = channel();
+//!
+//! let t = thread::spawn(move || {
+//!
+//!     // 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();
+//!
+//! });
+//!
+//! 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 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;
+//! ```
+//!
+//! # 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:
+//!
+//! ```toml
+//! send_wrapper = { version = "...", features = ["futures"] }
+//! ```
+//!
+//! # License
+//!
+//! `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(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};
+
+/// 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<T> {
+       data: ManuallyDrop<T>,
+       thread_id: ThreadId,
+}
+
+impl<T> SendWrapper<T> {
+       /// Create a `SendWrapper<T>` wrapper around a value of type `T`.
+       /// The wrapper takes ownership of the value.
+       pub fn new(data: T) -> SendWrapper<T> {
+               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<T>`.
+       ///
+       /// # Panics
+       ///
+       /// Panics if it is called from a different thread than the one the `SendWrapper<T>` 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()
+               }
+       }
+}
+
+unsafe impl<T> Send for SendWrapper<T> {}
+unsafe impl<T> Sync for SendWrapper<T> {}
+
+impl<T> Deref for SendWrapper<T> {
+       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<T>` 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<T> DerefMut for SendWrapper<T> {
+       /// Returns a mutable reference to the contained value.
+       ///
+       /// # Panics
+       ///
+       /// Dereferencing panics if it is done from a different thread than the one the `SendWrapper<T>` 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<T> Drop for SendWrapper<T> {
+       /// Drops the contained value.
+       ///
+       /// # Panics
+       ///
+       /// Dropping panics if it is done from a different thread than the one the `SendWrapper<T>` 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::<T>()`] is false) then this method never panics.
+       ///
+       /// [`needs_drop::<T>()`]: 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::<T>() || 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<T: fmt::Debug> fmt::Debug for SendWrapper<T> {
+       /// Formats the value using the given formatter.
+       ///
+       /// # Panics
+       ///
+       /// Formatting panics if it is done from a different thread than the one
+       /// the `SendWrapper<T>` 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()
+       }
+}
+
+impl<T: Clone> Clone for SendWrapper<T> {
+       /// Returns a copy of the value.
+       ///
+       /// # Panics
+       ///
+       /// Cloning panics if it is done from a different thread than the one
+       /// the `SendWrapper<T>` instance has been created with.
+       #[track_caller]
+       fn clone(&self) -> Self {
+               Self::new(self.deref().clone())
+       }
+}
+
+#[cold]
+#[inline(never)]
+#[track_caller]
+fn invalid_deref() -> ! {
+       const DEREF_ERROR: &'static str = "Dereferenced SendWrapper<T> variable from a thread different to the one it has been created with.";
+
+       panic!("{}", DEREF_ERROR)
+}
+
+#[cold]
+#[inline(never)]
+#[track_caller]
+fn invalid_poll() -> ! {
+       const POLL_ERROR: &'static str = "Polling SendWrapper<T> variable from a thread different to the one it has been created with.";
+
+       panic!("{}", POLL_ERROR)
+}
+
+#[cold]
+#[inline(never)]
+#[track_caller]
+fn invalid_drop() {
+       const DROP_ERROR: &'static str = "Dropped SendWrapper<T> 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)
+       }
+}
+
+#[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<usize> = 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<T> 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());
+       }
+}