any_handle

Crates.ioany_handle
lib.rsany_handle
version0.1.4
sourcesrc
created_at2023-05-11 20:01:49.056434
updated_at2023-05-11 22:09:15.653112
descriptionA thread-safe, type-safe smart pointer that can share, store and downcast a `dyn Any`.
homepagehttps://github.com/emctague/any_handle
repositoryhttps://github.com/emctague/any_handle
max_upload_size
id862431
size9,299
Ethan McTague (emctague)

documentation

README

any_handle

Crates.io docs.rs GitHub Workflow Status Crates.io

any_handle provides a reference-counting smart pointer type, AnyHandle<T>, which can store a value of a type T. The special AnyHandle<dyn Any> allows for downcasting to any other AnyHandle<T: Any> type.

Internally, an AnyHandle is an Arc<RwLock<Box<dyn Any>>>, and matches the reference-counting behaviour of Arc as well as the many-readers-or-one-writer thread safety model of RwLock.

use any_handle::{AnyHandle, Any};
struct SomeStruct (i32);

fn main() -> 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(())
}
Commit count: 10

cargo fmt