atomic_refcell-0.1.13/.cargo_vcs_info.json0000644000000001360000000000100140660ustar { "git": { "sha1": "f9d987f7f863364e5bc3a32f6683cb0f303079c6" }, "path_in_vcs": "" }atomic_refcell-0.1.13/.gitignore000064400000000000000000000000221046102023000146400ustar 00000000000000target Cargo.lock atomic_refcell-0.1.13/Cargo.toml0000644000000016360000000000100120720ustar # 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 = "atomic_refcell" version = "0.1.13" authors = ["Bobby Holley "] description = "Threadsafe RefCell" documentation = "https://docs.rs/atomic_refcell/" readme = "README.md" license = "Apache-2.0/MIT" repository = "https://github.com/bholley/atomic_refcell" [dependencies.serde] version = "1.0" optional = true [dev-dependencies.serde_json] version = "1.0" [features] default = [] serde = ["dep:serde"] atomic_refcell-0.1.13/Cargo.toml.orig000064400000000000000000000006651046102023000155540ustar 00000000000000[package] name = "atomic_refcell" version = "0.1.13" authors = ["Bobby Holley "] description = "Threadsafe RefCell" license = "Apache-2.0/MIT" repository = "https://github.com/bholley/atomic_refcell" documentation = "https://docs.rs/atomic_refcell/" edition = "2018" [dependencies] serde = { version = "1.0", optional = true } [dev-dependencies] serde_json = "1.0" [features] default = [] serde = ["dep:serde"] atomic_refcell-0.1.13/LICENSE.APACHE000064400000000000000000000261351046102023000146120ustar 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. atomic_refcell-0.1.13/LICENSE.MIT000064400000000000000000000020551046102023000143150ustar 00000000000000MIT License Copyright (c) 2022 Bobby Holley 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. atomic_refcell-0.1.13/README.md000064400000000000000000000000561046102023000141360ustar 00000000000000# atomic_refcell Threadsafe RefCell for Rust. atomic_refcell-0.1.13/SECURITY.md000064400000000000000000000012671046102023000144550ustar 00000000000000# Security Policy ## Supported Versions Security updates are applied only to the latest release. ## Reporting a Vulnerability If you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released. Please disclose it at [security advisory](https://github.com/bholley/atomic_refcell/security/advisories/new). This project is maintained by a team of volunteers on a reasonable-effort basis. As such, please give us at least 90 days to work on a fix before public exposure. atomic_refcell-0.1.13/benches/basic.rs000064400000000000000000000013761046102023000157230ustar 00000000000000#![feature(test)] extern crate atomic_refcell; extern crate test; use atomic_refcell::AtomicRefCell; use test::Bencher; #[derive(Default)] struct Bar(u32); #[bench] fn immutable_borrow(b: &mut Bencher) { let a = AtomicRefCell::new(Bar::default()); b.iter(|| a.borrow()); } #[bench] fn immutable_second_borrow(b: &mut Bencher) { let a = AtomicRefCell::new(Bar::default()); let _first = a.borrow(); b.iter(|| a.borrow()); } #[bench] fn immutable_third_borrow(b: &mut Bencher) { let a = AtomicRefCell::new(Bar::default()); let _first = a.borrow(); let _second = a.borrow(); b.iter(|| a.borrow()); } #[bench] fn mutable_borrow(b: &mut Bencher) { let a = AtomicRefCell::new(Bar::default()); b.iter(|| a.borrow_mut()); } atomic_refcell-0.1.13/src/lib.rs000064400000000000000000000441771046102023000145760ustar 00000000000000//! Implements a container type providing RefCell-like semantics for objects //! shared across threads. //! //! RwLock is traditionally considered to be the |Sync| analogue of RefCell. //! However, for consumers that can guarantee that they will never mutably //! borrow the contents concurrently with immutable borrows, an RwLock is //! overkill, and has key disadvantages: //! * Performance: Even the fastest existing implementation of RwLock (that of //! parking_lot) performs at least two atomic operations during immutable //! borrows. This makes mutable borrows significantly cheaper than immutable //! borrows, leading to weird incentives when writing performance-critical //! code. //! * Features: Implementing AtomicRefCell on top of RwLock makes it impossible //! to implement useful things like AtomicRef{,Mut}::map. //! //! As such, we re-implement RefCell semantics from scratch with a single atomic //! reference count. The primary complication of this scheme relates to keeping //! things in a consistent state when one thread performs an illegal borrow and //! panics. Since an AtomicRefCell can be accessed by multiple threads, and since //! panics are recoverable, we need to ensure that an illegal (panicking) access by //! one thread does not lead to undefined behavior on other, still-running threads. //! //! So we represent things as follows: //! * Any value with the high bit set (so half the total refcount space) indicates //! a mutable borrow. //! * Mutable borrows perform an atomic compare-and-swap, swapping in the high bit //! if the current value is zero. If the current value is non-zero, the thread //! panics and the value is left undisturbed. //! * Immutable borrows perform an atomic increment. If the new value has the high //! bit set, the thread panics. The incremented refcount is left as-is, since it //! still represents a valid mutable borrow. When the mutable borrow is released, //! the refcount is set unconditionally to zero, clearing any stray increments by //! panicked threads. //! //! There are a few additional purely-academic complications to handle overflow, //! which are documented in the implementation. //! //! The rest of this module is mostly derived by copy-pasting the implementation of //! RefCell and fixing things up as appropriate. Certain non-threadsafe methods //! have been removed. We segment the concurrency logic from the rest of the code to //! keep the tricky parts small and easy to audit. #![no_std] #![allow(unsafe_code)] #![deny(missing_docs)] use core::cell::UnsafeCell; use core::cmp; use core::fmt; use core::fmt::{Debug, Display}; use core::marker::PhantomData; use core::ops::{Deref, DerefMut}; use core::ptr::NonNull; use core::sync::atomic; use core::sync::atomic::AtomicUsize; #[cfg(feature = "serde")] extern crate serde; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; /// A threadsafe analogue to RefCell. pub struct AtomicRefCell { borrow: AtomicUsize, value: UnsafeCell, } /// An error returned by [`AtomicRefCell::try_borrow`](struct.AtomicRefCell.html#method.try_borrow). pub struct BorrowError { _private: (), } impl Debug for BorrowError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("BorrowError").finish() } } impl Display for BorrowError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Display::fmt("already mutably borrowed", f) } } /// An error returned by [`AtomicRefCell::try_borrow_mut`](struct.AtomicRefCell.html#method.try_borrow_mut). pub struct BorrowMutError { _private: (), } impl Debug for BorrowMutError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("BorrowMutError").finish() } } impl Display for BorrowMutError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Display::fmt("already borrowed", f) } } impl AtomicRefCell { /// Creates a new `AtomicRefCell` containing `value`. #[inline] pub const fn new(value: T) -> AtomicRefCell { AtomicRefCell { borrow: AtomicUsize::new(0), value: UnsafeCell::new(value), } } /// Consumes the `AtomicRefCell`, returning the wrapped value. #[inline] pub fn into_inner(self) -> T { debug_assert!(self.borrow.load(atomic::Ordering::Acquire) == 0); self.value.into_inner() } } impl AtomicRefCell { /// Immutably borrows the wrapped value. #[inline] pub fn borrow(&self) -> AtomicRef { match AtomicBorrowRef::try_new(&self.borrow) { Ok(borrow) => AtomicRef { value: unsafe { NonNull::new_unchecked(self.value.get()) }, borrow, }, Err(s) => panic!("{}", s), } } /// Attempts to immutably borrow the wrapped value, but instead of panicking /// on a failed borrow, returns `Err`. #[inline] pub fn try_borrow(&self) -> Result, BorrowError> { match AtomicBorrowRef::try_new(&self.borrow) { Ok(borrow) => Ok(AtomicRef { value: unsafe { NonNull::new_unchecked(self.value.get()) }, borrow, }), Err(_) => Err(BorrowError { _private: () }), } } /// Mutably borrows the wrapped value. #[inline] pub fn borrow_mut(&self) -> AtomicRefMut { match AtomicBorrowRefMut::try_new(&self.borrow) { Ok(borrow) => AtomicRefMut { value: unsafe { NonNull::new_unchecked(self.value.get()) }, borrow, marker: PhantomData, }, Err(s) => panic!("{}", s), } } /// Attempts to mutably borrow the wrapped value, but instead of panicking /// on a failed borrow, returns `Err`. #[inline] pub fn try_borrow_mut(&self) -> Result, BorrowMutError> { match AtomicBorrowRefMut::try_new(&self.borrow) { Ok(borrow) => Ok(AtomicRefMut { value: unsafe { NonNull::new_unchecked(self.value.get()) }, borrow, marker: PhantomData, }), Err(_) => Err(BorrowMutError { _private: () }), } } /// Returns a raw pointer to the underlying data in this cell. /// /// External synchronization is needed to avoid data races when dereferencing /// the pointer. #[inline] pub fn as_ptr(&self) -> *mut T { self.value.get() } /// Returns a mutable reference to the wrapped value. /// /// No runtime checks take place (unless debug assertions are enabled) /// because this call borrows `AtomicRefCell` mutably at compile-time. #[inline] pub fn get_mut(&mut self) -> &mut T { debug_assert!(self.borrow.load(atomic::Ordering::Acquire) == 0); unsafe { &mut *self.value.get() } } } // // Core synchronization logic. Keep this section small and easy to audit. // const HIGH_BIT: usize = !(::core::usize::MAX >> 1); const MAX_FAILED_BORROWS: usize = HIGH_BIT + (HIGH_BIT >> 1); struct AtomicBorrowRef<'b> { borrow: &'b AtomicUsize, } impl<'b> AtomicBorrowRef<'b> { #[inline] fn try_new(borrow: &'b AtomicUsize) -> Result { let new = borrow.fetch_add(1, atomic::Ordering::Acquire) + 1; if new & HIGH_BIT != 0 { // If the new count has the high bit set, that almost certainly // means there's an pre-existing mutable borrow. In that case, // we simply leave the increment as a benign side-effect and // return `Err`. Once the mutable borrow is released, the // count will be reset to zero unconditionally. // // The overflow check here ensures that an unbounded number of // immutable borrows during the scope of one mutable borrow // will soundly trigger a panic (or abort) rather than UB. Self::check_overflow(borrow, new); Err("already mutably borrowed") } else { Ok(AtomicBorrowRef { borrow: borrow }) } } #[cold] #[inline(never)] fn check_overflow(borrow: &'b AtomicUsize, new: usize) { if new == HIGH_BIT { // We overflowed into the reserved upper half of the refcount // space. Before panicking, decrement the refcount to leave things // in a consistent immutable-borrow state. // // This can basically only happen if somebody forget()s AtomicRefs // in a tight loop. borrow.fetch_sub(1, atomic::Ordering::Release); panic!("too many immutable borrows"); } else if new >= MAX_FAILED_BORROWS { // During the mutable borrow, an absurd number of threads have // attempted to increment the refcount with immutable borrows. // To avoid hypothetically wrapping the refcount, we abort the // process once a certain threshold is reached. // // This requires billions of borrows to fail during the scope of // one mutable borrow, and so is very unlikely to happen in a real // program. // // To avoid a potential unsound state after overflowing, we make // sure the entire process aborts. // // Right now, there's no stable way to do that without `std`: // https://github.com/rust-lang/rust/issues/67952 // As a workaround, we cause an abort by making this thread panic // during the unwinding of another panic. // // On platforms where the panic strategy is already 'abort', the // ForceAbort object here has no effect, as the program already // panics before it is dropped. struct ForceAbort; impl Drop for ForceAbort { fn drop(&mut self) { panic!("Aborting to avoid unsound state of AtomicRefCell"); } } let _abort = ForceAbort; panic!("Too many failed borrows"); } } } impl<'b> Drop for AtomicBorrowRef<'b> { #[inline] fn drop(&mut self) { let old = self.borrow.fetch_sub(1, atomic::Ordering::Release); // This assertion is technically incorrect in the case where another // thread hits the hypothetical overflow case, since we might observe // the refcount before it fixes it up (and panics). But that never will // never happen in a real program, and this is a debug_assert! anyway. debug_assert!(old & HIGH_BIT == 0); } } struct AtomicBorrowRefMut<'b> { borrow: &'b AtomicUsize, } impl<'b> Drop for AtomicBorrowRefMut<'b> { #[inline] fn drop(&mut self) { self.borrow.store(0, atomic::Ordering::Release); } } impl<'b> AtomicBorrowRefMut<'b> { #[inline] fn try_new(borrow: &'b AtomicUsize) -> Result, &'static str> { // Use compare-and-swap to avoid corrupting the immutable borrow count // on illegal mutable borrows. let old = match borrow.compare_exchange( 0, HIGH_BIT, atomic::Ordering::Acquire, atomic::Ordering::Relaxed, ) { Ok(x) => x, Err(x) => x, }; if old == 0 { Ok(AtomicBorrowRefMut { borrow }) } else if old & HIGH_BIT == 0 { Err("already immutably borrowed") } else { Err("already mutably borrowed") } } } unsafe impl Send for AtomicRefCell {} unsafe impl Sync for AtomicRefCell {} // // End of core synchronization logic. No tricky thread stuff allowed below // this point. // impl Clone for AtomicRefCell { #[inline] fn clone(&self) -> AtomicRefCell { AtomicRefCell::new(self.borrow().clone()) } } impl Default for AtomicRefCell { #[inline] fn default() -> AtomicRefCell { AtomicRefCell::new(Default::default()) } } impl PartialEq for AtomicRefCell { #[inline] fn eq(&self, other: &AtomicRefCell) -> bool { *self.borrow() == *other.borrow() } } impl Eq for AtomicRefCell {} impl PartialOrd for AtomicRefCell { #[inline] fn partial_cmp(&self, other: &AtomicRefCell) -> Option { self.borrow().partial_cmp(&*other.borrow()) } } impl Ord for AtomicRefCell { #[inline] fn cmp(&self, other: &AtomicRefCell) -> cmp::Ordering { self.borrow().cmp(&*other.borrow()) } } impl From for AtomicRefCell { fn from(t: T) -> AtomicRefCell { AtomicRefCell::new(t) } } impl<'b> Clone for AtomicBorrowRef<'b> { #[inline] fn clone(&self) -> AtomicBorrowRef<'b> { AtomicBorrowRef::try_new(self.borrow).unwrap() } } /// A wrapper type for an immutably borrowed value from an `AtomicRefCell`. pub struct AtomicRef<'b, T: ?Sized + 'b> { value: NonNull, borrow: AtomicBorrowRef<'b>, } // SAFETY: `AtomicRef<'_, T> acts as a reference. `AtomicBorrowRef` is a // reference to an atomic. unsafe impl<'b, T: ?Sized> Sync for AtomicRef<'b, T> where for<'a> &'a T: Sync {} unsafe impl<'b, T: ?Sized> Send for AtomicRef<'b, T> where for<'a> &'a T: Send {} impl<'b, T: ?Sized> Deref for AtomicRef<'b, T> { type Target = T; #[inline] fn deref(&self) -> &T { // SAFETY: We hold shared borrow of the value. unsafe { self.value.as_ref() } } } impl<'b, T: ?Sized> AtomicRef<'b, T> { /// Copies an `AtomicRef`. #[inline] pub fn clone(orig: &AtomicRef<'b, T>) -> AtomicRef<'b, T> { AtomicRef { value: orig.value, borrow: orig.borrow.clone(), } } /// Make a new `AtomicRef` for a component of the borrowed data. #[inline] pub fn map(orig: AtomicRef<'b, T>, f: F) -> AtomicRef<'b, U> where F: FnOnce(&T) -> &U, { AtomicRef { value: NonNull::from(f(&*orig)), borrow: orig.borrow, } } /// Make a new `AtomicRef` for an optional component of the borrowed data. #[inline] pub fn filter_map(orig: AtomicRef<'b, T>, f: F) -> Option> where F: FnOnce(&T) -> Option<&U>, { Some(AtomicRef { value: NonNull::from(f(&*orig)?), borrow: orig.borrow, }) } } impl<'b, T: ?Sized> AtomicRefMut<'b, T> { /// Make a new `AtomicRefMut` for a component of the borrowed data, e.g. an enum /// variant. #[inline] pub fn map(mut orig: AtomicRefMut<'b, T>, f: F) -> AtomicRefMut<'b, U> where F: FnOnce(&mut T) -> &mut U, { AtomicRefMut { value: NonNull::from(f(&mut *orig)), borrow: orig.borrow, marker: PhantomData, } } /// Make a new `AtomicRefMut` for an optional component of the borrowed data. #[inline] pub fn filter_map( mut orig: AtomicRefMut<'b, T>, f: F, ) -> Option> where F: FnOnce(&mut T) -> Option<&mut U>, { Some(AtomicRefMut { value: NonNull::from(f(&mut *orig)?), borrow: orig.borrow, marker: PhantomData, }) } } /// A wrapper type for a mutably borrowed value from an `AtomicRefCell`. pub struct AtomicRefMut<'b, T: ?Sized + 'b> { value: NonNull, borrow: AtomicBorrowRefMut<'b>, // `NonNull` is covariant over `T`, but this is used in place of a mutable // reference so we need to be invariant over `T`. marker: PhantomData<&'b mut T>, } // SAFETY: `AtomicRefMut<'_, T> acts as a mutable reference. // `AtomicBorrowRefMut` is a reference to an atomic. unsafe impl<'b, T: ?Sized> Sync for AtomicRefMut<'b, T> where for<'a> &'a mut T: Sync {} unsafe impl<'b, T: ?Sized> Send for AtomicRefMut<'b, T> where for<'a> &'a mut T: Send {} impl<'b, T: ?Sized> Deref for AtomicRefMut<'b, T> { type Target = T; #[inline] fn deref(&self) -> &T { // SAFETY: We hold an exclusive borrow of the value. unsafe { self.value.as_ref() } } } impl<'b, T: ?Sized> DerefMut for AtomicRefMut<'b, T> { #[inline] fn deref_mut(&mut self) -> &mut T { // SAFETY: We hold an exclusive borrow of the value. unsafe { self.value.as_mut() } } } impl<'b, T: ?Sized + Debug + 'b> Debug for AtomicRef<'b, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { ::fmt(self, f) } } impl<'b, T: ?Sized + Debug + 'b> Debug for AtomicRefMut<'b, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { ::fmt(self, f) } } impl Debug for AtomicRefCell { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.try_borrow() { Ok(borrow) => f.debug_struct("AtomicRefCell").field("value", &borrow).finish(), Err(_) => { // The RefCell is mutably borrowed so we can't look at its value // here. Show a placeholder instead. struct BorrowedPlaceholder; impl Debug for BorrowedPlaceholder { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("") } } f.debug_struct("AtomicRefCell").field("value", &BorrowedPlaceholder).finish() } } } } #[cfg(feature = "serde")] impl<'de, T: Deserialize<'de>> Deserialize<'de> for AtomicRefCell { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { T::deserialize(deserializer).map(Self::from) } } #[cfg(feature = "serde")] impl Serialize for AtomicRefCell { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer, { use serde::ser::Error; match self.try_borrow() { Ok(value) => value.serialize(serializer), Err(_err) => Err(S::Error::custom("already mutably borrowed")), } } } atomic_refcell-0.1.13/tests/async.rs000064400000000000000000000014161046102023000155050ustar 00000000000000use std::future::Future; use atomic_refcell::AtomicRefCell; fn spawn(_future: Fut) where Fut: Future + Send + Sync, { } async fn something_async() {} // see https://github.com/bholley/atomic_refcell/issues/24 #[test] fn test_atomic_ref_in_spawn() { let arc: Box usize + Send + Sync> = Box::new(|| 42); let a = AtomicRefCell::new(arc); spawn(async move { let x = a.borrow(); something_async().await; assert_eq!(x(), 42); }); } #[test] fn test_atomic_ref_mut_in_spawn() { let arc: Box usize + Send + Sync> = Box::new(|| 42); let a = AtomicRefCell::new(arc); spawn(async move { let x = a.borrow_mut(); something_async().await; assert_eq!(x(), 42); }); } atomic_refcell-0.1.13/tests/basic.rs000064400000000000000000000113661046102023000154560ustar 00000000000000extern crate atomic_refcell; #[cfg(feature = "serde")] extern crate serde; use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut}; #[derive(Debug)] struct Foo { u: u32, } #[derive(Debug)] struct Bar { f: Foo, } impl Default for Bar { fn default() -> Self { Bar { f: Foo { u: 42 } } } } // FIXME(bholley): Add tests to exercise this in concurrent scenarios. #[test] fn immutable() { let a = AtomicRefCell::new(Bar::default()); let _first = a.borrow(); let _second = a.borrow(); } #[test] fn try_immutable() { let a = AtomicRefCell::new(Bar::default()); let _first = a.try_borrow().unwrap(); let _second = a.try_borrow().unwrap(); } #[test] fn mutable() { let a = AtomicRefCell::new(Bar::default()); let _ = a.borrow_mut(); } #[test] fn try_mutable() { let a = AtomicRefCell::new(Bar::default()); let _ = a.try_borrow_mut().unwrap(); } #[test] fn get_mut() { let mut a = AtomicRefCell::new(Bar::default()); let _ = a.get_mut(); } #[test] fn interleaved() { let a = AtomicRefCell::new(Bar::default()); { let _ = a.borrow_mut(); } { let _first = a.borrow(); let _second = a.borrow(); } { let _ = a.borrow_mut(); } } #[test] fn try_interleaved() { let a = AtomicRefCell::new(Bar::default()); { let _ = a.try_borrow_mut().unwrap(); } { let _first = a.try_borrow().unwrap(); let _second = a.try_borrow().unwrap(); let _ = a.try_borrow_mut().unwrap_err(); } { let _first = a.try_borrow_mut().unwrap(); let _ = a.try_borrow().unwrap_err(); } } // For Miri to catch issues when calling a function. // // See how this scenerio affects std::cell::RefCell implementation: // https://github.com/rust-lang/rust/issues/63787 // // Also see relevant unsafe code guidelines issue: // https://github.com/rust-lang/unsafe-code-guidelines/issues/125 #[test] fn drop_and_borrow_in_fn_call() { fn drop_and_borrow(cell: &AtomicRefCell, borrow: AtomicRef<'_, Bar>) { drop(borrow); *cell.borrow_mut() = Bar::default(); } let a = AtomicRefCell::new(Bar::default()); let borrow = a.borrow(); drop_and_borrow(&a, borrow); } #[test] #[should_panic(expected = "already immutably borrowed")] fn immutable_then_mutable() { let a = AtomicRefCell::new(Bar::default()); let _first = a.borrow(); let _second = a.borrow_mut(); } #[test] fn immutable_then_try_mutable() { let a = AtomicRefCell::new(Bar::default()); let _first = a.borrow(); let _second = a.try_borrow_mut().unwrap_err(); } #[test] #[should_panic(expected = "already mutably borrowed")] fn mutable_then_immutable() { let a = AtomicRefCell::new(Bar::default()); let _first = a.borrow_mut(); let _second = a.borrow(); } #[test] fn mutable_then_try_immutable() { let a = AtomicRefCell::new(Bar::default()); let _first = a.borrow_mut(); let _second = a.try_borrow().unwrap_err(); } #[test] #[should_panic(expected = "already mutably borrowed")] fn double_mutable() { let a = AtomicRefCell::new(Bar::default()); let _first = a.borrow_mut(); let _second = a.borrow_mut(); } #[test] fn mutable_then_try_mutable() { let a = AtomicRefCell::new(Bar::default()); let _first = a.borrow_mut(); let _second = a.try_borrow_mut().unwrap_err(); } #[test] fn map() { let a = AtomicRefCell::new(Bar::default()); let b = a.borrow(); assert_eq!(b.f.u, 42); let c = AtomicRef::map(b, |x| &x.f); assert_eq!(c.u, 42); let d = AtomicRef::map(c, |x| &x.u); assert_eq!(*d, 42); } #[test] fn map_mut() { let a = AtomicRefCell::new(Bar::default()); let mut b = a.borrow_mut(); assert_eq!(b.f.u, 42); b.f.u = 43; let mut c = AtomicRefMut::map(b, |x| &mut x.f); assert_eq!(c.u, 43); c.u = 44; let mut d = AtomicRefMut::map(c, |x| &mut x.u); assert_eq!(*d, 44); *d = 45; assert_eq!(*d, 45); } #[test] fn debug_fmt() { let a = AtomicRefCell::new(Foo { u: 42 }); assert_eq!(format!("{:?}", a), "AtomicRefCell { value: Foo { u: 42 } }"); } #[test] fn debug_fmt_borrowed() { let a = AtomicRefCell::new(Foo { u: 42 }); let _b = a.borrow(); assert_eq!(format!("{:?}", a), "AtomicRefCell { value: Foo { u: 42 } }"); } #[test] fn debug_fmt_borrowed_mut() { let a = AtomicRefCell::new(Foo { u: 42 }); let _b = a.borrow_mut(); assert_eq!(format!("{:?}", a), "AtomicRefCell { value: }"); } #[test] #[cfg(feature = "serde")] fn serde() { let value = 10; let cell = AtomicRefCell::new(value); let serialized = serde_json::to_string(&cell).unwrap(); let deserialized = serde_json::from_str::>(&serialized).unwrap(); assert_eq!(*deserialized.borrow(), value); }