Crate vec_mem_heap

Source
Expand description

Fun little virtual memory allocator.

This is a learning experience for me and should be used with a mountain of salt. At some point I need to rename it, but I don’t have a good one yet.

This crate is intended for the creation of graphs and similar data structures, with a focus on storing data contiguously in memory while allowing it to have multiple owners. Internally the data is stored in a Vec.

This crate does not yet support Weak or Atomic references to data, that’s on the todo list (maybe).

Errors will cancel the request and returning an AccessError.

Indexing is performed internally using usize, but you can use any type which implements Indexable.

§Example

use vec_mem_heap::prelude::*;
 
fn main() {
 
    let mut storage : NodeField<u32> = NodeField::new();
 
    // When you push data into the structure, it returns the index that data was stored at and sets the reference count to 1.
    let data1 = storage.push(15); // data1 == 0

    {
        let data2 = storage.push(72); // data2 == 1
 
        // Now that a second reference to the data at index 0 exists, we have to manually add to the reference count.
        let data3 = data1;
        storage.add_ref(data3);
     
        // data2 and data3 are about to go out of scope, so we have to manually remove their references.
        // returns Ok( Some(72) ) -> The data at index 1 only had one reference, so it was freed.
        storage.remove_ref(data2);
 
        // returns Ok( None ) -> The data at index 0 had two references, now one.
        storage.remove_ref(data3); 
    }
 
    // returns Ok( &15 ) -> The data at index 0 (data1) still has one reference.
    dbg!( storage.data( data1 ) );
    // Err( AccessError::FreeMemory(1) ) -> The data at index 1 was freed when its last reference was removed.
    dbg!( storage.data( 1 ) );
 
}

Modules§

prelude
Common types and traits exported for convenience.

Structs§

NodeField
Used to allocate space on the heap, read from that space, and write to it.

Enums§

AccessError
Errors which may occur while accessing and modifying memory.

Traits§

Indexable
A trait which allows you to customize how indexes are stored on your side of the api