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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/// Helper macro to provide baseline unsigned integer functionality.
/// Assumes the type has a single unsigned integer field.
#[macro_export]
macro_rules! wrapped_uint {
($type_name:ident, $inner:ty) => {
impl From<$inner> for $type_name {
#[inline]
fn from(value: $inner) -> Self {
$type_name(value)
}
}
impl From<$type_name> for $inner {
#[inline]
fn from(value: $type_name) -> $inner {
value.0
}
}
};
}
/// A macro to create distinct value types wrapping a `u64` for type safety.
/// Generates a newtype struct with conversions, Default implementations.
#[macro_export]
macro_rules! define_u64_type {
($type_name:ident) => {
/// A type-safe wrapper around a `u64` value for $type_name.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "wincode", derive(wincode_derive::SchemaRead, wincode_derive::SchemaWrite))]
#[repr(transparent)]
pub struct $type_name(pub u64);
unsafe impl bytemuck::Pod for $type_name {}
unsafe impl bytemuck::Zeroable for $type_name {}
impl $type_name {
/// Creates a new $type_name from a u64.
#[inline]
pub fn new(value: u64) -> Self {
$type_name(value)
}
/// Zero value for $type_name.
#[inline]
pub const fn zero() -> Self {
$type_name(0)
}
/// One value for $type_name.
#[inline]
pub const fn one() -> Self {
$type_name(1)
}
/// Pack from a u64 into a [u8; 8] array in little-endian order.
#[inline]
pub fn pack(&self) -> [u8; 8] {
self.0.to_le_bytes()
}
/// Unpack from a [u8; 8] array in little-endian order into a $type_name.
#[inline]
pub fn unpack(data: [u8; 8]) -> Self {
$type_name(u64::from_le_bytes(data))
}
/// Returns the inner u64 value.
#[inline]
pub fn as_u64(&self) -> u64 {
self.0
}
/// Returns the value as a u128
#[inline]
pub fn as_u128(&self) -> u128 {
self.0 as u128
}
/// Converts the value to usize.
#[inline]
pub fn as_usize(&self) -> usize {
self.0 as usize
}
/// Fallibly converts the value to usize.
#[inline]
pub fn try_as_usize(&self) -> Result<usize, core::num::TryFromIntError> {
usize::try_from(self.0)
}
/// Converts the value to u32.
#[inline]
pub fn as_u32(&self) -> u32 {
self.0 as u32
}
/// Checked addition with overflow handling.
#[inline]
pub fn checked_add(&self, rhs: Self) -> Option<Self> {
self.0.checked_add(rhs.0).map($type_name)
}
/// Checked subtraction with underflow handling.
#[inline]
pub fn checked_sub(&self, rhs: Self) -> Option<Self> {
self.0.checked_sub(rhs.0).map($type_name)
}
/// Checked multiplication with overflow handling.
#[inline]
pub fn checked_mul(&self, rhs: Self) -> Option<Self> {
self.0.checked_mul(rhs.0).map($type_name)
}
/// Checked division with division-by-zero handling.
#[inline]
pub fn checked_div(&self, rhs: Self) -> Option<Self> {
self.0.checked_div(rhs.0).map($type_name)
}
/// Saturating addition, capping at u64::MAX.
#[inline]
pub fn saturating_add(&self, rhs: Self) -> Self {
$type_name(self.0.saturating_add(rhs.0))
}
/// Saturating subtraction, capping at 0.
#[inline]
pub fn saturating_sub(&self, rhs: Self) -> Self {
$type_name(self.0.saturating_sub(rhs.0))
}
/// Saturating multiplication, capping at u64::MAX.
#[inline]
pub fn saturating_mul(&self, rhs: Self) -> Self {
$type_name(self.0.saturating_mul(rhs.0))
}
/// Minimum of two values.
#[inline]
pub fn min(&self, rhs: Self) -> Self {
if *self <= rhs { *self } else { rhs }
}
/// Maximum of two values.
#[inline]
pub fn max(&self, rhs: Self) -> Self {
if *self >= rhs { *self } else { rhs }
}
/// Next value, returning None on overflow.
#[inline]
pub fn checked_next(&self) -> Option<Self> {
self.checked_add($type_name(1))
}
/// Previous value, returning None on underflow.
#[inline]
pub fn checked_prev(&self) -> Option<Self> {
self.checked_sub($type_name(1))
}
/// Next value, saturating at u64::MAX.
#[inline]
pub fn next(&self) -> Self {
self.saturating_add($type_name(1))
}
/// Previous value, saturating at 0.
#[inline]
pub fn prev(&self) -> Self {
self.saturating_sub($type_name(1))
}
/// Increments the by 1, saturating at u64::MAX.
#[inline]
pub fn increment(&mut self) {
self.0 = self.0.saturating_add(1);
}
/// Decrements the by 1, saturating at 0.
#[inline]
pub fn decrement(&mut self) {
self.0 = self.0.saturating_sub(1);
}
/// Returns true if the value is zero.
#[inline]
pub fn is_zero(&self) -> bool {
self.0 == 0
}
/// Returns true if the value is one.
#[inline]
pub fn is_one(&self) -> bool {
self.0 == 1
}
}
impl core::ops::Add for $type_name {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self {
self.checked_add(rhs).expect("Addition overflow")
}
}
impl core::ops::Sub for $type_name {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self {
self.checked_sub(rhs).expect("Subtraction underflow")
}
}
impl core::ops::Mul for $type_name {
type Output = Self;
#[inline]
fn mul(self, rhs: Self) -> Self {
self.checked_mul(rhs).expect("Multiplication overflow")
}
}
impl core::ops::Div for $type_name {
type Output = Self;
#[inline]
fn div(self, rhs: Self) -> Self {
self.checked_div(rhs).expect("Division by zero or overflow")
}
}
impl Default for $type_name {
/// Returns a default $type_name with value 0.
fn default() -> Self {
$type_name(0)
}
}
$crate::wrapped_uint!($type_name, u64);
};
}
/// A macro to create distinct value types wrapping a `u64` for type safety.
/// Generates a newtype struct with conversions, Default, and Display implementations.
#[macro_export]
macro_rules! define_numeric_type {
($type_name:ident, $prefix:literal) => {
$crate::define_u64_type!($type_name);
impl core::fmt::Debug for $type_name {
/// Formats the $type_name as its inner u64 value with a prefix.
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}:{}", $prefix, self.0)
}
}
impl core::fmt::Display for $type_name {
/// Formats the $type_name as its inner u64 value with a prefix.
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}:{}", $prefix, self.0)
}
}
};
}
#[cfg(test)]
mod tests {
define_u64_type!(BasisPoints);
define_numeric_type!(TapeNumber, "tape");
#[test]
fn test_segment() {
let v = BasisPoints::new(42_000);
assert_eq!(v.as_u64(), 42_000);
assert_eq!(v.as_usize(), 42_000);
assert_eq!(v.as_u32(), 42_000);
assert_eq!(u64::from(v), 42_000);
}
#[test]
fn test_tape() {
let v = TapeNumber::new(99_000);
assert_eq!(v.as_u64(), 99_000);
assert_eq!(v.as_usize(), 99_000);
assert_eq!(v.as_u32(), 99_000);
assert_eq!(v, TapeNumber::from(99_000));
assert_eq!(u64::from(v), 99_000);
assert_eq!(format!("{}", v), "tape:99000");
assert_eq!(TapeNumber::default(), TapeNumber(0));
}
#[test]
fn test_order_and_step_helpers() {
let low = TapeNumber::new(3);
let high = TapeNumber::new(9);
assert_eq!(low.min(high), low);
assert_eq!(low.max(high), high);
assert_eq!(low.checked_next(), Some(TapeNumber::new(4)));
assert_eq!(low.checked_prev(), Some(TapeNumber::new(2)));
assert_eq!(low.next(), TapeNumber::new(4));
assert_eq!(low.prev(), TapeNumber::new(2));
assert_eq!(TapeNumber::zero().checked_prev(), None);
assert_eq!(TapeNumber::zero().prev(), TapeNumber::zero());
assert_eq!(TapeNumber::new(u64::MAX).checked_next(), None);
assert_eq!(TapeNumber::new(u64::MAX).next(), TapeNumber::new(u64::MAX));
}
}