commonware-codec 2026.4.0

Serialize structured data.
Documentation
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! Types for use as [crate::Read::Cfg].

use core::{
    num::{NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize},
    ops::{Bound, RangeBounds},
};

/// Configuration for limiting the range of a value.
///
/// This is often used to configure length limits for variable-length types or collections.
///
/// # Examples
///
/// ```
/// use commonware_codec::RangeCfg;
///
/// // Limit lengths to 0..=1024 (type inferred as usize)
/// let cfg = RangeCfg::new(0..=1024);
/// assert!(cfg.contains(&500));
/// assert!(!cfg.contains(&2000));
///
/// // Allow any length >= 1
/// let cfg_min = RangeCfg::from(1..);
/// assert!(cfg_min.contains(&1));
/// assert!(!cfg_min.contains(&0));
///
/// // Works with other integer types
/// let cfg_u8: RangeCfg<u8> = RangeCfg::new(0u8..=255u8);
/// assert!(cfg_u8.contains(&128));
///
/// let cfg_u32 = RangeCfg::new(0u32..1024u32);
/// assert!(cfg_u32.contains(&500));
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct RangeCfg<T: Copy + PartialOrd> {
    /// The lower bound of the range.
    start: Bound<T>,

    /// The upper bound of the range.
    end: Bound<T>,
}

impl<T: Copy + PartialOrd> From<core::ops::Range<T>> for RangeCfg<T> {
    fn from(r: core::ops::Range<T>) -> Self {
        Self::new(r)
    }
}

impl<T: Copy + PartialOrd> From<core::ops::RangeInclusive<T>> for RangeCfg<T> {
    fn from(r: core::ops::RangeInclusive<T>) -> Self {
        Self::new(r)
    }
}

impl<T: Copy + PartialOrd> From<core::ops::RangeFrom<T>> for RangeCfg<T> {
    fn from(r: core::ops::RangeFrom<T>) -> Self {
        Self::new(r)
    }
}

impl<T: Copy + PartialOrd> From<core::ops::RangeTo<T>> for RangeCfg<T> {
    fn from(r: core::ops::RangeTo<T>) -> Self {
        Self::new(r)
    }
}

impl<T: Copy + PartialOrd> From<core::ops::RangeToInclusive<T>> for RangeCfg<T> {
    fn from(r: core::ops::RangeToInclusive<T>) -> Self {
        Self::new(r)
    }
}

impl<T: Copy + PartialOrd> From<core::ops::RangeFull> for RangeCfg<T> {
    fn from(_: core::ops::RangeFull) -> Self {
        Self::new(..)
    }
}

macro_rules! impl_from_nonzero {
    ($nz_ty:ty, $ty:ty) => {
        impl From<RangeCfg<$nz_ty>> for RangeCfg<$ty> {
            fn from(value: RangeCfg<$nz_ty>) -> Self {
                let start = match value.start {
                    Bound::Included(nz) => Bound::Included(nz.get()),
                    Bound::Excluded(nz) => Bound::Excluded(nz.get()),
                    Bound::Unbounded => Bound::Unbounded,
                };
                let end = match value.end {
                    Bound::Included(nz) => Bound::Included(nz.get()),
                    Bound::Excluded(nz) => Bound::Excluded(nz.get()),
                    Bound::Unbounded => Bound::Unbounded,
                };
                RangeCfg { start, end }
            }
        }
    };
}

impl_from_nonzero!(NonZeroUsize, usize);
impl_from_nonzero!(NonZeroU8, u8);
impl_from_nonzero!(NonZeroU16, u16);
impl_from_nonzero!(NonZeroU32, u32);
impl_from_nonzero!(NonZeroU64, u64);

