Skip to main content

cranpose_core/
scene_records.rs

1use std::num::{NonZeroU16, NonZeroU32};
2
3/// A record of a scene store: its row, one more than its index, so that an
4/// absent record costs no space beside a present one.
5#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
6pub struct RecordId(NonZeroU32);
7
8impl RecordId {
9    /// The record at row `index`; `None` past the last row a store can hold.
10    pub fn from_index(index: usize) -> Option<Self> {
11        u32::try_from(index)
12            .ok()
13            .and_then(|index| index.checked_add(1))
14            .and_then(NonZeroU32::new)
15            .map(Self)
16    }
17
18    /// The row of the record.
19    pub fn index(self) -> usize {
20        (self.0.get() - 1) as usize
21    }
22}
23
24/// A scene store, one per surface renderer, so a layout node that moves to
25/// another window knows which store holds its records.
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
27pub struct StoreId(NonZeroU16);
28
29impl StoreId {
30    /// The store numbered `number`; `None` for zero.
31    pub fn new(number: u16) -> Option<Self> {
32        NonZeroU16::new(number).map(Self)
33    }
34
35    /// The store's number.
36    pub fn number(self) -> u16 {
37        self.0.get()
38    }
39}
40
41/// A record held outside a frame: its row and the generation the row had,
42/// which tells a holder that the row went to another record since.
43#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
44pub struct RecordRef {
45    /// The record's row.
46    pub id: RecordId,
47    /// The generation of the row when the holder took it.
48    pub generation: u32,
49}
50
51/// A scene update's number. It wraps: of two numbers less than 2^31 apart,
52/// the one reached by counting on from the other is the newer.
53#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
54pub struct SceneUpdate(u32);
55
56impl SceneUpdate {
57    /// The update after this one.
58    #[must_use]
59    pub fn next(self) -> Self {
60        Self(self.0.wrapping_add(1))
61    }
62
63    /// Whether this update came after `other`.
64    pub fn is_after(self, other: Self) -> bool {
65        self != other && self.0.wrapping_sub(other.0) < 1 << 31
66    }
67
68    /// How many updates came after `earlier` up to this one.
69    pub fn since(self, earlier: Self) -> u32 {
70        self.0.wrapping_sub(earlier.0)
71    }
72}
73
74#[cfg(test)]
75#[path = "tests/scene_records_tests.rs"]
76mod tests;