#memory #memory-map #storage #map #fixed-size #no-std

no-std memory_storage

A memory storage comparable to a Vec where removing items doesn't shift all the items after the removed item to the left and doesn't invalidate their IDs. It allows you to remove items with high speed and access items via an ID that was returned after adding them.

7 releases

0.9.30 Jun 30, 2023
0.9.23 Jun 30, 2023

#255 in Memory management

Download history 14/week @ 2024-07-30 2/week @ 2024-09-17 22/week @ 2024-09-24

70 downloads per month

Custom license

21KB
393 lines

Memory Storage

A memory storage comparable to a Vec where removing items doesn't shift all the items after the removed item to the left and doesn't invalidate their IDs. It allows you to remove items with high speed and access items via an ID that was returned after adding them.

When to use?

  • When needing to remove/add items as fast as possible
  • When needing to access the items with high speed
  • When you don't want to generate your own ID for accessing items
  • When you don't have access to an allocator

Example with array

use memory_storage::new_with_array;

let mut memory_storage = new_with_array::<i32, 3>();

let id_of_one = memory_storage.insert(1)
    .expect("Something went wrong!");
let id_of_two = memory_storage.insert(2)
    .expect("Something went wrong!");
let id_of_three = memory_storage.insert(3)
    .expect("Something went wrong!");

// We are at max capacity!
assert!(memory_storage.insert(4).is_err());

let two = memory_storage.remove(id_of_two);
let id_of_four = memory_storage.insert(4)
    .expect("Something went wrong!");
let three = *memory_storage.get(id_of_three)
    .expect("Something went wrong!");

assert_eq!(three, 3);

Example with vec (only with the 'alloc' feature)

// Only with 'alloc' feature on!
use memory_storage::vec::new_with_fixed_capacity_vec;
use memory_storage::vec::new_with_vec;

// Create a MemoryStorage using a vec with a fixed size of 3.
let fixed_size_vec_memory_storage = new_with_fixed_capacity_vec::<()>(3);

// MemoryStorage using a vec allowing to allocate more space.
// Here we create an instance with the size of 1 (which can be increased).
let mut vec_memory_storage = new_with_vec(1);

let id_of_one = vec_memory_storage.push(1);
let id_of_two = vec_memory_storage.push(2);
let id_of_three = vec_memory_storage.push(3);

let three = *vec_memory_storage.get(id_of_three)
     .expect("Something went wrong!");

assert_eq!(three, 3);

No runtime deps

Features