Crate castbox

Crate castbox 

Source
Expand description

ยง๐Ÿ“ฆ AnyRef โ€” Runtime-Typed Reference-Counted Smart Pointer for Rust

AnyRef is a custom smart pointer similar to Arc, designed for storing dynamically typed (dyn Any) values with strong and weak reference support, runtime downcasting, and optional thread-safe interior mutability.
It is ideal for scenarios where type erasure and runtime polymorphism are needed without exposing generic interfaces.


ยงโœจ Features

  • โœ… Runtime type storage via dyn Any
  • ๐Ÿ” Strong and weak reference counting
  • ๐Ÿ” Optional thread-safe mutability (with internal locking)
  • ๐Ÿ” Safe runtime downcasting (try_downcast, try_downcast_mut)
  • ๐Ÿšซ No generics in the pointer interface
  • ๐Ÿง  Suitable for runtime-managed object graphs

ยงโš™๏ธ Example Usage

ยงBasic Allocation and Access

use castbox::AnyRef;

let a = AnyRef::new(42i32);
assert_eq!(a.as_ref::<i32>(), 42);

ยงRuntime Downcasting

use castbox::AnyRef;

let a = AnyRef::new("hello".to_string());
if let Some(s) = a.try_downcast_ref::<String>() {
    assert_eq!(s, "hello");
}

ยงCloning and Reference Counting

use castbox::AnyRef;

let a = AnyRef::new(vec![1, 2, 3]);
let b = a.clone();

assert_eq!(AnyRef::strong_count(&a), 2);

ยงWeak Reference

use castbox::AnyRef;

let a = AnyRef::new("temporary".to_string());
let w = a.downgrade();

assert!(w.upgrade().is_some());
drop(a);
assert!(w.upgrade().is_none());

ยงThread-Safe Mode

use castbox::AnyRef;
use crossync::sync::Barrier;
use std::thread;

let x = AnyRef::new(123i32);
let mut handles = vec![];
let barrier = AnyRef::new(Barrier::with_capacity(10, 0));

for i in 0..10 {
    let x_clone = x.clone();
    let barrier_clone = barrier.clone();
    handles.push(thread::spawn(move || {
        barrier_clone.try_downcast_ref::<Barrier>().unwrap().wait();
        let val = x_clone.as_ref::<i32>();
        assert_eq!(*val, 123);
    }));
}

for h in handles {
    h.join().unwrap();
}

assert_eq!(AnyRef::strong_count(&x), 1);
assert_eq!(AnyRef::weak_count(&x), 0);

ยง๐Ÿ“ฆ Installation

Install AnyRef from crates.io Open your Cargo.toml and add:

[dependencies]
castbox = "0.1.1" # or the latest version available 

ยง๐Ÿ“„ License

Apache-2.0


Modulesยง

utils

Structsยง

AnyRef
Arw
WatchGuardMut
used as wrapper for a pointer to a reference
WatchGuardRef
used as wrapper for a pointer to a reference
WeakAnyRef
WeakArw