// Original work Copyright (c) 2014 The Rust Project Developers // Modified work Copyright (c) 2016-2020 Nikita Pekin and the lazycell contributors // See the README.md file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
//! This crate provides a `LazyCell` struct which acts as a lazily filled //! `Cell`. //! //! With a `RefCell`, the inner contents cannot be borrowed for the lifetime of //! the entire object, but only of the borrows returned. A `LazyCell` is a //! variation on `RefCell` which allows borrows to be tied to the lifetime of //! the outer object. //! //! # Example //! //! The following example shows a quick example of the basic functionality of //! `LazyCell`. //! //! ``` //! use lazycell::LazyCell; //! //! let lazycell = LazyCell::new(); //! //! assert_eq!(lazycell.borrow(), None); //! assert!(!lazycell.filled()); //! lazycell.fill(1).ok(); //! assert!(lazycell.filled()); //! assert_eq!(lazycell.borrow(), Some(&1)); //! assert_eq!(lazycell.into_inner(), Some(1)); //! ``` //! //! `AtomicLazyCell` is a variant that uses an atomic variable to manage //! coordination in a thread-safe fashion. The limitation of an `AtomicLazyCell` //! is that after it is initialized, it can't be modified.
use std::cell::UnsafeCell; use std::mem; use std::sync::atomic::{AtomicUsize, Ordering};
/// A lazily filled `Cell`, with mutable contents. /// /// A `LazyCell` is completely frozen once filled, **unless** you have `&mut` /// access to it, in which case `LazyCell::borrow_mut` may be used to mutate the /// contents. #[derive(Debug)] pubstruct LazyCell<T> {
inner: UnsafeCell<Option<T>>,
}
/// Put a value into this cell. /// /// This function will return `Err(value)` if the cell is already full. pubfn fill(&self, value: T) -> Result<(), T> { let slot = unsafe { &*self.inner.get() }; if slot.is_some() { return Err(value);
} let slot = unsafe { &mut *self.inner.get() };
*slot = Some(value);
Ok(())
}
/// Put a value into this cell. /// /// Note that this function is infallible but requires `&mut self`. By /// requiring `&mut self` we're guaranteed that no active borrows to this /// cell can exist so we can always fill in the value. This may not always /// be usable, however, as `&mut self` may not be possible to borrow. /// /// # Return value /// /// This function returns the previous value, if any. pubfn replace(&mutself, value: T) -> Option<T> {
mem::replace(unsafe { &mut *self.inner.get() }, Some(value))
}
/// Test whether this cell has been previously filled. pubfn filled(&self) -> bool { self.borrow().is_some()
}
/// Borrows the contents of this lazy cell for the duration of the cell /// itself. /// /// This function will return `Some` if the cell has been previously /// initialized, and `None` if it has not yet been initialized. pubfn borrow(&self) -> Option<&T> { unsafe { &*self.inner.get() }.as_ref()
}
/// Borrows the contents of this lazy cell mutably for the duration of the cell /// itself. /// /// This function will return `Some` if the cell has been previously /// initialized, and `None` if it has not yet been initialized. pubfn borrow_mut(&mutself) -> Option<&mutT> { unsafe { &mut *self.inner.get() }.as_mut()
}
/// Borrows the contents of this lazy cell for the duration of the cell /// itself. /// /// If the cell has not yet been filled, the cell is first filled using the /// function provided. /// /// # Panics /// /// Panics if the cell becomes filled as a side effect of `f`. pubfn borrow_with<F: FnOnce() -> T>(&self, f: F) -> &T { iflet Some(value) = self.borrow() { return value;
} let value = f(); ifself.fill(value).is_err() {
panic!("borrow_with: cell was filled by closure")
} self.borrow().unwrap()
}
/// Borrows the contents of this `LazyCell` mutably for the duration of the /// cell itself. /// /// If the cell has not yet been filled, the cell is first filled using the /// function provided. /// /// # Panics /// /// Panics if the cell becomes filled as a side effect of `f`. pubfn borrow_mut_with<F: FnOnce() -> T>(&mutself, f: F) -> &'color:red'>mut T { if !self.filled() { let value = f(); ifself.fill(value).is_err() {
panic!("borrow_mut_with: cell was filled by closure")
}
}
self.borrow_mut().unwrap()
}
/// Same as `borrow_with`, but allows the initializing function to fail. /// /// # Panics /// /// Panics if the cell becomes filled as a side effect of `f`. pubfn try_borrow_with<E, F>(&self, f: F) -> Result<&T, E> where F: FnOnce() -> Result<T, E>
{ iflet Some(value) = self.borrow() { return Ok(value);
} let value = f()?; ifself.fill(value).is_err() {
panic!("try_borrow_with: cell was filled by closure")
}
Ok(self.borrow().unwrap())
}
/// Same as `borrow_mut_with`, but allows the initializing function to fail. /// /// # Panics /// /// Panics if the cell becomes filled as a side effect of `f`. pubfn try_borrow_mut_with<E, F>(&mutself, f: F) -> Result<&='color:red'>mut T, E> where F: FnOnce() -> Result<T, E>
{ ifself.filled() { return Ok(self.borrow_mut().unwrap());
} let value = f()?; ifself.fill(value).is_err() {
panic!("try_borrow_mut_with: cell was filled by closure")
}
Ok(self.borrow_mut().unwrap())
}
/// Consumes this `LazyCell`, returning the underlying value. pubfn into_inner(self) -> Option<T> { // Rust 1.25 changed UnsafeCell::into_inner() from unsafe to safe // function. This unsafe can be removed when supporting Rust older than // 1.25 is not needed. #[allow(unused_unsafe)] unsafe { self.inner.into_inner() }
}
}
impl<T: Copy> LazyCell<T> { /// Returns a copy of the contents of the lazy cell. /// /// This function will return `Some` if the cell has been previously initialized, /// and `None` if it has not yet been initialized. pubfn get(&self) -> Option<T> { unsafe { *self.inner.get() }
}
}
impl <T: Clone> Clone for LazyCell<T> { /// Create a clone of this `LazyCell` /// /// If self has not been initialized, returns an uninitialized `LazyCell` /// otherwise returns a `LazyCell` already initialized with a clone of the /// contents of self. fn clone(&self) -> LazyCell<T> {
LazyCell { inner: UnsafeCell::new(self.borrow().map(Clone::clone) ) }
}
}
/// Put a value into this cell. /// /// This function will return `Err(value)` if the cell is already full. pubfn fill(&self, t: T) -> Result<(), T> { if NONE != self.state.compare_and_swap(NONE, LOCK, Ordering::Acquire) { return Err(t);
}
unsafe { *self.inner.get() = Some(t) };
if LOCK != self.state.compare_and_swap(LOCK, SOME, Ordering::Release) {
panic!("unable to release lock");
}
Ok(())
}
/// Put a value into this cell. /// /// Note that this function is infallible but requires `&mut self`. By /// requiring `&mut self` we're guaranteed that no active borrows to this /// cell can exist so we can always fill in the value. This may not always /// be usable, however, as `&mut self` may not be possible to borrow. /// /// # Return value /// /// This function returns the previous value, if any. pubfn replace(&mutself, value: T) -> Option<T> { match mem::replace(self.state.get_mut(), SOME) {
NONE | SOME => {}
_ => panic!("cell in inconsistent state"),
}
mem::replace(unsafe { &mut *self.inner.get() }, Some(value))
}
/// Test whether this cell has been previously filled. pubfn filled(&self) -> bool { self.state.load(Ordering::Acquire) == SOME
}
/// Borrows the contents of this lazy cell for the duration of the cell /// itself. /// /// This function will return `Some` if the cell has been previously /// initialized, and `None` if it has not yet been initialized. pubfn borrow(&self) -> Option<&T> { matchself.state.load(Ordering::Acquire) {
SOME => unsafe { &*self.inner.get() }.as_ref(),
_ => None,
}
}
/// Consumes this `LazyCell`, returning the underlying value. pubfn into_inner(self) -> Option<T> { // Rust 1.25 changed UnsafeCell::into_inner() from unsafe to safe // function. This unsafe can be removed when supporting Rust older than // 1.25 is not needed. #[allow(unused_unsafe)] unsafe { self.inner.into_inner() }
}
}
impl<T: Copy> AtomicLazyCell<T> { /// Returns a copy of the contents of the lazy cell. /// /// This function will return `Some` if the cell has been previously initialized, /// and `None` if it has not yet been initialized. pubfn get(&self) -> Option<T> { matchself.state.load(Ordering::Acquire) {
SOME => unsafe { *self.inner.get() },
_ => None,
}
}
}
impl<T: Clone> Clone for AtomicLazyCell<T> { /// Create a clone of this `AtomicLazyCell` /// /// If self has not been initialized, returns an uninitialized `AtomicLazyCell` /// otherwise returns an `AtomicLazyCell` already initialized with a clone of the /// contents of self. fn clone(&self) -> AtomicLazyCell<T> { self.borrow().map_or( Self::NONE,
|v| AtomicLazyCell {
inner: UnsafeCell::new(Some(v.clone())),
state: AtomicUsize::new(SOME),
}
)
}
}
unsafeimpl<T: Sync + Send> Sync for AtomicLazyCell<T> {}
unsafeimpl<T: Send> Send for AtomicLazyCell<T> {}
#[cfg(test)] mod tests { usesuper::{AtomicLazyCell, LazyCell};
#[test] fn test_borrow_from_empty() { let lazycell: LazyCell<usize> = LazyCell::new();
let value = lazycell.borrow();
assert_eq!(value, None);
let value = lazycell.get();
assert_eq!(value, None);
}
#[test] fn test_fill_and_borrow() { let lazycell = LazyCell::new();
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.