nodedb_types/id/error.rs
1// SPDX-License-Identifier: Apache-2.0
2
3//! Shared error type for string-based identifier validation.
4
5/// Maximum byte length for all string ID types.
6///
7/// IDs exceeding this are rejected by `try_new` to bound allocations and
8/// prevent key-space abuse. The cap is generous enough for any realistic
9/// identifier (UUIDs, URNs, DNS-qualified names, etc.).
10pub const ID_MAX_LEN: usize = 1024;
11
12/// Error returned when constructing a string-based ID type fails validation.
13#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
14pub enum IdError {
15 /// The supplied string was empty.
16 #[error("ID must not be empty")]
17 Empty,
18
19 /// The supplied string exceeded the maximum allowed byte length.
20 #[error("ID is too long: {len} bytes (max {max})")]
21 TooLong {
22 /// Actual byte length of the rejected string.
23 len: usize,
24 /// Maximum allowed byte length.
25 max: usize,
26 },
27
28 /// The supplied string contained a NUL byte (`\0`), which is disallowed
29 /// because storage backends treat NUL as a key terminator.
30 #[error("ID must not contain NUL bytes")]
31 ContainsNul,
32
33 /// A requested ID length falls outside the allowed range for the generator.
34 #[error("id length {requested} out of range [{min}, {max}]")]
35 LengthOutOfRange {
36 /// The length that was requested.
37 requested: usize,
38 /// The minimum allowed length.
39 min: usize,
40 /// The maximum allowed length.
41 max: usize,
42 },
43}
44
45/// Validate a candidate ID string against the shared rules.
46///
47/// Returns `Ok(())` if the string passes all checks, or the first
48/// failing `IdError` variant otherwise.
49pub(super) fn validate(id: &str) -> Result<(), IdError> {
50 if id.is_empty() {
51 return Err(IdError::Empty);
52 }
53 if id.len() > ID_MAX_LEN {
54 return Err(IdError::TooLong {
55 len: id.len(),
56 max: ID_MAX_LEN,
57 });
58 }
59 if id.contains('\0') {
60 return Err(IdError::ContainsNul);
61 }
62 Ok(())
63}