Skip to main content

telltale_types/
units.rs

1//! Sized count and length newtypes for protocol-visible values.
2
3use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
4use std::fmt;
5
6/// Maximum allowed role index (0-based).
7pub const MAX_ROLE_INDEX: u32 = 9_999;
8/// Maximum allowed loop iteration count.
9pub const MAX_LOOP_COUNT: u32 = 1_000_000;
10/// Maximum on-wire message length in bytes (16 MiB).
11pub const MAX_MESSAGE_LEN_BYTES: u32 = 16 * 1024 * 1024;
12/// Maximum queue capacity (entries).
13pub const MAX_QUEUE_CAPACITY_COUNT: u32 = 65_536;
14/// Maximum channel capacity (bits).
15pub const MAX_CHANNEL_CAPACITY_BITS: u32 = 1_024;
16/// Maximum content store capacity (entries).
17pub const MAX_STORE_CAPACITY_COUNT: u32 = 1_000_000;
18
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct CountError {
21    pub kind: &'static str,
22    pub value: u64,
23    pub min: u64,
24    pub max: u64,
25}
26
27impl fmt::Display for CountError {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        write!(
30            f,
31            "invalid {}: {} (expected {}..={})",
32            self.kind, self.value, self.min, self.max
33        )
34    }
35}
36
37impl std::error::Error for CountError {}
38
39macro_rules! define_count {
40    ($name:ident, $doc:literal, min = $min:expr, max = $max:expr) => {
41        #[doc = $doc]
42        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
43        pub struct $name(u32);
44
45        impl $name {
46            pub const MIN: u32 = $min;
47            pub const MAX: u32 = $max;
48
49            #[must_use]
50            pub fn new(value: u32) -> Self {
51                assert!(
52                    value >= Self::MIN,
53                    concat!(stringify!($name), " below minimum")
54                );
55                assert!(
56                    value <= Self::MAX,
57                    concat!(stringify!($name), " above maximum")
58                );
59                Self(value)
60            }
61
62            pub fn try_new(value: u32) -> Result<Self, CountError> {
63                if !(Self::MIN..=Self::MAX).contains(&value) {
64                    return Err(CountError {
65                        kind: stringify!($name),
66                        value: value as u64,
67                        min: Self::MIN as u64,
68                        max: Self::MAX as u64,
69                    });
70                }
71                Ok(Self(value))
72            }
73
74            #[must_use]
75            pub const fn get(self) -> u32 {
76                self.0
77            }
78
79            #[must_use]
80            pub const fn as_usize(self) -> usize {
81                self.0 as usize
82            }
83        }
84
85        impl TryFrom<u32> for $name {
86            type Error = CountError;
87
88            fn try_from(value: u32) -> Result<Self, Self::Error> {
89                Self::try_new(value)
90            }
91        }
92
93        impl TryFrom<usize> for $name {
94            type Error = CountError;
95
96            fn try_from(value: usize) -> Result<Self, Self::Error> {
97                let value_u32 = u32::try_from(value).map_err(|_| CountError {
98                    kind: stringify!($name),
99                    value: value as u64,
100                    min: Self::MIN as u64,
101                    max: Self::MAX as u64,
102                })?;
103                Self::try_new(value_u32)
104            }
105        }
106
107        impl From<$name> for u32 {
108            fn from(value: $name) -> Self {
109                value.0
110            }
111        }
112
113        impl fmt::Display for $name {
114            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115                write!(f, "{}", self.0)
116            }
117        }
118
119        impl Serialize for $name {
120            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
121            where
122                S: Serializer,
123            {
124                serializer.serialize_u32(self.0)
125            }
126        }
127
128        impl<'de> Deserialize<'de> for $name {
129            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
130            where
131                D: Deserializer<'de>,
132            {
133                let value = u32::deserialize(deserializer)?;
134                $name::try_new(value).map_err(de::Error::custom)
135            }
136        }
137    };
138}
139
140define_count!(
141    RoleIndex,
142    "Index for a role instance (0-based).",
143    min = 0,
144    max = MAX_ROLE_INDEX
145);
146define_count!(
147    LoopCount,
148    "Count of loop iterations (bounded).",
149    min = 0,
150    max = MAX_LOOP_COUNT
151);
152define_count!(
153    MessageLenBytes,
154    "On-wire message length in bytes.",
155    min = 0,
156    max = MAX_MESSAGE_LEN_BYTES
157);
158define_count!(
159    QueueCapacity,
160    "Queue capacity (entries).",
161    min = 1,
162    max = MAX_QUEUE_CAPACITY_COUNT
163);
164define_count!(
165    ChannelCapacity,
166    "Channel capacity (bits).",
167    min = 0,
168    max = MAX_CHANNEL_CAPACITY_BITS
169);
170define_count!(
171    StoreCapacity,
172    "Content store capacity (entries).",
173    min = 1,
174    max = MAX_STORE_CAPACITY_COUNT
175);