Skip to main content

dope_core/driver/route/table/
conn.rs

1use std::num;
2
3use o3::{base::num::bounded, depot, depot::capacity};
4
5use crate::driver::{route, route::table};
6
7/// A non-empty target-table capacity with one encodable slot left as a sentinel.
8#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
9#[repr(transparent)]
10pub struct Capacity(num::NonZero<u32>);
11
12impl Capacity {
13    pub const fn fixed<const COUNT: usize>() -> Self {
14        const { assert!(COUNT > 0 && COUNT <= route::SLOT_MASK as usize, "capacity") };
15        Self(num::NonZero::<u32>::MIN.saturating_add(COUNT as u32 - 1))
16    }
17
18    pub const fn nonzero(self) -> num::NonZero<usize> {
19        num::NonZero::<usize>::MIN.saturating_add(self.raw() as usize - 1)
20    }
21
22    pub(crate) const fn raw(self) -> u32 {
23        self.0.get()
24    }
25
26    pub const fn count(self) -> num::NonZero<u32> {
27        self.0
28    }
29
30    pub const fn entries(self) -> capacity::Count {
31        capacity::Count::new(self.0.get())
32    }
33
34    /// Scales this validated connection domain into a collection count.
35    ///
36    /// The factor is part of the type-level call site, so the complete
37    /// connection domain must fit before any value can be scaled.
38    pub const fn scale<const FACTOR: u32>(self) -> capacity::Count {
39        const {
40            assert!(FACTOR != 0);
41            assert!(route::SLOT_MASK <= (u32::MAX / FACTOR) as u64);
42        }
43        capacity::Count::new(self.0.get() * FACTOR)
44    }
45}
46
47impl TryFrom<usize> for Capacity {
48    type Error = table::Invalid;
49
50    fn try_from(actual: usize) -> Result<Self, Self::Error> {
51        bounded::raw::NonZeroU32::<1, { route::SLOT_MASK as u32 }>::from_usize(actual)
52            .map(|count| Self(count.nonzero()))
53            .ok_or_else(|| table::Invalid::from_bounds(actual, 1, route::SLOT_MASK as usize))
54    }
55}
56
57impl From<num::NonZero<u16>> for Capacity {
58    fn from(count: num::NonZero<u16>) -> Self {
59        const { assert!(u16::MAX as u64 <= route::SLOT_MASK, "capacity bound") };
60        Self(count.into())
61    }
62}
63
64impl From<Capacity> for table::Capacity {
65    fn from(capacity: Capacity) -> Self {
66        Self(capacity::Count::new(capacity.0.get()))
67    }
68}
69
70// SAFETY: the retained nonzero connection domain is bounded by SLOT_MASK, which is one immutable u32 extent.
71unsafe impl depot::raw::Count for Capacity {
72    const MAX: u32 = route::SLOT_MASK as u32;
73
74    fn count(self) -> capacity::Count {
75        capacity::Count::new(self.0.get())
76    }
77}