pub struct SynchronizedOptional<T> { /* private fields */ }std only.Expand description
Basically a RwLock<Option<Arc<T>>> - the benefits here being:
- This structure is
Syncin that it can be shared between threads - This structure can be lazily initialized, and then reset back to
None, and back again - This structure provides multiple access to a single shared instance, like a
Stringso we’re not cloning it a bunch of times unnecessarily. (Arc<T>)
The Arc<T> bit is because you can’t return a &T out of a RwLock<T> the way you can
from a std::sync::OnceLock<T>. The only reason this isn’t a OnceLock is because I wanted
a swap method that was atomic, rather than relying on a std::sync::OnceLock<T>::take
followed by a std::sync::OnceLock<T>::set, which allows a very slight race condition.
Implementations§
Source§impl<T> SynchronizedOptional<T>
impl<T> SynchronizedOptional<T>
Returns a new struct initialized with the provided already shared value
Sourcepub fn get(&self) -> Option<Arc<T>>
pub fn get(&self) -> Option<Arc<T>>
If this struct has been initialized, returns a copy of the data, otherwise None
Sourcepub fn set(&self, value: Option<T>) -> Result<(), Option<T>>
pub fn set(&self, value: Option<T>) -> Result<(), Option<T>>
Sets the value to be the specified value, throwing away any value that was stored previously Returns the value provided as a parameter if it was unable to replace the value.
Sets the value to be the specified value, throwing away any value that was stored previously Returns the value provided as a parameter if it was unable to replace the value.
Sourcepub fn take(&self) -> Option<Arc<T>>
pub fn take(&self) -> Option<Arc<T>>
Takes the value out of this structure, leaving None in it’s place.
Sourcepub fn swap(&self, value: T) -> Result<Option<Arc<T>>, T>
pub fn swap(&self, value: T) -> Result<Option<Arc<T>>, T>
Swaps the value contained within this structure (if any) with the value provided. Upon
success, returns the old value (which is possibly None).
Will only fail if the lock has been poisoned, at which point it returns the provided
value back to you.
Swaps the value contained within this structure (if any) with the already shared value
provided. Upon success, returns the old value (which is possibly None).
Will only fail if the lock has been poisoned, at which point it returns the provided
value back to you.