macro_rules! impl_from_nonzero_to_usize {
    ($from_ty:ty) => {
        impl From<RangeCfg<$from_ty>> for RangeCfg<usize> {
            fn from(value: RangeCfg<$from_ty>) -> Self {
                let start = match value.start {
                    Bound::Included(v) => Bound::Included(
                        usize::try_from(v.get()).expect("range start exceeds usize"),
                    ),
                    Bound::Excluded(v) => Bound::Excluded(
                        usize::try_from(v.get()).expect("range start exceeds usize"),
                    ),
                    Bound::Unbounded => Bound::Unbounded,
                };
                let end = match value.end {
                    Bound::Included(v) => {
                        Bound::Included(usize::try_from(v.get()).expect("range end exceeds usize"))
                    }
                    Bound::Excluded(v) => {
                        Bound::Excluded(usize::try_from(v.get()).expect("range end exceeds usize"))
                    }
                    Bound::Unbounded => Bound::Unbounded,
                };
                RangeCfg { start, end }
            }
        }
    };
}

impl_from_nonzero_to_usize!(NonZeroU8);
impl_from_nonzero_to_usize!(NonZeroU16);
impl_from_nonzero_to_usize!(NonZeroU32);

macro_rules! impl_nonzero_to_nonzero_usize {
    ($from_ty:ty) => {
        impl From<RangeCfg<$from_ty>> for RangeCfg<NonZeroUsize> {
            fn from(value: RangeCfg<$from_ty>) -> Self {
                let start = match value.start {
                    Bound::Included(v) => Bound::Included(
                        NonZeroUsize::try_from(v).expect("range start exceeds usize"),
                    ),
                    Bound::Excluded(v) => Bound::Excluded(
                        NonZeroUsize::try_from(v).expect("range start exceeds usize"),
                    ),
                    Bound::Unbounded => Bound::Unbounded,
                };
                let end = match value.end {
                    Bound::Included(v) => {
                        Bound::Included(NonZeroUsize::try_from(v).expect("range end exceeds usize"))
                    }
                    Bound::Excluded(v) => {
                        Bound::Excluded(NonZeroUsize::try_from(v).expect("range end exceeds usize"))
                    }
                    Bound::Unbounded => Bound::Unbounded,
                };
                RangeCfg { start, end }
            }
        }
    };
}

impl_nonzero_to_nonzero_usize!(NonZeroU8);
impl_nonzero_to_nonzero_usize!(NonZeroU16);
impl_nonzero_to_nonzero_usize!(NonZeroU32);

impl<T: Copy + PartialOrd> RangeCfg<T> {
    /// Creates a new `RangeCfg` from any type implementing `RangeBounds<T>`.
    ///
    /// # Examples
    ///
    /// ```
    /// use commonware_codec::RangeCfg;
    ///
    /// let cfg = RangeCfg::new(0..=1024);
    /// assert!(cfg.contains(&500));
    /// ```
    pub fn new(r: impl RangeBounds<T>) -> Self {
        Self {
            start: r.start_bound().cloned(),
            end: r.end_bound().cloned(),
        }
    }

    /// Creates a `RangeCfg` that only accepts exactly `value`.
    pub const fn exact(value: T) -> Self {
        Self {
            start: Bound::Included(value),
            end: Bound::Included(value),
        }
    }

    /// Returns true if the value is within this range.
    pub fn contains(&self, value: &T) -> bool {
        // Exclude by start bound
        match &self.start {
            Bound::Included(s) if value < s => return false,
            Bound::Excluded(s) if value <= s => return false,
            _ => {}
        }

        // Exclude by end bound
        match &self.end {
            Bound::Included(e) if value > e => return false,
            Bound::Excluded(e) if value >= e => return false,
            _ => {}
        }

        // If not excluded by either bound, the value is within the range
        true
    }
}

impl<T: Copy + PartialOrd> RangeBounds<T> for RangeCfg<T> {
    fn start_bound(&self) -> Bound<&T> {
        self.start.as_ref()
    }

