This crate dynvec
provides the DynVec
type that acts like a vector to store any datatype.
By default, the DynVec
uses a system of chunks that are allocated on the heap when needed but this can be changed using the RawDynVec
structure along with a Region
.
At the moment, three types of regions are implemented.
* Block
: A fixed-size block of memory
* Chunks
: A region that allocates Block
s (chunks) when one becomes full.
* Global
: A simple region that maps to rust's allocator (each item is allocated anywhere on the heap memory).
Using the default DynVec
:
```rust
use dynvec::DynVec;
// Create an empty DynVec
let mut my_vec = DynVec::new();
// By default, each chunk will be allocated with a size of 1024 bytes.
// This can be changed using the DynVec::with_chunk_size
function.
// Items can be inserted into the vector let handleu8 = myvec.insert(142u8); let handlestr = myvec.insert("Hello, world!"); let handlevec = myvec.insert(vec![1, 2, 3]);
// They can be accessed normally using indexing operations myvec[handlevec].push(4); asserteq!(myvec[handleu8], 142); asserteq!(myvec[handlestr], "Hello, world!"); asserteq!(&myvec[handle_vec][..], &[1, 2, 3, 4][..]);
// Removing them is just as easy let vector = myvec.remove(handlevec).unwrap(); assert_eq!(&vector[..], &[1, 2, 3, 4][..]);
// The vector can be cleared (everything gets properly dropped) my_vec.clear(); ```
Using another type of region: ```rust use dynvec::RawDynVec; use dynvec::region::global::Global;
// This is basically a vector of boxes. let mut myvec = RawDynVec::withregion(Global::default()); myvec.insert(42); myvec.insert("Hello"); ```
You might want to avoid having typed handles everywhere. You can use raw handles: ```rust use dynvec::DynVec;
let mut my_vec = DynVec::new(); let mut handles = Vec::new();
handles.push(myvec.insert("ABC").raw()); handles.push(myvec.insert(64u8).raw()); handles.push(my_vec.insert(String::from("BDE")).raw());
for handle in handles { // This returns nothing // We do not know the type of the item anymore // The item gets properly dropped though myvec.removeraw(handle).unwrap(); } ```
I used DynVec
as a name even though it is not at all a vector because it makes it easy to understand what it does.