pub struct AnyHandle<T>(/* private fields */)
where
T: ?Sized;Expand description
A thread-safe shared pointer to a value of any Any type, allowing for downcasting.
Internally, this uses RwLock, allowing for multiple concurrent readers or a single writer.
§Example
use any_handle::{AnyHandle, Any};
struct SomeStruct (i32);
impl SomeStruct {
fn do_things_with(&self) {}
fn do_mut_things_with(&mut self) {}
}
fn demo() -> Option<()> {
// Initialize a handle with an unknown type.
// If you want to pass in a Box<dyn SomeOtherTrait>, instead of a concrete
// type, you will have to use `#![feature(trait_upcasting)]`, unfortunately.
let handle : AnyHandle<dyn Any> = AnyHandle::new(Box::new(SomeStruct(12)));
// Now we can put it in some sort of generic container...
// ...and when we retrieve it later:
let mut handle : AnyHandle<SomeStruct> = handle.downcast().ok()?;
handle.write().do_mut_things_with();
handle.read().do_things_with();
Some(())
}
fn main() { demo().unwrap() }Implementations§
Source§impl AnyHandle<dyn Any>
impl AnyHandle<dyn Any>
Sourcepub fn downcast<Y>(self) -> Result<AnyHandle<Y>, AnyHandle<dyn Any>>where
Y: 'static,
pub fn downcast<Y>(self) -> Result<AnyHandle<Y>, AnyHandle<dyn Any>>where
Y: 'static,
Downcast this handle from dyn Any to a specific type.
If the stored data can be downcast to type Y, succeeds and
returns Ok(the cast AnyHandle).
If the data cannot be downcast, errors and returns Error(self).
You may also downcast using Option<AnyHandle<T>>::from.
Source§impl<T> AnyHandle<T>where
T: ?Sized,
impl<T> AnyHandle<T>where
T: ?Sized,
Sourcepub fn read(&self) -> AnyHandleReadGuard<'_, T>
pub fn read(&self) -> AnyHandleReadGuard<'_, T>
Get a ‘read guard’ that allows for reading from the object. Any number of read guards can exist at a given time, but not at the same time as any write guards, so this may block or result in deadlocks if used improperly.
Sourcepub fn write(&mut self) -> AnyHandleWriteGuard<'_, T>
pub fn write(&mut self) -> AnyHandleWriteGuard<'_, T>
Get a ‘write guard’ that allows for writing to the object. Only one write guard can exist at a given time for an object, and not at the same time as any read guards, so this may block or result in deadlocks if used improperly.
Sourcepub fn reference_count(&self) -> usize
pub fn reference_count(&self) -> usize
Get a count of the number of living references to this object.