Skip to main content

tightbeam/utils/urn/
error.rs

1//! URN validation error types
2
3#![cfg_attr(not(feature = "std"), no_std)]
4
5#[cfg(not(feature = "std"))]
6extern crate alloc;
7
8#[cfg(not(feature = "std"))]
9use alloc::string::String;
10
11#[cfg(feature = "derive")]
12use crate::Errorizable;
13
14#[cfg(not(feature = "derive"))]
15use core::fmt;
16
17use crate::utils::urn::builders::spec::Pattern;
18
19/// Errors that can occur during URN validation and construction
20#[cfg_attr(feature = "derive", derive(Errorizable))]
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum UrnValidationError {
23	/// A required field is missing
24	#[cfg_attr(feature = "derive", error("Required field missing: {0}"))]
25	RequiredFieldMissing(&'static str),
26
27	/// A field has an invalid format
28	#[cfg_attr(
29		feature = "derive",
30		error("Invalid format for field '{field}': expected pattern {pattern:?}")
31	)]
32	InvalidFormat { field: &'static str, pattern: Option<Pattern> },
33
34	/// A forbidden field is present
35	#[cfg_attr(feature = "derive", error("Forbidden field present: {0}"))]
36	ForbiddenFieldPresent(&'static str),
37
38	/// NID does not match the spec's expected NID
39	#[cfg_attr(feature = "derive", error("NID does not match spec"))]
40	NidMismatch,
41
42	/// NID length is invalid (must be 2-32 characters)
43	#[cfg_attr(feature = "derive", error("Invalid NID length: must be 2-32 characters"))]
44	InvalidNidLength,
45
46	/// NID must start with a letter
47	#[cfg_attr(feature = "derive", error("Invalid NID: must start with a letter"))]
48	InvalidNidStart,
49
50	/// NID contains invalid characters (must be alphanumeric and hyphens only)
51	#[cfg_attr(
52		feature = "derive",
53		error("Invalid NID characters: must be alphanumeric and hyphens only")
54	)]
55	InvalidNidCharacters,
56}
57
58#[cfg(not(feature = "derive"))]
59impl fmt::Display for UrnValidationError {
60	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61		match self {
62			Self::RequiredFieldMissing(field) => write!(f, "Required field missing: {field}"),
63			Self::InvalidFormat { field, pattern } => {
64				if let Some(p) = pattern {
65					write!(f, "Invalid format for field '{field}': expected pattern {}", p.pattern_str())
66				} else {
67					write!(f, "Invalid format for field '{field}'")
68				}
69			}
70			Self::ForbiddenFieldPresent(field) => write!(f, "Forbidden field present: {field}"),
71			Self::NidMismatch => write!(f, "NID does not match spec"),
72			Self::InvalidNidLength => write!(f, "Invalid NID length: must be 2-32 characters"),
73			Self::InvalidNidStart => write!(f, "Invalid NID: must start with a letter"),
74			Self::InvalidNidCharacters => {
75				write!(f, "Invalid NID characters: must be alphanumeric and hyphens only")
76			}
77		}
78	}
79}
80
81#[cfg(all(feature = "std", not(feature = "derive")))]
82impl std::error::Error for UrnValidationError {}