9 unstable releases (3 breaking)
new 0.4.1 | Jan 16, 2025 |
---|---|
0.4.0 | Jan 16, 2025 |
0.3.0 | Jan 14, 2025 |
0.2.0 | Dec 15, 2024 |
0.1.4 | Nov 14, 2024 |
#301 in Memory management
95 downloads per month
19KB
251 lines
vec_mem_heap
A reference counting Vec, allowing you to store data and manually track how many 'references' you have to each index. Documentation was done hastily, expect stuff like use examples to be added as I feel like it.
lib.rs
:
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 which are caused by external factors are handled, canceling the request and returning an [AccessError]. Errors which are caused by internal factors, such as a failure in the allocation process, will be automatically repaired. If the repair fails, we will panic!().
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 == Index(0)
{
let data2 = storage.push(72); // data2 == Index(1)
// Now that a second reference to the data in 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) still has one reference (data1).
dbg!( storage.data( Index(0) ) );
// Err( AccessError::FreeMemory(Index(1)) ) -> The data at Index(1) was freed when its last reference was removed.
dbg!( storage.data( Index(1) ) );
}
Dependencies
~0.3–0.9MB
~20K SLoC