diff options
| author | John Kåre Alsaker <john.kare.alsaker@gmail.com> | 2018-04-01 12:14:19 +0200 |
|---|---|---|
| committer | John Kåre Alsaker <john.kare.alsaker@gmail.com> | 2018-04-10 14:39:33 +0200 |
| commit | 26f16e85ffcc3ebcaf12029865dee257760901b5 (patch) | |
| tree | 9a747e3a88f0266e284dedaffe8d0693c5d8c44c /src/librustc_data_structures | |
| parent | 60d0cbe532eba39dba75d84b1eb98abf7cd12a48 (diff) | |
| download | rust-26f16e85ffcc3ebcaf12029865dee257760901b5.tar.gz rust-26f16e85ffcc3ebcaf12029865dee257760901b5.zip | |
Add a Once type for values which are only written once
Diffstat (limited to 'src/librustc_data_structures')
| -rw-r--r-- | src/librustc_data_structures/sync.rs | 129 |
1 files changed, 129 insertions, 0 deletions
diff --git a/src/librustc_data_structures/sync.rs b/src/librustc_data_structures/sync.rs index 19039b9b0b0..3b7d6efbdae 100644 --- a/src/librustc_data_structures/sync.rs +++ b/src/librustc_data_structures/sync.rs @@ -32,6 +32,7 @@ use std::collections::HashMap; use std::hash::{Hash, BuildHasher}; use std::cmp::Ordering; +use std::marker::PhantomData; use std::fmt::Debug; use std::fmt::Formatter; use std::fmt; @@ -241,6 +242,134 @@ impl<K: Eq + Hash, V: Eq, S: BuildHasher> HashMapExt<K, V> for HashMap<K, V, S> } } +/// A type whose inner value can be written once and then will stay read-only +// This contains a PhantomData<T> since this type conceptually owns a T outside the Mutex once +// initialized. This ensures that Once<T> is Sync only if T is. If we did not have PhantomData<T> +// we could send a &Once<Cell<bool>> to multiple threads and call `get` on it to get access +// to &Cell<bool> on those threads. +pub struct Once<T>(Lock<Option<T>>, PhantomData<T>); + +impl<T> Once<T> { + /// Creates an Once value which is uninitialized + #[inline(always)] + pub fn new() -> Self { + Once(Lock::new(None), PhantomData) + } + + /// Consumes the value and returns Some(T) if it was initialized + #[inline(always)] + pub fn into_inner(self) -> Option<T> { + self.0.into_inner() + } + + /// Tries to initialize the inner value to `value`. + /// Returns `None` if the inner value was uninitialized and `value` was consumed setting it + /// otherwise if the inner value was already set it returns `value` back to the caller + #[inline] + pub fn try_set(&self, value: T) -> Option<T> { + let mut lock = self.0.lock(); + if lock.is_some() { + return Some(value); + } + *lock = Some(value); + None + } + + /// Tries to initialize the inner value to `value`. + /// Returns `None` if the inner value was uninitialized and `value` was consumed setting it + /// otherwise if the inner value was already set it asserts that `value` is equal to the inner + /// value and then returns `value` back to the caller + #[inline] + pub fn try_set_same(&self, value: T) -> Option<T> where T: Eq { + let mut lock = self.0.lock(); + if let Some(ref inner) = *lock { + assert!(*inner == value); + return Some(value); + } + *lock = Some(value); + None + } + + /// Tries to initialize the inner value to `value` and panics if it was already initialized + #[inline] + pub fn set(&self, value: T) { + assert!(self.try_set(value).is_none()); + } + + /// Tries to initialize the inner value by calling the closure while ensuring that no-one else + /// can access the value in the mean time by holding a lock for the duration of the closure. + /// If the value was already initialized the closure is not called and `false` is returned, + /// otherwise if the value from the closure initializes the inner value, `true` is returned + #[inline] + pub fn init_locking<F: FnOnce() -> T>(&self, f: F) -> bool { + let mut lock = self.0.lock(); + if lock.is_some() { + return false; + } + *lock = Some(f()); + true + } + + /// Tries to initialize the inner value by calling the closure without ensuring that no-one + /// else can access it. This mean when this is called from multiple threads, multiple + /// closures may concurrently be computing a value which the inner value should take. + /// Only one of these closures are used to actually initialize the value. + /// If some other closure already set the value, + /// we return the value our closure computed wrapped in a `Option`. + /// If our closure set the value, `None` is returned. + /// If the value is already initialized, the closure is not called and `None` is returned. + #[inline] + pub fn init_nonlocking<F: FnOnce() -> T>(&self, f: F) -> Option<T> { + if self.0.lock().is_some() { + None + } else { + self.try_set(f()) + } + } + + /// Tries to initialize the inner value by calling the closure without ensuring that no-one + /// else can access it. This mean when this is called from multiple threads, multiple + /// closures may concurrently be computing a value which the inner value should take. + /// Only one of these closures are used to actually initialize the value. + /// If some other closure already set the value, we assert that it our closure computed + /// a value equal to the value aready set and then + /// we return the value our closure computed wrapped in a `Option`. + /// If our closure set the value, `None` is returned. + /// If the value is already initialized, the closure is not called and `None` is returned. + #[inline] + pub fn init_nonlocking_same<F: FnOnce() -> T>(&self, f: F) -> Option<T> where T: Eq { + if self.0.lock().is_some() { + None + } else { + self.try_set_same(f()) + } + } + + /// Tries to get a reference to the inner value, returns `None` if it is not yet initialized + #[inline(always)] + pub fn try_get(&self) -> Option<&T> { + let lock = &*self.0.lock(); + if let Some(ref inner) = *lock { + // This is safe since we won't mutate the inner value + unsafe { Some(&*(inner as *const T)) } + } else { + None + } + } + + /// Gets reference to the inner value, panics if it is not yet initialized + #[inline(always)] + pub fn get(&self) -> &T { + self.try_get().expect("value was not set") + } + + /// Gets reference to the inner value, panics if it is not yet initialized + #[inline(always)] + pub fn borrow(&self) -> &T { + self.get() + } +} + impl<T: Copy + Debug> Debug for LockCell<T> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { f.debug_struct("LockCell") |