    fn end_bound(&self) -> Bound<&T> {
        self.end.as_ref()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use core::ops::Bound::{Excluded, Included, Unbounded};

    #[test]
    fn test_range_cfg_from() {
        // Full range
        let cfg_full: RangeCfg<usize> = (..).into();
        assert_eq!(
            cfg_full,
            RangeCfg {
                start: Unbounded,
                end: Unbounded
            }
        );

        // Start bounded, end unbounded
        let cfg_start_incl: RangeCfg<usize> = (5..).into();
        assert_eq!(
            cfg_start_incl,
            RangeCfg {
                start: Included(5),
                end: Unbounded
            }
        );

        // Start unbounded, end bounded (exclusive)
        let cfg_end_excl: RangeCfg<usize> = (..10).into();
        assert_eq!(
            cfg_end_excl,
            RangeCfg {
                start: Unbounded,
                end: Excluded(10)
            }
        );

        // Start unbounded, end bounded (inclusive)
        let cfg_end_incl: RangeCfg<usize> = (..=10).into();
        assert_eq!(
            cfg_end_incl,
            RangeCfg {
                start: Unbounded,
                end: Included(10)
            }
        );

        // Fully bounded (inclusive start, exclusive end)
        let cfg_incl_excl: RangeCfg<usize> = (5..10).into();
        assert_eq!(
            cfg_incl_excl,
            RangeCfg {
                start: Included(5),
                end: Excluded(10)
            }
        );

        // Fully bounded (inclusive)
        let cfg_incl_incl: RangeCfg<usize> = (5..=10).into();
        assert_eq!(
            cfg_incl_incl,
            RangeCfg {
                start: Included(5),
                end: Included(10)
            }
        );

        // Fully bounded (exclusive start)
        struct ExclusiveStartRange(usize, usize);
        impl RangeBounds<usize> for ExclusiveStartRange {
            fn start_bound(&self) -> Bound<&usize> {
                Excluded(&self.0)
            }
            fn end_bound(&self) -> Bound<&usize> {
                Included(&self.1)
            }
        }
        let cfg_excl_incl = RangeCfg::new(ExclusiveStartRange(5, 10));
        assert_eq!(
            cfg_excl_incl,
            RangeCfg {
                start: Excluded(5),
                end: Included(10)
            }
        );
    }

    #[test]
    fn test_range_cfg_contains() {
        // Unbounded range (..)
        let cfg_unbounded: RangeCfg<usize> = (..).into();
        assert!(cfg_unbounded.contains(&0));
        assert!(cfg_unbounded.contains(&100));
        assert!(cfg_unbounded.contains(&usize::MAX));

        // Inclusive start (5..)
        let cfg_start_incl: RangeCfg<usize> = (5..).into();
        assert!(!cfg_start_incl.contains(&4));
        assert!(cfg_start_incl.contains(&5));
        assert!(cfg_start_incl.contains(&6));
        assert!(cfg_start_incl.contains(&usize::MAX));

        // Exclusive end (..10)
        let cfg_end_excl: RangeCfg<usize> = (..10).into();
        assert!(cfg_end_excl.contains(&0));
        assert!(cfg_end_excl.contains(&9));
        assert!(!cfg_end_excl.contains(&10));
        assert!(!cfg_end_excl.contains(&11));

        // Inclusive end (..=10)
        let cfg_end_incl: RangeCfg<usize> = (..=10).into();
        assert!(cfg_end_incl.contains(&0));
        assert!(cfg_end_incl.contains(&9));
        assert!(cfg_end_incl.contains(&10));
        assert!(!cfg_end_incl.contains(&11));

        // Inclusive start, exclusive end (5..10)
        let cfg_incl_excl: RangeCfg<usize> = (5..10).into();
        assert!(!cfg_incl_excl.contains(&4));
        assert!(cfg_incl_excl.contains(&5));
        assert!(cfg_incl_excl.contains(&9));
        assert!(!cfg_incl_excl.contains(&10));
        assert!(!cfg_incl_excl.contains(&11));

        // Inclusive start, inclusive end (5..=10)
        let cfg_incl_incl: RangeCfg<usize> = (5..=10).into();
        assert!(!cfg_incl_incl.contains(&4));
        assert!(cfg_incl_incl.contains(&5));
        assert!(cfg_incl_incl.contains(&9));
        assert!(cfg_incl_incl.contains(&10));
        assert!(!cfg_incl_incl.contains(&11));

        // Exclusive start, inclusive end (pseudo: >5 ..=10)
        let cfg_excl_incl = RangeCfg {
            start: Excluded(5),
            end: Included(10),
        };
        assert!(!cfg_excl_incl.contains(&4));
        assert!(!cfg_excl_incl.contains(&5)); // Excluded
        assert!(cfg_excl_incl.contains(&6));
        assert!(cfg_excl_incl.contains(&10)); // Included
        assert!(!cfg_excl_incl.contains(&11));

        // Exclusive start, exclusive end (pseudo: >5 .. <10)
        let cfg_excl_excl = RangeCfg {
            start: Excluded(5),
            end: Excluded(10),
        };
        assert!(!cfg_excl_excl.contains(&5)); // Excluded
        assert!(cfg_excl_excl.contains(&6));
        assert!(cfg_excl_excl.contains(&9));
        assert!(!cfg_excl_excl.contains(&10)); // Excluded
    }

    #[test]
    fn test_contains_empty_range() {
        // Empty range (e.g., 5..5)
        let cfg_empty_excl: RangeCfg<usize> = (5..5).into();
        assert!(!cfg_empty_excl.contains(&4));
        assert!(!cfg_empty_excl.contains(&5));
        assert!(!cfg_empty_excl.contains(&6));

        // Slightly less obvious empty range (e.g., 6..=5)
        #[allow(clippy::reversed_empty_ranges)]
        let cfg_empty_incl: RangeCfg<usize> = (6..=5).into();
        assert!(!cfg_empty_incl.contains(&5));
        assert!(!cfg_empty_incl.contains(&6));
    }

    #[test]
    fn test_range_cfg_u8() {
        // Test with u8 type
        let cfg = RangeCfg::new(0u8..=255u8);
        assert!(cfg.contains(&0));
        assert!(cfg.contains(&128));
        assert!(cfg.contains(&255));

        let cfg_partial = RangeCfg::new(10u8..20u8);
        assert!(!cfg_partial.contains(&9));
        assert!(cfg_partial.contains(&10));
        assert!(cfg_partial.contains(&19));
        assert!(!cfg_partial.contains(&20));
    }

    #[test]
    fn test_range_cfg_u16() {
        // Test with u16 type
        let cfg = RangeCfg::new(100u16..=1000u16);
        assert!(!cfg.contains(&99));
        assert!(cfg.contains(&100));
        assert!(cfg.contains(&500));
        assert!(cfg.contains(&1000));
        assert!(!cfg.contains(&1001));
    }

    #[test]
    fn test_range_cfg_u32() {
        // Test with u32 type
        let cfg = RangeCfg::new(0u32..1024u32);
        assert!(cfg.contains(&0));
        assert!(cfg.contains(&512));
        assert!(!cfg.contains(&1024));
        assert!(!cfg.contains(&2000));
    }

    #[test]
    fn test_range_cfg_u64() {
        // Test with u64 type
        let cfg = RangeCfg::new(1000u64..);
        assert!(!cfg.contains(&999));
        assert!(cfg.contains(&1000));
        assert!(cfg.contains(&u64::MAX));
    }

    #[test]
    fn test_type_inference() {
        // Type inference from range literal with explicit type suffixes
        let cfg = RangeCfg::new(0u8..10u8);
        assert!(cfg.contains(&5u8));

        // Type inference when assigning to typed variable
        let cfg: RangeCfg<u32> = RangeCfg::new(0..1000);
        assert!(cfg.contains(&500));
    }
}