[][src]Crate unique

Allocators which create one unique, shared pointer per distinct object. Useful for applications with highly-redundant data structures such as compilers or automatic theorem provers.

If t1 == t2 (as determined by the allocator), then Id::new(t1) is pointer-equal to Id::new(t2). This property reduces memory use, reduces allocator hits, and allows for short-circuiting operations such as Eq and Hash by using the pointer rather than the data.

Occasionally you may wish to "garbage collect" unused objects. This can be achieved with Allocator::delete_unused.

Example

use unique::{Allocated, Id, make_allocator};
use unique::allocators::HashAllocator;

#[derive(PartialEq, Eq, Hash)]
enum Expr {
    Const(i32),
    Add(Id<Expr>, Id<Expr>),
}
make_allocator!(Expr, EXPR_ALLOC, HashAllocator);

#[test]
fn example() {
    use Expr::*;

    // Equivalent ways of allocating a `2` object.
    let two_x = Expr::allocator().allocate(Const(2));
    let two_y = EXPR_ALLOC.allocate(Const(2));
    let two_z = Id::new(Const(2));
    assert_eq!(*two_x, *two_y, *two_z, Const(2));
    assert_eq!(two_x, two_y, two_z);

    // A distinct object, 2 + 2.
    let four = Id::new(Add(two_x.clone(), two_y.clone()));
    assert_ne!(two_x, four);

    // Note only two allocations.
    assert_eq!(EXPR_ALLOC.allocations(), 2);

    std::mem::drop(four);

    // Still two allocations.
    assert_eq!(EXPR_ALLOC.allocations(), 2);
    EXPR_ALLOC.delete_unused();
    // Now four is no more.
    assert_eq!(EXPR_ALLOC.allocations(), 1);
}

Modules

allocators

Possible allocators to use

Macros

make_allocator

make_allocator!(Type, NAME, Allocator)

Structs

Id

A unique, shared pointer

Traits

Allocated

A type which has some allocator

Allocator

Allocate shared unique pointers