shelves/
lib.rs

1//! This is a small utility library for storing values of and
2//! reference them using a unique typed index, `Ref<T>`,
3//! which is a simple typed wrapper around `usize`.
4//!
5//! Any data structure can be used behind the shelf as long as it provides
6//! a way to store and fetch values by `usize` through the implementation of the `Storage` trait.
7//! This library provides a `Storage` implementation for `Vec`, `BTreeMap` and `HashMap`.
8//! In addition, a `Storage` implementation is provided for the `slab::Slab` type by enabling
9//! the `slab-storage` feature.
10use derivative::Derivative;
11
12pub mod btree_const_dictionary;
13pub mod btree_dictionary;
14pub mod hash_const_dictionary;
15pub mod hash_dictionary;
16mod map;
17pub mod shelf;
18pub mod storage;
19
20pub use btree_dictionary::BTreeDictionary;
21pub use hash_const_dictionary::HashConstDictionary;
22pub use hash_dictionary::HashDictionary;
23pub use map::Map;
24pub use shelf::Shelf;
25pub use storage::*;
26
27/// Typed reference to a stored value.
28#[derive(Derivative)]
29#[derivative(
30	Clone(bound = ""),
31	Copy(bound = ""),
32	PartialEq(bound = ""),
33	Eq(bound = ""),
34	Hash(bound = ""),
35	PartialOrd(bound = ""),
36	Ord(bound = ""),
37	Debug(bound = "")
38)]
39#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
40pub struct Ref<T>(
41	usize,
42	#[cfg_attr(feature = "serde", serde(skip))] std::marker::PhantomData<T>,
43);
44
45impl<T> Ref<T> {
46	/// Creates a new reference from an index.
47	pub fn new(index: usize) -> Self {
48		Self(index, std::marker::PhantomData)
49	}
50
51	/// Returns the underlying index referencing the value.
52	pub fn index(&self) -> usize {
53		self.0
54	}
55
56	/// Changes the reference type.
57	pub fn cast<U>(self) -> Ref<U> {
58		Ref::new(self.0)
59	}
60}