temporal_control/dispatch/index.rs
1//! Integer types for the dispatcher's internal point and entry handles.
2
3use core::fmt::Debug;
4use core::hash::Hash;
5
6/// Seals [`Index`] so that only the integer types below implement it.
7mod sealed {
8 /// Implemented exactly for the types that implement [`super::Index`].
9 pub trait Sealed {}
10}
11
12/// Unsigned integer type a [`Dispatcher`](super::Dispatcher) stores point and entry handles
13/// in: `u16`, `u32` or `usize` (the default).
14///
15/// Public handles stay [`TimePoint`](crate::TimePoint)`(usize)`; the index type only sets the
16/// width of the dispatcher's internal arrays (adjacency targets, range offsets, precedence
17/// counters, activation links). A network fits iff its point count and its entry count
18/// (`2 * edges + waits`) are both at most the type's maximum value, so that every index and
19/// every range offset, including the one-past-the-end offset, is representable. Loading a
20/// network that does not fit fails with
21/// [`DispatchError::IndexTypeTooSmall`](super::DispatchError::IndexTypeTooSmall). Choosing
22/// capacities `N, E <= MAX` rules that out statically.
23///
24/// # Memory
25///
26/// Measured `size_of` per point and per entry capacity slot:
27///
28/// | Target | `usize` | `u32` | `u16` |
29/// | --- | --- | --- | --- |
30/// | `thumbv7em-none-eabihf` (32-bit) | 80 + 16 | 80 + 16 | 76 + 16 |
31/// | `x86_64` | 96 + 24 | 80 + 16 | 76 + 16 |
32///
33/// Entries and windows hold `i64` ticks and are 8-byte aligned, so on 32-bit targets a narrow
34/// index saves only the per-point offsets and counters.
35///
36/// The trait is sealed: it cannot be implemented outside this crate.
37pub trait Index: sealed::Sealed + Copy + Eq + Ord + Hash + Debug + 'static {
38 /// The value zero, for `const` initialisers.
39 const ZERO: Self;
40
41 /// Converts `value`, or `None` if it does not fit.
42 fn from_usize(value: usize) -> Option<Self>;
43
44 /// Widens to `usize`.
45 ///
46 /// Exact for every value obtained from [`Index::from_usize`]; on targets where `usize` is
47 /// narrower than `Self` other values map to `usize::MAX`.
48 fn to_usize(self) -> usize;
49
50 /// Subtracts one, staying at zero.
51 #[must_use]
52 fn saturating_dec(self) -> Self;
53}
54
55/// Implements [`Index`] for unsigned integer types.
56macro_rules! impl_index {
57 ($($t:ty),*) => {$(
58 impl sealed::Sealed for $t {}
59
60 impl Index for $t {
61 const ZERO: Self = 0;
62
63 fn from_usize(value: usize) -> Option<Self> {
64 Self::try_from(value).ok()
65 }
66
67 fn to_usize(self) -> usize {
68 usize::try_from(self).unwrap_or(usize::MAX)
69 }
70
71 fn saturating_dec(self) -> Self {
72 self.saturating_sub(1)
73 }
74 }
75 )*};
76}
77
78impl_index!(u16, u32, usize);