futures-locks-0.7.1/.cargo_vcs_info.json0000644000000001360000000000100136470ustar { "git": { "sha1": "eb972e8d23fc80d9474d85da31eabfcc3c35d080" }, "path_in_vcs": "" }futures-locks-0.7.1/CHANGELOG.md000064400000000000000000000100241046102023000142450ustar 00000000000000# Change Log All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/). ## [0.7.1] - 2022-12-07 - The published package on crates.io now includes functional tests. No user-visible changes. ([#53](https://github.com/asomers/futures-locks/pull/53)) ## [0.7.0] - 2021-11-18 ### Added ### Changed - Updated to Tokio 1.0. Crates needing Tokio 0.2 must stay on the 0.6 branch. ([#42](https://github.com/asomers/futures-locks/pull/42)) - `Mutex::try_lock`, `RwLock::try_read`, and `RwLock::try_write`, now return a dedicated error type instead of `()`, and it implements `std::error::Error`. ([#41](https://github.com/asomers/futures-locks/pull/41)) ### Fixed - Fixed a soundness issue with `RwLock`: it shouldn't implement `Sync` unless its inner type also does. ([#45](https://github.com/asomers/futures-locks/pull/45)) ### Removed ## [0.6.0] - 2020-09-07 ### Added ### Changed - Updated to `std::future`. `futures-locks` no longer works with `futures-0.1`. For `futures-0.1`-based applications, continue to use the 0.5 branch. Most methods have similar interfaces. However, the `IntoFuture` trait no longer exists in the `std::future` world. And `Future` doesn't implement `From` (though I don't know why it couldn't). So `Mutex::with`, `RwLock::with_read`, and `RwLock::with_write` now take closures that return `impl Future`, instead of `impl IntoFuture`. Closure arguments that used to return something like `Result` should now return `futures::future::ready>` instead. ### Fixed ### Removed ## [0.5.0] - 2019-11-03 ### Added - Derived `Default` for `Mutex` and `RwLock` ([#22](https://github.com/asomers/futures-locks/pull/22)) ### Changed - Minimum compiler version has increased to 1.32.0 ([#28](https://github.com/asomers/futures-locks/pull/28)) ### Fixed - Fixed panics after an unready Future gets dropped ([#24](https://github.com/asomers/futures-locks/pull/24)) ## [0.4.0] - 2019-08-24 ### Added - Added `Mutex::ptr_eq()` ([#20](https://github.com/asomers/futures-locks/pull/20)) - Added `MutexWeak` ([#17](https://github.com/asomers/futures-locks/pull/17)) ## [0.3.2] - 2019-01-30 ### Changed - Better documentation ([#15](https://github.com/asomers/futures-locks/pull/15)) ## [0.3.1] - 2018-12-26 ### Changed - Minimum compiler version has increased to 1.31.0 ([#10](https://github.com/asomers/futures-locks/pull/10)) - `futures-locks` only depends on tokio crates `tokio-current-thread` and `tokio-executor` when built with the `tokio` feature. ([#10](https://github.com/asomers/futures-locks/pull/10)) ## [0.3.0] - 2018-06-28 ### Added - Added `Mutex::with_local`, `RwLock::with_read_local`, and `RwLock::with_write_local` for non-`Send` Futures. ([#7](https://github.com/asomers/futures-locks/pull/7)) ### Changed - `Mutex::with`, `RwLock::with_read`, and `RwLock::with_write` now require their Futures to be `Send`. They also can return errors. ([#7](https://github.com/asomers/futures-locks/pull/7)) - Methods enabled with the tokio feature now return a Future type equivalent to the one returned by the provided closure. ([#6](https://github.com/asomers/futures-locks/pull/6)) ### Fixed - `Mutex::with`, `RwLock::with_read`, and `RwLock::with_write` now work with all Tokio Runtimes. ([#7](https://github.com/asomers/futures-locks/pull/7)) ## [0.2.1] - 2018-06-18 ### Changed - Tokio support is now enabled by default. ## [0.2.0] - 2018-06-18 ### Added - Added methods for running critical code in its own task. These methods require Tokio. ([#3](https://github.com/asomers/futures-locks/issues/3)) - Implemented `Future` for all future types, even when the wrapped type is unsized. ## [0.1.1] - 2018-06-07 ### Added ### Changed - Futures should do nothing until polled. ([#2](https://github.com/asomers/futures-locks/issues/2)) - Fixed potential deadlocks when dropping Futures without first polling them. ([#1](https://github.com/asomers/futures-locks/issues/1)) ### Fixed ### Removed futures-locks-0.7.1/Cargo.toml0000644000000027150000000000100116520ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "futures-locks" version = "0.7.1" authors = ["Alan Somers "] include = [ "src/**/*", "tests/**/*", "LICENSE-*", "README.md", "CHANGELOG.md", ] autotests = false description = """ Futures-aware lock primitives """ documentation = "https://docs.rs/futures-locks" readme = "README.md" categories = ["asynchronous"] license = "MIT/Apache-2.0" repository = "https://github.com/asomers/futures-locks" [package.metadata.docs.rs] features = ["tokio"] rustdoc-args = [ "--cfg", "docsrs", ] [[test]] name = "functional" path = "tests/test.rs" [dependencies.futures-channel] version = "0.3.1" [dependencies.futures-task] version = "0.3.1" [dependencies.tokio] version = "1.0" features = ["rt"] optional = true [dev-dependencies.futures] version = "0.3.1" [dev-dependencies.tokio] version = "1.0" features = [ "sync", "macros", "rt-multi-thread", ] [dev-dependencies.tokio-test] version = "0.4.2" [features] default = ["tokio"] futures-locks-0.7.1/Cargo.toml.orig000064400000000000000000000016551046102023000153350ustar 00000000000000[package] name = "futures-locks" edition = "2018" version = "0.7.1" authors = ["Alan Somers "] license = "MIT/Apache-2.0" readme = "README.md" repository = "https://github.com/asomers/futures-locks" description = """ Futures-aware lock primitives """ categories = ["asynchronous"] documentation = "https://docs.rs/futures-locks" autotests = false include = ["src/**/*", "tests/**/*", "LICENSE-*", "README.md", "CHANGELOG.md"] [package.metadata.docs.rs] features = ["tokio"] rustdoc-args = ["--cfg", "docsrs"] [features] # Enable methods that require a Tokio runtime. default = ["tokio"] [dependencies] futures-channel = "0.3.1" futures-task = "0.3.1" tokio = { version = "1.0", features = ["rt"], optional = true } [dev-dependencies] futures = "0.3.1" tokio = { version = "1.0", features = ["sync", "macros", "rt-multi-thread"] } tokio-test = { version = "0.4.2" } [[test]] name = "functional" path = "tests/test.rs" futures-locks-0.7.1/LICENSE-APACHE000064400000000000000000000251371046102023000143730ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS 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. futures-locks-0.7.1/LICENSE-MIT000064400000000000000000000020371046102023000140750ustar 00000000000000Copyright (c) 2018 Alan Somers 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. futures-locks-0.7.1/README.md000064400000000000000000000021651046102023000137220ustar 00000000000000# futures-locks A library of [Futures]-aware locking primitives. These locks can safely be used in asynchronous environments like [Tokio]. When they block, they'll only block a single task, not the entire reactor. [![Build Status](https://api.cirrus-ci.com/github/asomers/futures-locks.svg)](https://cirrus-ci.com/github/asomers/futures-locks) [![CodeCov.io](https://codecov.io/gh/asomers/futures-locks/branch/master/graph/badge.svg)](https://codecov.io/gh/asomers/futures-locks) [Futures]: https://github.com/rust-lang-nursery/futures-rs [Tokio]: https:/tokio.rs ```toml # Cargo.toml [dependencies] futures = "0.3.1" futures-locks = "0.6" ``` # Usage Generally, the provided primitives work much like their counterparts from the standard library. But instead of blocking until ready, they return Futures which will become ready when the lock is acquired. See the doc comments for individual examples. `futures-locks` requires Rust 1.49.0 or higher. # License `futures-locks` is primarily distributed under the terms of both the MIT license and the Apache License (Version 2.0). See LICENSE-APACHE, and LICENSE-MIT for details futures-locks-0.7.1/src/lib.rs000064400000000000000000000032111046102023000143370ustar 00000000000000// vim: tw=80 //! A library of [`Futures`]-aware locking primitives. These locks can safely //! be used in asynchronous environments like [`Tokio`]. When they block, //! they'll only block a single task, not the entire reactor. //! //! These primitives generally work much like their counterparts from the //! standard library. But instead of blocking, they return a `Future` that //! completes when the lock has been acquired. //! //! # Examples //! //! ``` //! # use futures_locks::*; //! # use futures::executor::block_on; //! # use futures::{Future, FutureExt}; //! # fn main() { //! let mtx = Mutex::::new(0); //! let fut = mtx.lock().map(|mut guard| { *guard += 5; }); //! block_on(fut); //! assert_eq!(mtx.try_unwrap().unwrap(), 5); //! # } //! ``` //! //! [`Futures`]: https://github.com/rust-lang-nursery/futures-rs //! [`Tokio`]: https:/tokio.rs #![cfg_attr(docsrs, feature(doc_cfg))] #![warn(missing_docs)] mod mutex; mod rwlock; pub use mutex::{Mutex, MutexFut, MutexGuard, MutexWeak}; pub use rwlock::{RwLock, RwLockReadFut, RwLockWriteFut, RwLockReadGuard, RwLockWriteGuard}; use futures_channel::oneshot; use std::{error, fmt}; /// Poll state of all Futures in this crate. enum FutState { New, Pending(oneshot::Receiver<()>), Acquired } /// The lock could not be acquired at this time because the operation would /// otherwise block. #[derive(Clone, Copy, Debug)] pub struct TryLockError; impl fmt::Display for TryLockError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "try_lock failed because the operation would block") } } impl error::Error for TryLockError {} futures-locks-0.7.1/src/mutex.rs000064400000000000000000000342731046102023000147470ustar 00000000000000// vim: tw=80 use futures_channel::oneshot; use futures_task::{Context, Poll}; use std::{ cell::UnsafeCell, clone::Clone, collections::VecDeque, future::Future, ops::{Deref, DerefMut}, pin::Pin, sync }; use super::{FutState, TryLockError}; #[cfg(feature = "tokio")] use tokio::task; /// An RAII mutex guard, much like `std::sync::MutexGuard`. The wrapped data /// can be accessed via its `Deref` and `DerefMut` implementations. #[derive(Debug)] pub struct MutexGuard { mutex: Mutex } impl Drop for MutexGuard { fn drop(&mut self) { self.mutex.unlock(); } } impl Deref for MutexGuard { type Target = T; fn deref(&self) -> &T { unsafe {&*self.mutex.inner.data.get()} } } impl DerefMut for MutexGuard { fn deref_mut(&mut self) -> &mut T { unsafe {&mut *self.mutex.inner.data.get()} } } /// A `Future` representing a pending `Mutex` acquisition. pub struct MutexFut { state: FutState, mutex: Mutex, } impl MutexFut { fn new(state: FutState, mutex: Mutex) -> Self { MutexFut{state, mutex} } } impl Drop for MutexFut { fn drop(&mut self) { match self.state { FutState::New => { // Mutex hasn't yet been modified; nothing to do }, FutState::Pending(ref mut rx) => { rx.close(); match rx.try_recv() { Ok(Some(())) => { // This future received ownership of the mutex, but got // dropped before it was ever polled. Release the // mutex. self.mutex.unlock() }, Ok(None) => { // Dropping the Future before it acquires the Mutex is // equivalent to cancelling it. }, Err(oneshot::Canceled) => { // Never received ownership of the mutex } } }, FutState::Acquired => { // The MutexGuard will take care of releasing the Mutex } } } } impl Future for MutexFut { type Output = MutexGuard; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll { let (result, new_state) = match self.state { FutState::New => { let mut mtx_data = self.mutex.inner.mutex.lock() .expect("sync::Mutex::lock"); if mtx_data.owned { let (tx, mut rx) = oneshot::channel::<()>(); mtx_data.waiters.push_back(tx); // Even though we know it isn't ready, we need to poll the // receiver in order to register our task for notification. assert!(Pin::new(&mut rx).poll(cx).is_pending()); (Poll::Pending, FutState::Pending(rx)) } else { mtx_data.owned = true; let guard = MutexGuard{mutex: self.mutex.clone()}; (Poll::Ready(guard), FutState::Acquired) } }, FutState::Pending(ref mut rx) => { match Pin::new(rx).poll(cx) { Poll::Pending => return Poll::Pending, Poll::Ready(_) => { let state = FutState::Acquired; let result = Poll::Ready( MutexGuard{mutex: self.mutex.clone()} ); (result, state) } //LCOV_EXCL_LINE kcov false negative } }, FutState::Acquired => panic!("Double-poll of ready Future") }; self.state = new_state; result } } #[derive(Debug, Default)] struct MutexData { owned: bool, // FIFO queue of waiting tasks. waiters: VecDeque>, } #[derive(Debug, Default)] struct Inner { mutex: sync::Mutex, data: UnsafeCell, } /// `MutexWeak` is a non-owning reference to a [`Mutex`]. `MutexWeak` is to /// [`Mutex`] as [`std::sync::Weak`] is to [`std::sync::Arc`]. /// /// # Examples /// ``` /// # use futures_locks::{Mutex,MutexGuard}; /// # fn main() { /// let mutex = Mutex::::new(0); /// let mutex_weak = Mutex::downgrade(&mutex); /// let mutex_new = mutex_weak.upgrade().unwrap(); /// # } /// ``` /// /// [`Mutex`]: struct.Mutex.html /// [`std::sync::Weak`]: https://doc.rust-lang.org/std/sync/struct.Weak.html /// [`std::sync::Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html #[derive(Debug)] pub struct MutexWeak { inner: sync::Weak>, } impl MutexWeak { /// Tries to upgrade the `MutexWeak` to `Mutex`. If the `Mutex` was dropped /// then the function return `None`. pub fn upgrade(&self) -> Option> { if let Some(inner) = self.inner.upgrade() { return Some(Mutex{inner}) } None } } impl Clone for MutexWeak { fn clone(&self) -> MutexWeak { MutexWeak {inner: self.inner.clone()} } } // Clippy doesn't like the Arc within Inner. But the access rules of the Mutex // make it safe to send. std::sync::Mutex has the same Send impl #[allow(clippy::non_send_fields_in_send_ty)] unsafe impl Send for MutexWeak {} unsafe impl Sync for MutexWeak {} /// A Futures-aware Mutex. /// /// `std::sync::Mutex` cannot be used in an asynchronous environment like Tokio, /// because a mutex acquisition can block an entire reactor. This class can be /// used instead. It functions much like `std::sync::Mutex`. Unlike that /// class, it also has a builtin `Arc`, making it accessible from multiple /// threads. It's also safe to `clone`. Also unlike `std::sync::Mutex`, this /// class does not detect lock poisoning. /// /// # Examples /// /// ``` /// # use futures_locks::*; /// # use futures::executor::block_on; /// # use futures::{Future, FutureExt}; /// # fn main() { /// let mtx = Mutex::::new(0); /// let fut = mtx.lock().map(|mut guard| { *guard += 5; }); /// block_on(fut); /// assert_eq!(mtx.try_unwrap().unwrap(), 5); /// # } /// ``` #[derive(Debug, Default)] pub struct Mutex { inner: sync::Arc>, } impl Clone for Mutex { fn clone(&self) -> Mutex { Mutex { inner: self.inner.clone()} } } impl Mutex { /// Create a new `Mutex` in the unlocked state. pub fn new(t: T) -> Mutex { let mutex_data = MutexData { owned: false, waiters: VecDeque::new(), }; let inner = Inner { mutex: sync::Mutex::new(mutex_data), data: UnsafeCell::new(t) }; //LCOV_EXCL_LINE kcov false negative Mutex { inner: sync::Arc::new(inner)} } /// Consumes the `Mutex` and returns the wrapped data. If the `Mutex` still /// has multiple references (not necessarily locked), returns a copy of /// `self` instead. pub fn try_unwrap(self) -> Result> { match sync::Arc::try_unwrap(self.inner) { Ok(inner) => Ok({ // `unsafe` is no longer needed as of somewhere around 1.25.0. // https://github.com/rust-lang/rust/issues/35067 #[allow(unused_unsafe)] unsafe { inner.data.into_inner() } }), Err(arc) => Err(Mutex {inner: arc}) } } } impl Mutex { /// Create a [`MutexWeak`] reference to this `Mutex`. /// /// [`MutexWeak`]: struct.MutexWeak.html pub fn downgrade(this: &Mutex) -> MutexWeak { MutexWeak {inner: sync::Arc::>::downgrade(&this.inner)} } /// Returns a reference to the underlying data, if there are no other /// clones of the `Mutex`. /// /// Since this call borrows the `Mutex` mutably, no actual locking takes /// place -- the mutable borrow statically guarantees no locks exist. /// However, if the `Mutex` has already been cloned, then `None` will be /// returned instead. /// /// # Examples /// /// ``` /// # use futures_locks::*; /// # fn main() { /// let mut mtx = Mutex::::new(0); /// *mtx.get_mut().unwrap() += 5; /// assert_eq!(mtx.try_unwrap().unwrap(), 5); /// # } /// ``` pub fn get_mut(&mut self) -> Option<&mut T> { if let Some(inner) = sync::Arc::get_mut(&mut self.inner) { let lock_data = inner.mutex.get_mut().unwrap(); let data = unsafe { inner.data.get().as_mut() }.unwrap(); debug_assert!(!lock_data.owned); Some(data) } else { None } } /// Acquires a `Mutex`, blocking the task in the meantime. When the /// returned `Future` is ready, this task will have sole access to the /// protected data. pub fn lock(&self) -> MutexFut { MutexFut::new(FutState::New, self.clone()) } /// Attempts to acquire the lock. /// /// If the operation would block, returns `Err` instead. Otherwise, returns /// a guard (not a `Future`). /// /// # Examples /// ``` /// # use futures_locks::*; /// # fn main() { /// let mut mtx = Mutex::::new(0); /// match mtx.try_lock() { /// Ok(mut guard) => *guard += 5, /// Err(_) => println!("Better luck next time!") /// }; /// # } /// ``` pub fn try_lock(&self) -> Result, TryLockError> { let mut mtx_data = self.inner.mutex.lock().expect("sync::Mutex::lock"); if mtx_data.owned { Err(TryLockError) } else { mtx_data.owned = true; Ok(MutexGuard{mutex: self.clone()}) } } /// Release the `Mutex` fn unlock(&self) { let mut mtx_data = self.inner.mutex.lock().expect("sync::Mutex::lock"); assert!(mtx_data.owned); while let Some(tx) = mtx_data.waiters.pop_front() { if tx.send(()).is_ok() { return; } // An error indicates that the waiter's future was dropped } // Relinquish ownership mtx_data.owned = false; } /// Returns true if the two `Mutex` point to the same data else false. pub fn ptr_eq(this: &Mutex, other: &Mutex) -> bool { sync::Arc::ptr_eq(&this.inner, &other.inner) } } impl Mutex { /// Acquires a `Mutex` and performs a computation on its guarded value in a /// separate task. Returns a `Future` containing the result of the /// computation. /// /// When using Tokio, this method will often hold the `Mutex` for less time /// than chaining a computation to [`lock`](#method.lock). The reason is /// that Tokio polls all tasks promptly upon notification. However, Tokio /// does not guarantee that it will poll all futures promptly when their /// owning task gets notified. So it's best to hold `Mutex`es within their /// own tasks, lest their continuations get blocked by slow stacked /// combinators. /// /// # Examples /// /// ``` /// # use futures_locks::*; /// # use futures::{Future, future::ready}; /// # use tokio::runtime::Runtime; /// # fn main() { /// let mtx = Mutex::::new(0); /// let mut rt = Runtime::new().unwrap(); /// rt.block_on(async { /// mtx.with(|mut guard| { /// *guard += 5; /// ready::<()>(()) /// }).await /// }); /// assert_eq!(mtx.try_unwrap().unwrap(), 5); /// # } /// ``` #[cfg(any(feature = "tokio", all(docsrs, rustdoc)))] #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))] pub fn with(&self, f: F) -> impl Future where F: FnOnce(MutexGuard) -> B + Send + 'static, B: Future + Send + 'static, R: Send + 'static, T: Send { let jh = tokio::spawn({ let fut = self.lock(); async move { f(fut.await).await } }); async move { jh.await.unwrap() } } /// Like [`with`](#method.with) but for Futures that aren't `Send`. /// Spawns a new task on a single-threaded Runtime to complete the Future. /// /// # Examples /// /// ``` /// # use futures_locks::*; /// # use futures::{Future, future::ready}; /// # use std::rc::Rc; /// # use tokio::runtime::Runtime; /// # fn main() { /// // Note: Rc is not `Send` /// let mtx = Mutex::>::new(Rc::new(0)); /// let mut rt = Runtime::new().unwrap(); /// rt.block_on(async { /// mtx.with_local(|mut guard| { /// *Rc::get_mut(&mut *guard).unwrap() += 5; /// ready(()) /// }).await /// }); /// assert_eq!(*mtx.try_unwrap().unwrap(), 5); /// # } /// ``` #[cfg(any(feature = "tokio", all(docsrs, rustdoc)))] #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))] pub fn with_local(&self, f: F) -> impl Future where F: FnOnce(MutexGuard) -> B + 'static, B: Future + 'static + Unpin, R: 'static { let local = task::LocalSet::new(); let jh = local.spawn_local({ let fut = self.lock(); async move { f(fut.await).await } }); async move { local.await; jh.await.unwrap() } } } // Clippy doesn't like the Arc within Inner. But the access rules of the Mutex // make it safe to send. std::sync::Mutex has the same Send impl #[allow(clippy::non_send_fields_in_send_ty)] unsafe impl Send for Mutex {} unsafe impl Sync for Mutex {} // LCOV_EXCL_START #[cfg(test)] mod t { use super::*; /// Pet Kcov #[test] fn debug() { let m = Mutex::::new(0); format!("{:?}", &m); } #[test] fn test_default() { let m = Mutex::default(); let value: u32 = m.try_unwrap().unwrap(); let expected = u32::default(); assert_eq!(expected, value); } } // LCOV_EXCL_STOP futures-locks-0.7.1/src/rwlock.rs000064400000000000000000000545071046102023000151100ustar 00000000000000// vim: tw=80 use futures_channel::oneshot; use futures_task::{Context, Poll}; use std::{ cell::UnsafeCell, clone::Clone, collections::VecDeque, future::Future, ops::{Deref, DerefMut}, pin::Pin, sync, }; use super::{FutState, TryLockError}; #[cfg(feature = "tokio")] use tokio::task; /// An RAII guard, much like `std::sync::RwLockReadGuard`. The wrapped data can /// be accessed via its `Deref` implementation. #[derive(Debug)] pub struct RwLockReadGuard { rwlock: RwLock } impl Deref for RwLockReadGuard { type Target = T; fn deref(&self) -> &T { unsafe {&*self.rwlock.inner.data.get()} } } impl Drop for RwLockReadGuard { fn drop(&mut self) { self.rwlock.unlock_reader(); } } /// An RAII guard, much like `std::sync::RwLockWriteGuard`. The wrapped data /// can be accessed via its `Deref` and `DerefMut` implementations. #[derive(Debug)] pub struct RwLockWriteGuard { rwlock: RwLock } impl Deref for RwLockWriteGuard { type Target = T; fn deref(&self) -> &T { unsafe {&*self.rwlock.inner.data.get()} } } impl DerefMut for RwLockWriteGuard { fn deref_mut(&mut self) -> &mut T { unsafe {&mut *self.rwlock.inner.data.get()} } } impl Drop for RwLockWriteGuard { fn drop(&mut self) { self.rwlock.unlock_writer(); } } /// A `Future` representing a pending `RwLock` shared acquisition. pub struct RwLockReadFut { state: FutState, rwlock: RwLock, } impl RwLockReadFut { fn new(state: FutState, rwlock: RwLock) -> Self { RwLockReadFut{state, rwlock} } } impl Drop for RwLockReadFut { fn drop(&mut self) { match self.state { FutState::New => { // RwLock hasn't yet been modified; nothing to do }, FutState::Pending(ref mut rx) => { rx.close(); match rx.try_recv() { Ok(Some(())) => { // This future received ownership of the lock, but got // dropped before it was ever polled. Release the // lock. self.rwlock.unlock_reader() }, Ok(None) => { // Dropping the Future before it acquires the lock is // equivalent to cancelling it. }, Err(oneshot::Canceled) => { // Never received ownership of the lock } } }, FutState::Acquired => { // The RwLockReadGuard will take care of releasing the RwLock } } } } impl Future for RwLockReadFut { type Output = RwLockReadGuard; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll { let (result, new_state) = match self.state { FutState::New => { let mut lock_data = self.rwlock.inner.mutex.lock() .expect("sync::Mutex::lock"); if lock_data.exclusive { let (tx, mut rx) = oneshot::channel::<()>(); lock_data.read_waiters.push_back(tx); // Even though we know it isn't ready, we need to poll the // receiver in order to register our task for notification. assert!(Pin::new(&mut rx).poll(cx).is_pending()); (Poll::Pending, FutState::Pending(rx)) } else { lock_data.num_readers += 1; let guard = RwLockReadGuard{rwlock: self.rwlock.clone()}; (Poll::Ready(guard), FutState::Acquired) } }, FutState::Pending(ref mut rx) => { match Pin::new(rx).poll(cx) { Poll::Pending => return Poll::Pending, Poll::Ready(_) => { let state = FutState::Acquired; let result = Poll::Ready( RwLockReadGuard{rwlock: self.rwlock.clone()} ); (result, state) } // LCOV_EXCL_LINE kcov false negative } }, FutState::Acquired => panic!("Double-poll of ready Future") }; self.state = new_state; result } } /// A `Future` representing a pending `RwLock` exclusive acquisition. pub struct RwLockWriteFut { state: FutState, rwlock: RwLock, } impl RwLockWriteFut { fn new(state: FutState, rwlock: RwLock) -> Self { RwLockWriteFut{state, rwlock} } } impl Drop for RwLockWriteFut { fn drop(&mut self) { match self.state { FutState::New => { // RwLock hasn't yet been modified; nothing to do }, FutState::Pending(ref mut rx) => { rx.close(); match rx.try_recv() { Ok(Some(())) => { // This future received ownership of the lock, but got // dropped before it was ever polled. Release the // lock. self.rwlock.unlock_writer() }, Ok(None) => { // Dropping the Future before it acquires the lock is // equivalent to cancelling it. }, Err(oneshot::Canceled) => { // Never received ownership of the lock } } }, FutState::Acquired => { // The RwLockWriteGuard will take care of releasing the RwLock } } } } impl Future for RwLockWriteFut { type Output = RwLockWriteGuard; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll { let (result, new_state) = match self.state { FutState::New => { let mut lock_data = self.rwlock.inner.mutex.lock() .expect("sync::Mutex::lock"); if lock_data.exclusive || lock_data.num_readers > 0 { let (tx, mut rx) = oneshot::channel::<()>(); lock_data.write_waiters.push_back(tx); // Even though we know it isn't ready, we need to poll the // receiver in order to register our task for notification. assert!(Pin::new(&mut rx).poll(cx).is_pending()); (Poll::Pending, FutState::Pending(rx)) } else { lock_data.exclusive = true; let guard = RwLockWriteGuard{rwlock: self.rwlock.clone()}; (Poll::Ready(guard), FutState::Acquired) } }, FutState::Pending(ref mut rx) => { match Pin::new(rx).poll(cx) { Poll::Pending => return Poll::Pending, Poll::Ready(_) => { let state = FutState::Acquired; let result = Poll::Ready( RwLockWriteGuard{rwlock: self.rwlock.clone()} ); (result, state) } // LCOV_EXCL_LINE kcov false negative } }, FutState::Acquired => panic!("Double-poll of ready Future") }; self.state = new_state; result } } #[derive(Debug, Default)] struct RwLockData { /// True iff the `RwLock` is currently exclusively owned exclusive: bool, /// The number of tasks that currently have shared ownership of the RwLock num_readers: u32, // FIFO queue of waiting readers read_waiters: VecDeque>, // FIFO queue of waiting writers write_waiters: VecDeque>, } #[derive(Debug, Default)] struct Inner { mutex: sync::Mutex, data: UnsafeCell, } /// A Futures-aware RwLock. /// /// `std::sync::RwLock` cannot be used in an asynchronous environment like /// Tokio, because an acquisition can block an entire reactor. This class can /// be used instead. It functions much like `std::sync::RwLock`. Unlike that /// class, it also has a builtin `Arc`, making it accessible from multiple /// threads. It's also safe to `clone`. Also unlike `std::sync::RwLock`, this /// class does not detect lock poisoning. #[derive(Debug, Default)] pub struct RwLock { inner: sync::Arc>, } impl Clone for RwLock { fn clone(&self) -> RwLock { RwLock { inner: self.inner.clone()} } } impl RwLock { /// Create a new `RwLock` in the unlocked state. pub fn new(t: T) -> RwLock { let lock_data = RwLockData { exclusive: false, num_readers: 0, read_waiters: VecDeque::new(), write_waiters: VecDeque::new(), }; // LCOV_EXCL_LINE kcov false negative let inner = Inner { mutex: sync::Mutex::new(lock_data), data: UnsafeCell::new(t) }; // LCOV_EXCL_LINE kcov false negative RwLock { inner: sync::Arc::new(inner)} } /// Consumes the `RwLock` and returns the wrapped data. If the `RwLock` /// still has multiple references (not necessarily locked), returns a copy /// of `self` instead. pub fn try_unwrap(self) -> Result> { match sync::Arc::try_unwrap(self.inner) { Ok(inner) => Ok({ // `unsafe` is no longer needed as of somewhere around 1.25.0. // https://github.com/rust-lang/rust/issues/35067 #[allow(unused_unsafe)] unsafe { inner.data.into_inner() } }), Err(arc) => Err(RwLock {inner: arc}) } } } impl RwLock { /// Returns a reference to the underlying data, if there are no other /// clones of the `RwLock`. /// /// Since this call borrows the `RwLock` mutably, no actual locking takes /// place -- the mutable borrow statically guarantees no locks exist. /// However, if the `RwLock` has already been cloned, then `None` will be /// returned instead. /// /// # Examples /// /// ``` /// # use futures_locks::*; /// # fn main() { /// let mut lock = RwLock::::new(0); /// *lock.get_mut().unwrap() += 5; /// assert_eq!(lock.try_unwrap().unwrap(), 5); /// # } /// ``` pub fn get_mut(&mut self) -> Option<&mut T> { if let Some(inner) = sync::Arc::get_mut(&mut self.inner) { let lock_data = inner.mutex.get_mut().unwrap(); let data = unsafe { inner.data.get().as_mut() }.unwrap(); debug_assert!(!lock_data.exclusive); debug_assert_eq!(lock_data.num_readers, 0); Some(data) } else { None } } /// Acquire the `RwLock` nonexclusively, read-only, blocking the task in the /// meantime. /// /// When the returned `Future` is ready, then this task will have read-only /// access to the protected data. /// /// # Examples /// ``` /// # use futures_locks::*; /// # use futures::executor::block_on; /// # use futures::{Future, FutureExt}; /// # fn main() { /// let rwlock = RwLock::::new(42); /// let fut = rwlock.read().map(|mut guard| { *guard }); /// assert_eq!(block_on(fut), 42); /// # } /// /// ``` pub fn read(&self) -> RwLockReadFut { RwLockReadFut::new(FutState::New, self.clone()) } /// Acquire the `RwLock` exclusively, read-write, blocking the task in the /// meantime. /// /// When the returned `Future` is ready, then this task will have read-write /// access to the protected data. /// /// # Examples /// ``` /// # use futures_locks::*; /// # use futures::executor::block_on; /// # use futures::{Future, FutureExt}; /// # fn main() { /// let rwlock = RwLock::::new(42); /// let fut = rwlock.write().map(|mut guard| { *guard = 5;}); /// block_on(fut); /// assert_eq!(rwlock.try_unwrap().unwrap(), 5); /// # } /// /// ``` pub fn write(&self) -> RwLockWriteFut { RwLockWriteFut::new(FutState::New, self.clone()) } /// Attempts to acquire the `RwLock` nonexclusively. /// /// If the operation would block, returns `Err` instead. Otherwise, returns /// a guard (not a `Future`). /// /// # Examples /// ``` /// # use futures_locks::*; /// # fn main() { /// let mut lock = RwLock::::new(5); /// let r = match lock.try_read() { /// Ok(guard) => *guard, /// Err(_) => panic!("Better luck next time!") /// }; /// assert_eq!(5, r); /// # } /// ``` pub fn try_read(&self) -> Result, TryLockError> { let mut lock_data = self.inner.mutex.lock().expect("sync::Mutex::lock"); if lock_data.exclusive { Err(TryLockError) } else { lock_data.num_readers += 1; Ok(RwLockReadGuard{rwlock: self.clone()}) } } /// Attempts to acquire the `RwLock` exclusively. /// /// If the operation would block, returns `Err` instead. Otherwise, returns /// a guard (not a `Future`). /// /// # Examples /// ``` /// # use futures_locks::*; /// # fn main() { /// let mut lock = RwLock::::new(5); /// match lock.try_write() { /// Ok(mut guard) => *guard += 5, /// Err(_) => panic!("Better luck next time!") /// } /// assert_eq!(10, lock.try_unwrap().unwrap()); /// # } /// ``` pub fn try_write(&self) -> Result, TryLockError> { let mut lock_data = self.inner.mutex.lock().expect("sync::Mutex::lock"); if lock_data.exclusive || lock_data.num_readers > 0 { Err(TryLockError) } else { lock_data.exclusive = true; Ok(RwLockWriteGuard{rwlock: self.clone()}) } } /// Release a shared lock of an `RwLock`. fn unlock_reader(&self) { let mut lock_data = self.inner.mutex.lock().expect("sync::Mutex::lock"); assert!(lock_data.num_readers > 0); assert!(!lock_data.exclusive); assert_eq!(lock_data.read_waiters.len(), 0); lock_data.num_readers -= 1; if lock_data.num_readers == 0 { while let Some(tx) = lock_data.write_waiters.pop_front() { if tx.send(()).is_ok() { lock_data.exclusive = true; return } } } } /// Release an exclusive lock of an `RwLock`. fn unlock_writer(&self) { let mut lock_data = self.inner.mutex.lock().expect("sync::Mutex::lock"); assert!(lock_data.num_readers == 0); assert!(lock_data.exclusive); // First try to wake up any writers while let Some(tx) = lock_data.write_waiters.pop_front() { if tx.send(()).is_ok() { return; } } // If there are no writers, try to wake up readers lock_data.exclusive = false; lock_data.num_readers += lock_data.read_waiters.len() as u32; for tx in lock_data.read_waiters.drain(..) { // Ignore errors, which are due to a reader's future getting // dropped before it was ready let _ = tx.send(()); } } } impl RwLock { /// Acquires a `RwLock` nonexclusively and performs a computation on its /// guarded value in a separate task. Returns a `Future` containing the /// result of the computation. /// /// When using Tokio, this method will often hold the `RwLock` for less time /// than chaining a computation to [`read`](#method.read). The reason is /// that Tokio polls all tasks promptly upon notification. However, Tokio /// does not guarantee that it will poll all futures promptly when their /// owning task gets notified. So it's best to hold `RwLock`s within their /// own tasks, lest their continuations get blocked by slow stacked /// combinators. /// /// # Examples /// /// ``` /// # use futures_locks::*; /// # use futures::{Future, future::ready}; /// # use tokio::runtime::Runtime; /// # fn main() { /// let rwlock = RwLock::::new(5); /// let mut rt = Runtime::new().unwrap(); /// let r = rt.block_on(async { /// rwlock.with_read(|mut guard| { /// ready(*guard) /// }).await /// }); /// assert_eq!(r, 5); /// # } /// ``` #[cfg(any(feature = "tokio", all(docsrs, rustdoc)))] #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))] pub fn with_read(&self, f: F) -> impl Future where F: FnOnce(RwLockReadGuard) -> B + Send + 'static, B: Future + Send + 'static, R: Send + 'static, T: Send { let jh = tokio::spawn({ let fut = self.read(); async move { f(fut.await).await } }); async move { jh.await.unwrap() } } /// Like [`with_read`](#method.with_read) but for Futures that aren't /// `Send`. Spawns a new task on a single-threaded Runtime to complete the /// Future. /// /// # Examples /// /// ``` /// # use futures_locks::*; /// # use futures::{Future, future::ready}; /// # use std::rc::Rc; /// # use tokio::runtime::Runtime; /// # fn main() { /// // Note: Rc is not `Send` /// let rwlock = RwLock::>::new(Rc::new(5)); /// let mut rt = Runtime::new().unwrap(); /// let r = rt.block_on(async { /// rwlock.with_read_local(|mut guard| { /// ready(**guard) /// }).await /// }); /// assert_eq!(r, 5); /// # } /// ``` #[cfg(any(feature = "tokio", all(docsrs, rustdoc)))] #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))] pub fn with_read_local(&self, f: F) -> impl Future where F: FnOnce(RwLockReadGuard) -> B + 'static + Unpin, B: Future + 'static, R: 'static { let local = task::LocalSet::new(); let jh = local.spawn_local({ let fut = self.read(); async move { f(fut.await).await } }); async move { local.await; jh.await.unwrap() } } /// Acquires a `RwLock` exclusively and performs a computation on its /// guarded value in a separate task. Returns a `Future` containing the /// result of the computation. /// /// When using Tokio, this method will often hold the `RwLock` for less time /// than chaining a computation to [`write`](#method.write). The reason is /// that Tokio polls all tasks promptly upon notification. However, Tokio /// does not guarantee that it will poll all futures promptly when their /// owning task gets notified. So it's best to hold `RwLock`s within their /// own tasks, lest their continuations get blocked by slow stacked /// combinators. /// /// # Examples /// /// ``` /// # use futures::{Future, future::ready}; /// # use futures_locks::*; /// # use tokio::runtime::Runtime; /// # fn main() { /// let rwlock = RwLock::::new(0); /// let mut rt = Runtime::new().unwrap(); /// let r = rt.block_on(async { /// rwlock.with_write(|mut guard| { /// *guard += 5; /// ready(()) /// }).await /// }); /// assert_eq!(rwlock.try_unwrap().unwrap(), 5); /// # } /// ``` #[cfg(any(feature = "tokio", all(docsrs, rustdoc)))] #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))] pub fn with_write(&self, f: F) -> impl Future where F: FnOnce(RwLockWriteGuard) -> B + Send + 'static, B: Future + Send + 'static, R: Send + 'static, T: Send { let jh = tokio::spawn({ let fut = self.write(); async move { f(fut.await).await } }); async move { jh.await.unwrap() } } /// Like [`with_write`](#method.with_write) but for Futures that aren't /// `Send`. Spawns a new task on a single-threaded Runtime to complete the /// Future. /// /// # Examples /// /// ``` /// # use futures::{Future, future::ready}; /// # use futures_locks::*; /// # use std::rc::Rc; /// # use tokio::runtime::Runtime; /// # fn main() { /// // Note: Rc is not `Send` /// let rwlock = RwLock::>::new(Rc::new(0)); /// let mut rt = Runtime::new().unwrap(); /// let r = rt.block_on(async { /// rwlock.with_write_local(|mut guard| { /// *Rc::get_mut(&mut *guard).unwrap() += 5; /// ready(()) /// }).await /// }); /// assert_eq!(*rwlock.try_unwrap().unwrap(), 5); /// # } /// ``` #[cfg(any(feature = "tokio", all(docsrs, rustdoc)))] #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))] pub fn with_write_local(&self, f: F) -> impl Future where F: FnOnce(RwLockWriteGuard) -> B + 'static + Unpin, B: Future + 'static, R: 'static { let local = task::LocalSet::new(); let jh = local.spawn_local({ let fut = self.write(); async move { f(fut.await).await } }); async move { local.await; jh.await.unwrap() } } } // Clippy doesn't like the Arc within Inner. But the access rules of the RwLock // make it safe to send. std::sync::RwLock has the same Send impl #[allow(clippy::non_send_fields_in_send_ty)] unsafe impl Send for RwLock {} unsafe impl Sync for RwLock {} // LCOV_EXCL_START #[cfg(test)] mod t { use super::*; /// Pet Kcov #[test] fn debug() { let m = RwLock::::new(0); format!("{:?}", &m); } #[test] fn test_default() { let lock = RwLock::default(); let value: u32 = lock.try_unwrap().unwrap(); let expected = u32::default(); assert_eq!(expected, value); } } // LCOV_EXCL_STOP futures-locks-0.7.1/tests/mutex.rs000064400000000000000000000170301046102023000153120ustar 00000000000000//vim: tw=80 use futures::{FutureExt, stream}; #[cfg(feature = "tokio")] use futures::future::ready; use futures::stream::StreamExt; use std::sync::Arc; #[cfg(feature = "tokio")] use std::rc::Rc; use tokio::{self, sync::Barrier}; #[cfg(feature = "tokio")] use tokio::runtime; use tokio_test::task::spawn; use tokio_test::{assert_pending, assert_ready}; use futures_locks::*; // Create a MutexWeak and then upgrade it to Mutex #[test] fn mutex_weak_some() { let mutex = Mutex::::new(0); let mutex_weak = Mutex::downgrade(&mutex); assert!(mutex_weak.upgrade().is_some()) } // Create a MutexWeak and drop the mutex so that MutexWeak::upgrade return None #[test] fn mutex_weak_none() { let mutex = Mutex::::new(0); let mutex_weak = Mutex::downgrade(&mutex); drop(mutex); assert!(mutex_weak.upgrade().is_none()) } // Compare Mutexes if it point to the same value #[test] fn mutex_eq_ptr_true() { let mutex = Mutex::::new(0); let mutex_other = mutex.clone(); assert!(Mutex::ptr_eq(&mutex, &mutex_other)); } // Compare Mutexes if it point to the same value #[test] fn mutex_eq_ptr_false() { let mutex = Mutex::::new(0); let mutex_other = Mutex::::new(0); assert!(!Mutex::ptr_eq(&mutex, &mutex_other)); } // When a Mutex gets dropped after gaining ownership but before being polled, it // should drain its channel and relinquish ownership if a message was found. If // not, deadlocks may result. #[tokio::test] async fn drop_when_ready() { let mutex = Mutex::::new(0); let guard1 = mutex.lock().await; let fut2 = mutex.lock(); drop(guard1); // ownership transfers to fut2 drop(fut2); // relinquish ownership // The mutex should be available again let _guard3 = mutex.lock().await; } // When a pending Mutex gets dropped after being polled() but before gaining // ownership, ownership should pass on to the next waiter. #[test] fn drop_before_ready() { let mutex = Mutex::::new(0); let mut fut1 = spawn(mutex.lock()); let guard1 = assert_ready!(fut1.poll()); // fut1 immediately gets ownership let mut fut2 = spawn(mutex.lock()); assert_pending!(fut2.poll()); // fut2 is blocked let mut fut3 = spawn(mutex.lock()); assert_pending!(fut3.poll()); // fut3 is blocked, too drop(fut2); // drop before gaining ownership drop(guard1); // ownership transfers to fut3 drop(fut1); assert!(fut3.is_woken()); assert_ready!(fut3.poll()); } // Mutably dereference a uniquely owned Mutex #[test] fn get_mut() { let mut mutex = Mutex::::new(42); *mutex.get_mut().unwrap() += 1; assert_eq!(*mutex.get_mut().unwrap(), 43); } // Cloned Mutexes cannot be deferenced #[test] fn get_mut_cloned() { let mut mutex = Mutex::::new(42); let _clone = mutex.clone(); assert!(mutex.get_mut().is_none()); } // Acquire an uncontested Mutex. poll immediately returns Async::Ready // #[test] #[tokio::test] async fn lock_uncontested() { let mutex = Mutex::::new(0); let guard = mutex.lock().await; let result = *guard + 5; drop(guard); assert_eq!(result, 5); } // Pend on a Mutex held by another task in the same tokio Reactor. poll returns // Async::NotReady. Later, it gets woken up without involving the OS. #[test] fn lock_contested() { let mutex = Mutex::::new(0); let mut fut0 = spawn(mutex.lock()); let guard0 = assert_ready!(fut0.poll()); // fut0 immediately gets ownership let mut fut1 = spawn(mutex.lock()); assert_pending!(fut1.poll()); // fut1 is blocked drop(guard0); // Ownership transfers to fut1 assert!(fut1.is_woken()); assert_ready!(fut1.poll()); } // A single Mutex is contested by tasks in multiple threads #[tokio::test] async fn lock_multithreaded() { let mutex = Mutex::::new(0); let mtx_clone0 = mutex.clone(); let mtx_clone1 = mutex.clone(); let mtx_clone2 = mutex.clone(); let mtx_clone3 = mutex.clone(); let barrier = Arc::new(Barrier::new(5)); let b0 = barrier.clone(); let b1 = barrier.clone(); let b2 = barrier.clone(); let b3 = barrier.clone(); tokio::task::spawn(async move { stream::iter(0..1000).for_each(move |_| { mtx_clone0.lock().map(|mut guard| { *guard += 2 }) }).await; b0.wait().await; }); tokio::task::spawn(async move { stream::iter(0..1000).for_each(move |_| { mtx_clone1.lock().map(|mut guard| { *guard += 3 }) }).await; b1.wait().await; }); tokio::task::spawn(async move { stream::iter(0..1000).for_each(move |_| { mtx_clone2.lock().map(|mut guard| { *guard += 5 }) }).await; b2.wait().await; }); tokio::task::spawn(async move { stream::iter(0..1000).for_each(move |_| { mtx_clone3.lock().map(|mut guard| { *guard += 7 }) }).await; b3.wait().await; }); barrier.wait().await; assert_eq!(mutex.try_unwrap().expect("try_unwrap"), 17_000); } // Mutexes should be acquired in the order that their Futures are waited upon. #[tokio::test] async fn lock_order() { let mutex = Mutex::>::new(vec![]); let fut2 = mutex.lock().map(|mut guard| guard.push(2)); let fut1 = mutex.lock().map(|mut guard| guard.push(1)); fut1.then(|_| fut2).await; assert_eq!(mutex.try_unwrap().unwrap(), vec![1, 2]); } // Acquire an uncontested Mutex with try_lock #[test] fn try_lock_uncontested() { let mutex = Mutex::::new(5); let guard = mutex.try_lock().unwrap(); assert_eq!(5, *guard); } // Try and fail to acquire a contested Mutex with try_lock #[test] fn try_lock_contested() { let mutex = Mutex::::new(0); let _guard = mutex.try_lock().unwrap(); assert!(mutex.try_lock().is_err()); } #[test] fn try_unwrap_multiply_referenced() { let mtx = Mutex::::new(0); let _mtx2 = mtx.clone(); assert!(mtx.try_unwrap().is_err()); } // Returning errors is simpler than in futures-locks 0.5: just return a Result #[cfg(feature = "tokio")] #[test] fn with_err() { let mtx = Mutex::::new(-5); let rt = runtime::Builder::new_current_thread().build().unwrap(); let r = rt.block_on(async { mtx.with(|guard| { if *guard > 0 { ready(Ok(*guard)) } else { ready(Err("Whoops!")) } }).await }); assert_eq!(r, Err("Whoops!")); } #[cfg(feature = "tokio")] #[test] fn with_ok() { let mtx = Mutex::::new(5); let rt = runtime::Builder::new_current_thread().build().unwrap(); let r = rt.block_on(async { mtx.with(|guard| { ready(*guard) }).await }); assert_eq!(r, 5); } // Mutex::with should work with multithreaded Runtimes as well as // single-threaded Runtimes. // https://github.com/asomers/futures-locks/issues/5 #[cfg(feature = "tokio")] #[test] fn with_threadpool() { let mtx = Mutex::::new(5); let rt = runtime::Builder::new_multi_thread().build().unwrap(); let r = rt.block_on(async { mtx.with(|guard| { ready(*guard) }).await }); assert_eq!(r, 5); } #[cfg(feature = "tokio")] #[test] fn with_local_ok() { // Note: Rc is not Send let mtx = Mutex::>::new(Rc::new(5)); let rt = runtime::Builder::new_current_thread().build().unwrap(); let r = rt.block_on(async { mtx.with_local(|guard| { ready(**guard) }).await }); assert_eq!(r, 5); } futures-locks-0.7.1/tests/rwlock.rs000064400000000000000000000323771046102023000154640ustar 00000000000000//vim: tw=80 use futures::{ FutureExt, StreamExt, stream }; #[cfg(feature = "tokio")] use futures::future::ready; use std::sync::Arc; #[cfg(feature = "tokio")] use std::rc::Rc; use tokio::{self, sync::Barrier}; #[cfg(feature = "tokio")] use tokio::runtime; use tokio_test::{ assert_pending, assert_ready, task::spawn }; use futures_locks::*; // When an exclusively owned RwLock future is dropped after gaining ownership // but before being polled, it should relinquish ownership. If not, deadlocks // may result. #[test] fn drop_exclusive_before_poll_returns_ready() { let rwlock = RwLock::::new(42); let mut fut1 = spawn(rwlock.read()); let guard1 = assert_ready!(fut1.poll()); // fut1 immediately gets ownership let mut fut2 = spawn(rwlock.write()); assert_pending!(fut2.poll()); // fut2 is blocked drop(guard1); // ownership transfers to fut2 drop(fut1); drop(fut2); // relinquish ownership let mut fut3 = spawn(rwlock.read()); // fut3 immediately gets ownership assert_ready!(fut3.poll()); } // When a pending exclusive RwLock gets dropped after being polled() but before // gaining ownership, ownership should pass on to the next waiter. #[test] fn drop_exclusive_before_ready() { let rwlock = RwLock::::new(42); let mut fut1 = spawn(rwlock.read()); let guard1 = assert_ready!(fut1.poll()); // fut1 immediately gets ownership let mut fut2 = spawn(rwlock.write()); assert_pending!(fut2.poll()); // fut2 is blocked let mut fut3 = spawn(rwlock.write()); assert_pending!(fut3.poll()); // fut3 is also blocked drop(fut2); // drop before gaining ownership drop(guard1); // ownership transfers to fut3 drop(fut1); assert!(fut3.is_woken()); assert_ready!(fut3.poll()); } // Like drop_exclusive_before_ready, but the rwlock is already locked in // exclusive mode. #[test] fn drop_exclusive_before_ready_2() { let rwlock = RwLock::::new(42); let mut fut1 = spawn(rwlock.write()); let guard1 = assert_ready!(fut1.poll()); // fut1 immediately gets ownership let mut fut2 = spawn(rwlock.write()); assert_pending!(fut2.poll()); // fut2 is blocked let mut fut3 = spawn(rwlock.write()); assert_pending!(fut3.poll()); // fut3 is also blocked drop(fut2); // drop before gaining ownership drop(guard1); // ownership transfers to fut3 drop(fut1); assert!(fut3.is_woken()); assert_ready!(fut3.poll()); } // When a nonexclusively owned RwLock future is dropped after gaining ownership // but before begin polled, it should relinquish ownership. If not, deadlocks // may result. #[test] fn drop_shared_before_poll_returns_ready() { let rwlock = RwLock::::new(42); let mut fut1 = spawn(rwlock.write()); let guard1 = assert_ready!(fut1.poll()); // fut1 immediately gets ownership let mut fut2 = spawn(rwlock.read()); assert_pending!(fut2.poll()); // fut2 is blocked drop(guard1); // ownership transfers to fut2 drop(fut2); // relinquish ownership let mut fut3 = spawn(rwlock.write()); // fut3 immediately gets ownership assert_ready!(fut3.poll()); } // When a pending shared RwLock gets dropped after being polled() but before // gaining ownership, ownership should pass on to the next waiter. #[test] fn drop_shared_before_ready() { let rwlock = RwLock::::new(42); let mut fut1 = spawn(rwlock.write()); let guard1 = assert_ready!(fut1.poll()); // fut1 immediately gets ownership let mut fut2 = spawn(rwlock.read()); assert_pending!(fut2.poll()); // fut2 is blocked let mut fut3 = spawn(rwlock.read()); assert_pending!(fut3.poll()); // fut3 is also blocked drop(fut2); // drop before gaining ownership drop(guard1); // ownership transfers to fut3 drop(fut1); assert!(fut3.is_woken()); assert_ready!(fut3.poll()); } // Mutably dereference a uniquely owned RwLock #[test] fn get_mut() { let mut rwlock = RwLock::::new(42); *rwlock.get_mut().unwrap() += 1; assert_eq!(*rwlock.get_mut().unwrap(), 43); } // Cloned RwLocks cannot be deferenced #[test] fn get_mut_cloned() { let mut rwlock = RwLock::::new(42); let _clone = rwlock.clone(); assert!(rwlock.get_mut().is_none()); } // Acquire an RwLock nonexclusively by two different tasks simultaneously . #[test] fn read_shared() { let rwlock = RwLock::::new(42); let mut fut1 = spawn(rwlock.read()); let _guard1 = assert_ready!(fut1.poll()); // fut1 immediately gets ownership let mut fut2 = spawn(rwlock.read()); let _guard2 = assert_ready!(fut2.poll()); // fut2 also gets ownership } // Acquire an RwLock nonexclusively by a single task #[tokio::test] async fn read_uncontested() { let rwlock = RwLock::::new(42); let guard = rwlock.read().await; let result = *guard; drop(guard); assert_eq!(result, 42); } // Attempt to acquire an RwLock for reading that already has a writer #[test] fn write_read_contested() { let rwlock = RwLock::::new(0); let mut fut0 = spawn(rwlock.write()); let guard0 = assert_ready!(fut0.poll()); // fut0 immediately gets ownership let mut fut1 = spawn(rwlock.read()); assert_pending!(fut1.poll()); // fut1 is blocked drop(guard0); // Ownership transfers to fut1 assert!(fut1.is_woken()); assert_ready!(fut1.poll()); } // Attempt to acquire an rwlock exclusively when it already has a reader. #[test] fn read_write_contested() { let rwlock = RwLock::::new(42); let mut fut0 = spawn(rwlock.read()); let guard0 = assert_ready!(fut0.poll()); // fut0 immediately gets ownership let mut fut1 = spawn(rwlock.write()); assert_pending!(fut1.poll()); // fut1 is blocked drop(guard0); // Ownership transfers to fut1 assert!(fut1.is_woken()); assert_ready!(fut1.poll()); } // Attempt to acquire an rwlock exclusively when it already has a writer. #[test] fn write_contested() { let rwlock = RwLock::::new(42); let mut fut0 = spawn(rwlock.write()); let guard0 = assert_ready!(fut0.poll()); // fut0 immediately gets ownership let mut fut1 = spawn(rwlock.write()); assert_pending!(fut1.poll()); // fut1 is blocked drop(guard0); // Ownership transfers to fut1 assert!(fut1.is_woken()); assert_ready!(fut1.poll()); } #[test] fn try_read_uncontested() { let rwlock = RwLock::::new(42); assert_eq!(42, *rwlock.try_read().unwrap()); } #[test] fn try_read_contested() { let rwlock = RwLock::::new(42); let _guard = rwlock.try_write(); assert!(rwlock.try_read().is_err()); } #[test] fn try_unwrap_multiply_referenced() { let rwlock = RwLock::::new(0); let _rwlock2 = rwlock.clone(); assert!(rwlock.try_unwrap().is_err()); } #[test] fn try_write_uncontested() { let rwlock = RwLock::::new(0); *rwlock.try_write().unwrap() += 5; assert_eq!(5, rwlock.try_unwrap().unwrap()); } #[test] fn try_write_contested() { let rwlock = RwLock::::new(42); let _guard = rwlock.try_read(); assert!(rwlock.try_write().is_err()); } // Acquire an uncontested RwLock in exclusive mode. poll immediately returns // Ready #[tokio::test] async fn write_uncontested() { let rwlock = RwLock::::new(0); let mut guard = rwlock.write().await; *guard += 5; drop(guard); assert_eq!(rwlock.try_unwrap().expect("try_unwrap"), 5); } // RwLocks should be acquired in the order that their Futures are waited upon. #[tokio::test] async fn write_order() { let rwlock = RwLock::>::new(vec![]); let fut2 = rwlock.write().map(|mut guard| guard.push(2)); let fut1 = rwlock.write().map(|mut guard| guard.push(1)); fut1.then(|_| fut2).await; assert_eq!(rwlock.try_unwrap().unwrap(), vec![1, 2]); } // A single RwLock is contested by tasks in multiple threads #[tokio::test] async fn multithreaded() { let rwlock = RwLock::::new(0); let rwlock_clone0 = rwlock.clone(); let rwlock_clone1 = rwlock.clone(); let rwlock_clone2 = rwlock.clone(); let rwlock_clone3 = rwlock.clone(); let barrier = Arc::new(Barrier::new(5)); let b0 = barrier.clone(); let b1 = barrier.clone(); let b2 = barrier.clone(); let b3 = barrier.clone(); tokio::task::spawn(async move { stream::iter(0..1000).for_each(move |_| { let rwlock_clone4 = rwlock_clone0.clone(); rwlock_clone0.write() .map(|mut guard| { *guard += 2 }) .then(move |_| rwlock_clone4.read().map(|_| ())) }).await; b0.wait().await; }); tokio::task::spawn(async move { stream::iter(0..1000).for_each(move |_| { let rwlock_clone5 = rwlock_clone1.clone(); rwlock_clone1.write() .map(|mut guard| { *guard += 3 }) .then(move |_| rwlock_clone5.read().map(|_| ())) }).await; b1.wait().await; }); tokio::task::spawn(async move { stream::iter(0..1000).for_each(move |_| { let rwlock_clone6 = rwlock_clone2.clone(); rwlock_clone2.write() .map(|mut guard| { *guard += 5 }) .then(move |_| rwlock_clone6.read().map(|_| ())) }).await; b2.wait().await; }); tokio::task::spawn(async move { stream::iter(0..1000).for_each(move |_| { let rwlock_clone7 = rwlock_clone3.clone(); rwlock_clone3.write() .map(|mut guard| { *guard += 7 }) .then(move |_| rwlock_clone7.read().map(|_| ())) }).await; b3.wait().await; }); barrier.wait().await; assert_eq!(rwlock.try_unwrap().expect("try_unwrap"), 17_000); } // Returning errors is simpler than in futures-locks 0.5: just return a Result #[cfg(feature = "tokio")] #[test] fn with_read_err() { let mtx = RwLock::::new(-5); let rt = runtime::Builder::new_current_thread().build().unwrap(); let r = rt.block_on(async { mtx.with_read(|guard| { if *guard > 0 { ready(Ok(*guard)) } else { ready(Err("Whoops!")) } }).await }); assert_eq!(r, Err("Whoops!")); } #[cfg(feature = "tokio")] #[test] fn with_read_ok() { let mtx = RwLock::::new(5); let rt = runtime::Builder::new_current_thread().build().unwrap(); let r = rt.block_on(async { mtx.with_read(|guard| { ready(*guard) }).await }); assert_eq!(r, 5); } // RwLock::with_read should work with multithreaded Runtimes as well as // single-threaded Runtimes. // https://github.com/asomers/futures-locks/issues/5 #[cfg(feature = "tokio")] #[test] fn with_read_threadpool() { let mtx = RwLock::::new(5); let rt = runtime::Builder::new_multi_thread().build().unwrap(); let r = rt.block_on(async { mtx.with_read(|guard| { ready(*guard) }).await }); assert_eq!(r, 5); } #[cfg(feature = "tokio")] #[test] fn with_read_local_ok() { // Note: Rc is not Send let rwlock = RwLock::>::new(Rc::new(5)); let rt = runtime::Builder::new_current_thread().build().unwrap(); let r = rt.block_on(async { rwlock.with_read_local(|guard| { ready(**guard) }).await }); assert_eq!(r, 5); } // Returning errors is simpler than in futures-locks 0.5: just return a Result #[cfg(feature = "tokio")] #[test] fn with_write_err() { let mtx = RwLock::::new(-5); let rt = runtime::Builder::new_current_thread().build().unwrap(); let r = rt.block_on(async { mtx.with_write(|mut guard| { if *guard > 0 { *guard -= 1; ready(Ok(())) } else { ready(Err("Whoops!")) } }).await }); assert_eq!(r, Err("Whoops!")); } #[cfg(feature = "tokio")] #[test] fn with_write_ok() { let mtx = RwLock::::new(5); let rt = runtime::Builder::new_current_thread().build().unwrap(); rt.block_on(async { mtx.with_write(|mut guard| { *guard += 1; ready(()) }).await }); assert_eq!(mtx.try_unwrap().unwrap(), 6); } // RwLock::with_write should work with multithreaded Runtimes as well as // single-threaded Runtimes. // https://github.com/asomers/futures-locks/issues/5 #[cfg(feature = "tokio")] #[test] fn with_write_threadpool() { let mtx = RwLock::::new(5); let rt = runtime::Builder::new_multi_thread().build().unwrap(); rt.block_on(async { mtx.with_write(|mut guard| { *guard += 1; ready(()) }).await }); assert_eq!(mtx.try_unwrap().unwrap(), 6); } #[cfg(feature = "tokio")] #[test] fn with_write_local_ok() { // Note: Rc is not Send let rwlock = RwLock::>::new(Rc::new(5)); let rt = runtime::Builder::new_current_thread().build().unwrap(); rt.block_on(async { rwlock.with_write_local(|mut guard| { *Rc::get_mut(&mut *guard).unwrap() += 1; ready(()) }).await }); assert_eq!(*rwlock.try_unwrap().unwrap(), 6); } futures-locks-0.7.1/tests/test.rs000064400000000000000000000001031046102023000151200ustar 00000000000000//vim: tw=80 extern crate tokio as tokio; mod mutex; mod rwlock;