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
//! Byte-length-bounded owned UTF-8 strings and byte slices.
//!
//! Binary formats and wire protocols routinely encode variable-length fields
//! with a fixed-width length prefix (commonly `u8`, `u16`, or `u32`). Casting
//! a `usize` length into a narrower integer at serialization time silently
//! truncates oversized inputs and corrupts the framing of subsequent fields.
//!
//! [`str::BoundedString`] and [`bytes::BoundedBytes`] move that
//! constraint from the serializer into the type system: the maximum byte
//! length is a const generic parameter, the bound is checked once at
//! construction, and serialization can downcast the length infallibly
//! thereafter.
//!
//! # Examples
//!
//! ```ignore
//! use libpna::util::bounded::{str::BoundedString, bytes::BoundedBytes};
//!
//! // A field whose on-the-wire length prefix is a `u8` accepts at most 255 bytes.
//! let name: BoundedString<255> = "root".try_into().unwrap();
//! assert_eq!(name.len(), 4);
//!
//! let too_long: Result<BoundedString<255>, _> = "a".repeat(256).try_into();
//! assert!(too_long.is_err());
//!
//! // Arbitrary bytes (non-UTF-8 permitted).
//! let payload: BoundedBytes<8> = vec![0xFF, 0x00, 0x42].try_into().unwrap();
//! assert_eq!(payload.len(), 3);
//! ```
use ;
/// Error returned when a value exceeds the byte-length bound of a bounded
/// owned string or byte slice.
///
/// Inspect the bound and the actual length via [`max`](Self::max) and
/// [`actual`](Self::actual).
///
/// # Examples
///
/// ```ignore
/// use libpna::util::bounded::str::BoundedString;
///
/// let err = BoundedString::<3>::new("hello").unwrap_err();
/// assert_eq!(err.max(), 3);
/// assert_eq!(err.actual(), 5);
/// ```