Crate value_pool

Source
Expand description

This libraries allows easy use of self-referential structs by storing them in one place, the ValuePool<T> and referencing the stored values with UntypedValueRef or ValueRef<T>.

§Showcase

use value_pool::{ValueRef, ValuePool,UntypedValueRef};
let mut pool: ValuePool<u32> = ValuePool::new();
let ref_to_first: ValueRef<u32> = pool.push(12);

// You can convert ValueRef<T> to UntypedValueRef and the other way round.
// UntypedValueRef is useful if the type information of ValueRef<T> gets in your way
let untyped_ref_to_first: UntypedValueRef = ref_to_first.into();

// original type information gets lost
let wrongly_typed_ref_to_first: ValueRef<u8> = untyped_ref_to_first.into();  
// Notice the wrong type of `wrongly_typed_ref_to_first`
// Following line would result in compile time error:
//  `Trait From<ValueRef<u8>> is not implemented for ValueRef<u32>`
//pool.get(wrongly_typed_ref_to_first); // Error here

assert_eq!(pool.get(ref_to_first), Some(&12));
assert_eq!(pool.element_count(), 1);

// You can take a value
assert_eq!(pool.take(ref_to_first), Some(12));
assert_eq!(pool.element_count(), 0);

let mut ref_to_13 = pool.push(13);
let mut ref_to_14 = pool.push(14);
let copy_ref_to_14 = ref_to_14; // ValueRef implements Copy

// pool.swap is marked unsafe cause it causes all references to 14 (and 13) to point to the
// wrong value, except for the returned refs
unsafe{(ref_to_13,ref_to_14) = pool.swap(ref_to_13, ref_to_14).unwrap();}
assert_eq!(ref_to_13, copy_ref_to_14);

// unsafe cause now ref_to_13 will be invalid (Actually: all refs >= ref_to_14)
unsafe{pool.remove_full(ref_to_14);}
assert!(ref_to_13 > ref_to_14);
assert_eq!(pool.find(&13).unwrap(), ref_to_14);
assert_eq!(pool.find(&13).unwrap(), ValueRef::new(0));

§Features

  • unsafe - Library will use unsafe code to (potentially) improve speed. This could result in UB if implemented faulty even though it shouldn’t and the behavior of your code should be unchanged.

Modules§

smart_value_pool
This module implements SmartValuePool<T> which can automatically call a function if a method call changes it state from empty to one element or vice versa.

Structs§

UntypedValueRef
Struct that stores a location of an item in ValuePool<T>. It implements Copy.
ValuePool
A ValuePool<T> allows referencing data stored within without a lifetime bound.
It works by returning an Option<T>. It’s your responsibility to handel Nones.
ValueRef
Struct that stores a location of an item in ValuePool<T> as well as the type. It implements Copy.