paged_collections/key.rs
1//! Keys and how they map to slot indices.
2//!
3//! Every paged-index collection stores at most one key per *slot*, and
4//! [`Key::index`] names the slot. For plain integers the slot is the integer
5//! itself. For generational ids (an index plus a version or generation
6//! counter) the slot is the index part only, so successive generations of the
7//! same id share a slot.
8//!
9//! Collections compare the stored key with `==` on every lookup, so a key whose
10//! slot is held by a different key (for example an older generation) is not
11//! found. Methods that insert document what happens when the slot is held by a
12//! different key.
13//!
14//! # Implementing `Key` for an id type
15//!
16//! ```
17//! use paged_collections::key::Key;
18//!
19//! /// 32-bit entity id: low 24 bits are the index, high 8 bits the generation.
20//! #[derive(Clone, Copy, PartialEq, Eq, Debug)]
21//! struct Entity(u32);
22//!
23//! impl Key for Entity {
24//! fn index(self) -> usize {
25//! (self.0 & 0x00ff_ffff) as usize
26//! }
27//! }
28//!
29//! let a = Entity(5);
30//! let a_next_generation = Entity(5 | 1 << 24);
31//! assert_eq!(a.index(), a_next_generation.index());
32//! assert_ne!(a, a_next_generation);
33//! ```
34
35/// A value that names a slot in a paged collection.
36///
37/// # Contract
38///
39/// - `index` must be a pure function of the key: equal keys have equal
40/// indices, and calling it twice gives the same result.
41/// - `index` must not panic. Collections call it while they rewrite their
42/// index (after removing or sorting), where a panic would leave them
43/// inconsistent.
44/// - Different keys may share an index (generational ids do); the collections
45/// then treat them as competing for one slot.
46/// - Memory use follows the indices in use, not the number of keys, so keys
47/// should map to indices that cluster. A flat page directory allocates
48/// `max_index / PAGE` directory entries; see [`crate::page`].
49///
50/// Breaking the contract cannot cause undefined behaviour, but collections
51/// may then return wrong results or panic.
52pub trait Key: Copy + Eq {
53 /// The slot index of this key.
54 fn index(self) -> usize;
55}
56
57/// A [`Key`] that its slot index and a small *tag* determine, so a direct map
58/// stores only the tag in each slot, not the whole key.
59///
60/// [`PagedDirectMap`](crate::direct_map::PagedDirectMap) keeps
61/// `Option<(K::Tag, V)>` in each slot and rebuilds keys with
62/// [`from_parts`](DirectKey::from_parts). For plain integers the index is the
63/// whole key and the tag is `()`, so a `u32 -> u64` map uses 16-byte slots
64/// instead of 24. A generational id's tag is its generation. A key that its
65/// index does not help to rebuild can use `type Tag = Self`, which stores the
66/// whole key as before.
67///
68/// # Contract
69///
70/// For all keys `a` and `b`:
71///
72/// - `a == b` exactly when `a.index() == b.index()` and `a.tag() == b.tag()`;
73/// - `K::from_parts(a.index(), a.tag()) == a`.
74///
75/// Neither `tag` nor `from_parts` may panic: the map calls `from_parts` only
76/// with the parts of a key it was given, while iterating or removing.
77/// Breaking the contract cannot cause undefined behaviour, but maps may then
78/// return wrong keys or results.
79///
80/// ```
81/// use paged_collections::direct_map::PagedDirectMap;
82/// use paged_collections::key::{DirectKey, Key};
83///
84/// /// 32-bit entity id: low 24 bits are the index, high 8 bits the generation.
85/// #[derive(Clone, Copy, PartialEq, Eq, Debug)]
86/// struct Entity(u32);
87///
88/// impl Key for Entity {
89/// fn index(self) -> usize {
90/// (self.0 & 0x00ff_ffff) as usize
91/// }
92/// }
93///
94/// impl DirectKey for Entity {
95/// type Tag = u8;
96/// fn tag(self) -> u8 {
97/// (self.0 >> 24) as u8
98/// }
99/// fn from_parts(index: usize, tag: u8) -> Self {
100/// Entity(index as u32 | u32::from(tag) << 24)
101/// }
102/// }
103///
104/// let mut map: PagedDirectMap<Entity, &str> = PagedDirectMap::new();
105/// map.insert(Entity(5 | 1 << 24), "second generation");
106/// assert_eq!(map.keys().next(), Some(Entity(5 | 1 << 24)));
107/// assert_eq!(map.get(Entity(5)), None);
108/// ```
109pub trait DirectKey: Key {
110 /// What a slot stores besides the value: the part of the key that the
111 /// slot index does not give.
112 type Tag: Copy + Eq;
113
114 /// The part of this key that its index does not give.
115 fn tag(self) -> Self::Tag;
116
117 /// The key with slot index `index` and tag `tag`.
118 fn from_parts(index: usize, tag: Self::Tag) -> Self;
119}
120
121macro_rules! impl_key_lossless {
122 ($($t:ty),* $(,)?) => {$(
123 impl Key for $t {
124 #[inline]
125 fn index(self) -> usize {
126 usize::from(self)
127 }
128 }
129 )*};
130}
131
132/// Integers are their own index: the tag is `()`, and `from_parts` narrows
133/// an index that came from a key of the same type, so it loses nothing.
134macro_rules! impl_direct_key_int {
135 ($($t:ty),* $(,)?) => {$(
136 impl DirectKey for $t {
137 type Tag = ();
138
139 #[inline]
140 fn tag(self) {}
141
142 #[inline]
143 fn from_parts(index: usize, (): ()) -> Self {
144 index as $t
145 }
146 }
147 )*};
148}
149
150impl_direct_key_int!(u8, u16, usize);
151#[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
152impl_direct_key_int!(u32);
153#[cfg(target_pointer_width = "64")]
154impl_direct_key_int!(u64);
155
156impl_key_lossless!(u8, u16);
157
158impl Key for usize {
159 #[inline]
160 fn index(self) -> usize {
161 self
162 }
163}
164
165// `u32` and `u64` convert to `usize` without loss only on targets whose
166// pointers are at least that wide, so the impls are gated on pointer width.
167#[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
168impl Key for u32 {
169 #[inline]
170 fn index(self) -> usize {
171 self as usize
172 }
173}
174
175#[cfg(target_pointer_width = "64")]
176impl Key for u64 {
177 #[inline]
178 fn index(self) -> usize {
179 self as usize
180 }
181}