1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
#![doc = include_str!("../README.md")]
#![no_std]
#![forbid(unsafe_code)]
#![warn(missing_docs, clippy::pedantic)]

extern crate alloc;

/// An ordered collection of values, accessible by [`LotId`] or index.
pub mod ordered;
/// An unordered collection of values, accessible by [`LotId`].
pub mod unordered;

use core::array;
use core::fmt::{Debug, Write};
use core::num::{NonZeroU16, NonZeroUsize};

pub use ordered::OrderedLots;
pub use unordered::Lots;

/// A `LotId` is a single `usize`, encoding generation information in the top
/// 1/4 of the bits, and index information in the remaining bits. This table
/// shows the breakdown for supported target platforms:
///
/// | `target_pointer_width` | generation bits | index bits |
/// |------------------------|-----------------|------------|
/// | 16                     | 4               | 12         |
/// | 32                     | 8               | 24         |
/// | 64                     | 16              | 48         |
///
/// Each time a lot is allocated, its generation is incremented. When retrieving
/// values using a `LotId`, the generation is validated as a safe guard against
/// returning a value. Because the generation isn't significantly wide, the
/// generation can wrap and is not a perfect protection against stale data,
/// although the likelihood of improper access is greatly reduced.
#[derive(Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct LotId(NonZeroUsize);

impl Debug for LotId {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("LotId(")?;
        self.index().fmt(f)?;
        f.write_char('g')?;
        self.generation().fmt(f)?;
        f.write_char(')')
    }
}

#[test]
fn lot_id_debug() {
    let lot = LotId::new(Generation::first(), 0).unwrap();
    assert_eq!(alloc::format!("{lot:?}"), "LotId(0g1)");
}

#[cfg(not(any(
    target_pointer_width = "16",
    target_pointer_width = "32",
    target_pointer_width = "64"
)))]
compile_error!("LotId currently only supports 16, 32 and 64 bit architectures.");

impl LotId {
    #[allow(clippy::cast_possible_truncation)]
    const GENERATION_MAX: u16 = (usize::MAX >> Self::INDEX_BITS) as u16;
    const INDEX_BITS: u32 = usize::BITS / 4 * 3;
    const INDEX_MASK: usize = 2_usize.pow(Self::INDEX_BITS) - 1;

    #[cfg_attr(target_pointer_width = "64", allow(clippy::absurd_extreme_comparisons))]
    #[inline]
    fn new(generation: Generation, index: usize) -> Option<Self> {
        if index <= Self::INDEX_MASK && generation.get() <= Self::GENERATION_MAX {
            Some(Self(
                NonZeroUsize::new((generation.0.get() as usize) << Self::INDEX_BITS | index)
                    .expect("generation is non-zero"),
            ))
        } else {
            None
        }
    }

    #[inline]
    #[must_use]
    const fn index(self) -> usize {
        self.0.get() & Self::INDEX_MASK
    }

    #[inline]
    #[must_use]
    #[allow(clippy::cast_possible_truncation)]
    fn generation(self) -> Generation {
        Generation(
            NonZeroU16::new((self.0.get() >> Self::INDEX_BITS) as u16).expect("invalid Lot id"),
        )
    }

    /// Returns this ID as bytes. To decode the resulting bytes, use
    /// [`from_bytes()`](Self::from_bytes).
    ///
    /// The result of this fuction changes size based on the width of `usize`.
    #[must_use]
    pub const fn as_bytes(self) -> [u8; (usize::BITS / 8) as usize] {
        self.0.get().to_be_bytes()
    }

    /// Decodes `bytes` that were previously encoded with
    /// [`as_bytes()`](Self::as_bytes) and returns a `LotId` if it appears to be
    /// a valid ID.
    ///
    /// This function will "upgrade" previously encoded `LotId`s from
    /// architectures where `usize` is smaller than the current architecture.
    #[must_use]
    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
        let usize = match bytes.try_into() {
            Ok(bytes) => usize::from_be_bytes(bytes),
            Err(_) => match bytes.len() {
                2 if usize::BITS >= 16 => {
                    expand_from_shorter::<16>(u16::from_be_bytes(array::from_fn(|index| {
                        bytes[index]
                    })) as usize)
                }
                4 if usize::BITS >= 32 => {
                    expand_from_shorter::<32>(u32::from_be_bytes(array::from_fn(|index| {
                        bytes[index]
                    })) as usize)
                }
                _ => return None,
            },
        };

        if usize >> Self::INDEX_BITS == 0 {
            None
        } else {
            Some(Self(NonZeroUsize::new(usize).assert("generation checked")))
        }
    }
}

trait Assert {
    type Unwrapped;
    fn assert(self, msg: &str) -> Self::Unwrapped;
}

impl<T, E> Assert for Result<T, E>
where
    E: Debug,
{
    type Unwrapped = T;

    fn assert(self, msg: &str) -> Self::Unwrapped {
        self.expect(msg)
    }
}

impl<T> Assert for Option<T> {
    type Unwrapped = T;

    fn assert(self, msg: &str) -> Self::Unwrapped {
        self.expect(msg)
    }
}

#[inline]
fn expand_from_shorter<const BITS: usize>(value: usize) -> usize {
    let index_bits = BITS / 4 * 3;
    let generation = value >> index_bits;
    let index = value & ((1 << index_bits) - 1);

    (generation << LotId::INDEX_BITS) | index
}

#[test]
fn invalid_ids() {
    assert!(LotId::new(Generation::first(), usize::MAX).is_none());
}

#[test]
fn lot_id_bytes() {
    let decoded =
        LotId::from_bytes(&LotId::new(Generation::first(), 2).unwrap().as_bytes()).unwrap();
    assert_eq!(decoded.generation().get(), 1);
    assert_eq!(decoded.index(), 2);

    let expanded = LotId::from_bytes(&0xF001_u16.to_be_bytes()).unwrap();
    assert_eq!(expanded.generation().get(), 15);
    assert_eq!(expanded.index(), 1);
    let expanded = LotId::from_bytes(&0xFF00_0001_u32.to_be_bytes()).unwrap();
    assert_eq!(expanded.generation().get(), 255);
    assert_eq!(expanded.index(), 1);

    assert_eq!(LotId::from_bytes(&[]), None);
    assert_eq!(LotId::from_bytes(&[0; (usize::BITS / 8) as usize]), None);
}

#[derive(Clone, Copy, Eq, PartialEq)]
struct Generation(NonZeroU16);

impl Generation {
    #[cfg(test)]
    const MAX: Self = Self(match NonZeroU16::new(LotId::GENERATION_MAX) {
        Some(nz) => nz,
        None => unreachable!(),
    });

    #[inline]
    #[must_use]
    pub const fn first() -> Self {
        Self(match NonZeroU16::new(1) {
            Some(one) => one,
            None => unreachable!(),
        })
    }

    #[inline]
    #[must_use]
    #[cfg_attr(target_pointer_width = "64", allow(clippy::absurd_extreme_comparisons))]
    pub const fn next(self) -> Self {
        match self.0.checked_add(1) {
            Some(next) if next.get() <= LotId::GENERATION_MAX => Self(next),
            _ => Self::first(),
        }
    }

    #[inline]
    #[must_use]
    pub const fn get(self) -> u16 {
        self.0.get()
    }
}

impl Debug for Generation {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.0.fmt(f)
    }
}

#[test]
fn generation_wrapping() {
    let max = Generation::MAX;
    assert_eq!(max.next(), Generation::first());
}