2 unstable releases

0.2.0 Jun 5, 2020
0.1.0 Feb 2, 2020

#1026 in Concurrency

MIT license

38KB
657 lines

refptr

Latest Version Documentation Build Status

Macros, attributes, and traits for invasively reference-counted structs in Rust. See the documentation for more details.


lib.rs:

Macros, attributes, and traits for invasively reference-counted structs in Rust.

This crate is centered around manipulating invasively reference counted structs. These structs are declared using the #[refcounted] attribute, constructed with the make_refptr macro, and have their lifetimes managed using the RefPtr and WeakPtr smart pointer types.

Declaring a refcounted struct

The #[refcounted] attribute can be applied to a struct declaration to mark it as refcounted. Refcounted structs are always allocated on the heap, and are constructed using the make_refptr helper macro.

Example

#[refcounted(local)]
struct HeapInteger {
    value: Cell<i32>,
}

let orig = make_refptr!(HeapInteger { value: Cell::new(10) });
let copy = orig.clone();
orig.value.set(20);
assert_eq!(copy.value.get(), 20);

Allocating

Structs declared with #[refcounted] are constructed on the heap using the make_refptr! macro. This macro accepts struct literal syntax, but constructs the value onto the heap.

This is required in order to ensure that the type always lives on the heap for invasive reference counting.

Example

let ptr = make_refptr!(HeapPair { t: 10, u: 20 });
assert_eq!(ptr.t, 10);
assert_eq!(ptr.u, 20);

Finalization and Drop

Types annotated with #[refcounted] cannot manually implement Drop, as it would allow recovering a RefPtr<Self> while the object is being dropped, leading to a use-after-free.

If a finalization method is needed, the #[refcounted(finalize)] attribute provides support for custom finalization. If finalization is enabled, a fn finalize(&self) method is called before dropping any fields.

It is possible for code to acquire a new strong reference during the finalize method, which may cause the struct to not be dropped after it returns. Because of this, finalize may be called on the same struct multiple times over it's lifetime.

Configuration

#[refcounted(atomic)] and #[refcounted(local)]

Select between atomic reference counting, like Arc, or thread local reference counting, like Rc. Atomically refcounted types may be shared between threads, so long as all fields are also sharable.

The atomicity of the refcount must be specified.

Example

#[refcounted(atomic)]
struct HeapInt { i: i32 }

let here = make_refptr!(HeapInt { i: 10 });
let thread = thread::spawn(move || here.i);
assert_eq!(thread.join().unwrap(), 10);

#[refcounted(weak)]

Adds support for weak reference counts and the WeakPtr smart pointer type. This annotation may be combined with other annotations.

Example

#[refcounted(atomic, weak)]
struct HeapInt { i: i32 }

let here = make_refptr!(HeapInt { i: 10 });
let weak = WeakPtr::new(&*here);
assert_eq!(weak.upgrade().unwrap().i, 10);
drop(here);
assert!(weak.upgrade().is_none());

#[refcounted(finalize)]

Calls a fn finalize(&self) method on the struct before attempting to destroy it. See the "Finalization" section for more details. This annotation may be combined with other annotations.

Structs which support being referenced using RefPtr are annotated with the #[refcounted(...)] attribute. This attribute generates the necessary unsafe code, extra members, and trait implementations required.

#[refcounted(atomic, finalize)]
struct FinalizeExample {}

static FINALIZED: AtomicBool = AtomicBool::new(false);
impl FinalizeExample {
    fn finalize(&self) {
        FINALIZED.store(true, SeqCst);
    }
}

let orig = make_refptr!(FinalizeExample {});
assert_eq!(FINALIZED.load(SeqCst), false);
let copy = orig.clone();
assert_eq!(FINALIZED.load(SeqCst), false);
drop(orig);
assert_eq!(FINALIZED.load(SeqCst), false);
drop(copy);
assert_eq!(FINALIZED.load(SeqCst), true);

Trait Objects

#[refcounted] can also be used for managing the lifecycles of trait objects, by including the Refcounted trait in your trait object's hierarchy. The Rc associated type will need to be specified in order to maintain object safety.

The refcnt module contains the specific reference count types used by this crate.

Example

trait MyTrait : Refcounted<Rc = refcnt::AtomicWeak> {
    fn my_trait_method(&self) -> i32;
}

#[refcounted(atomic, weak)]
struct MyStruct { i: i32 }

impl MyTrait for MyStruct {
    fn my_trait_method(&self) -> i32 { self.i }
}

fn takes_trait_object(obj: &dyn MyTrait) -> i32 {
    let strong_ref: RefPtr<dyn MyTrait> = RefPtr::new(obj);
    strong_ref.my_trait_method()
}

let concrete = make_refptr!(MyStruct { i: 10 });
let i = takes_trait_object(&*concrete);
assert_eq!(i, 10);

Dependencies

~1.5MB
~37K SLoC