1use core::fmt;
9
10#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
15#[error("{type_name}: {kind}")]
16pub struct ValueError {
17 pub type_name: &'static str,
19 pub kind: ValueErrorKind,
21}
22
23#[derive(Debug, Clone, PartialEq, Eq)]
25#[non_exhaustive]
26pub enum ValueErrorKind {
27 Length {
29 min: usize,
31 max: usize,
33 actual: usize,
35 },
36 Pattern {
38 expected: &'static str,
40 },
41 Char {
43 index: usize,
45 codepoint: u32,
47 },
48 Sequence {
50 max: u64,
52 },
53 XmlChar {
56 index: usize,
58 codepoint: u32,
60 },
61}
62
63impl fmt::Display for ValueErrorKind {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 match self {
66 Self::Length { min, max, actual } if min == max => {
67 write!(f, "length must be {min}, is {actual}")
68 }
69 Self::Length { min, max, actual } => {
70 write!(f, "length must be {min}..={max}, is {actual}")
71 }
72 Self::Pattern { expected } => write!(f, "must match {expected}"),
73 Self::Char { index, codepoint } => {
74 write!(f, "character U+{codepoint:04X} at position {index} is outside the WBCI character set")
75 }
76 Self::Sequence { max } => write!(f, "sequence number must be at most {max}"),
77 Self::XmlChar { index, codepoint } => {
78 write!(f, "character U+{codepoint:04X} at position {index} is not permitted in XML text")
79 }
80 }
81 }
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub enum Charset {
87 Wbci,
89 WbciMultiline,
91 Xml,
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum Ws {
99 Preserve,
101 Replace,
103 Collapse,
105}
106
107#[must_use]
112pub fn in_wbci_charset(c: char, multiline: bool) -> bool {
113 matches!(c,
114 '\u{09}'
115 | '\u{20}'..='\u{5F}'
116 | '\u{61}'..='\u{7B}'
117 | '\u{7D}' | '\u{7F}' | '\u{A7}'
118 | '\u{B0}'..='\u{B3}'
119 | '\u{C0}'..='\u{D6}'
120 | '\u{D8}'..='\u{F6}'
121 | '\u{F8}'..='\u{FF}')
122 || (multiline && matches!(c, '\n' | '\r'))
123}
124
125fn is_xml_char(c: char) -> bool {
127 matches!(c, '\u{9}' | '\u{A}' | '\u{D}' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..)
128}
129
130pub type Shape = (fn(&str) -> bool, &'static str);
132
133#[derive(Debug, Clone, Copy)]
135pub struct TextSpec {
136 pub name: &'static str,
138 pub min: usize,
140 pub max: usize,
142 pub charset: Charset,
144 pub ws: Ws,
146 pub pattern: Option<Shape>,
148}
149
150impl TextSpec {
151 #[must_use]
153 pub const fn xml(name: &'static str, min: usize, max: usize) -> Self {
154 Self { name, min, max, charset: Charset::Xml, ws: Ws::Preserve, pattern: None }
155 }
156
157 pub fn parse(&self, input: &str) -> Result<String, ValueError> {
163 let value = match self.ws {
164 Ws::Preserve => input.to_owned(),
165 Ws::Replace => input.replace(['\t', '\n', '\r'], " "),
166 Ws::Collapse => {
167 input.split([' ', '\t', '\n', '\r']).filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" ")
168 }
169 };
170 let err = |kind| ValueError { type_name: self.name, kind };
171 for (index, c) in value.chars().enumerate() {
172 let codepoint = u32::from(c);
173 match self.charset {
174 Charset::Wbci | Charset::WbciMultiline => {
175 if !in_wbci_charset(c, self.charset == Charset::WbciMultiline) {
176 return Err(err(ValueErrorKind::Char { index, codepoint }));
177 }
178 }
179 Charset::Xml => {
180 if !(is_xml_char(c) && !c.is_control() || matches!(c, '\t' | '\n' | '\r')) {
181 return Err(err(ValueErrorKind::XmlChar { index, codepoint }));
182 }
183 }
184 }
185 }
186 let len = value.chars().count();
187 if len < self.min || len > self.max {
188 return Err(err(ValueErrorKind::Length { min: self.min, max: self.max, actual: len }));
189 }
190 if let Some((check, expected)) = self.pattern
191 && !check(&value)
192 {
193 return Err(err(ValueErrorKind::Pattern { expected }));
194 }
195 Ok(value)
196 }
197}
198
199#[must_use]
201pub fn digits(s: &str, n: usize, m: usize) -> bool {
202 (n..=m).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_digit())
203}
204
205#[must_use]
207pub fn upper_alnum(s: &str, n: usize, m: usize) -> bool {
208 (n..=m).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_digit() || b.is_ascii_uppercase())
209}
210
211#[macro_export]
216macro_rules! text_type {
217 (
218 $(#[$meta:meta])*
219 $name:ident, $spec:expr, $redact:tt
220 ) => {
221 $(#[$meta])*
222 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
223 pub struct $name(String);
224
225 impl $name {
226 pub(crate) const SPEC: $crate::text::TextSpec = $spec;
227
228 pub fn new(value: impl AsRef<str>) -> Result<Self, $crate::ValueError> {
234 Self::SPEC.parse(value.as_ref()).map(Self)
235 }
236
237 #[must_use]
239 pub fn as_str(&self) -> &str {
240 &self.0
241 }
242 }
243
244 impl core::str::FromStr for $name {
245 type Err = $crate::ValueError;
246 fn from_str(s: &str) -> Result<Self, Self::Err> {
247 Self::new(s)
248 }
249 }
250
251 impl TryFrom<&str> for $name {
252 type Error = $crate::ValueError;
253 fn try_from(s: &str) -> Result<Self, Self::Error> {
254 Self::new(s)
255 }
256 }
257
258 impl AsRef<str> for $name {
259 fn as_ref(&self) -> &str {
260 &self.0
261 }
262 }
263
264 impl core::fmt::Display for $name {
265 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
266 f.write_str(&self.0)
267 }
268 }
269
270 $crate::text_type!(@debug $name, $redact);
271 };
272 (@debug $name:ident, redact) => {
273 impl core::fmt::Debug for $name {
274 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
275 write!(f, concat!(stringify!($name), "(<redacted, {} chars>)"), self.0.chars().count())
276 }
277 }
278 };
279 (@debug $name:ident, plain) => {
280 impl core::fmt::Debug for $name {
281 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
282 write!(f, concat!(stringify!($name), "({:?})"), self.0)
283 }
284 }
285 };
286}
287
288#[macro_export]
290macro_rules! code_enum {
291 ($(#[$meta:meta])* $name:ident { $($(#[$vmeta:meta])* $variant:ident = $code:literal),+ $(,)? }) => {
292 $(#[$meta])*
293 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
294 pub enum $name {
295 $($(#[$vmeta])* $variant),+
296 }
297
298 impl $name {
299 pub const ALL: &'static [$name] = &[$(Self::$variant),+];
301
302 #[must_use]
304 pub const fn as_str(self) -> &'static str {
305 match self { $(Self::$variant => $code),+ }
306 }
307
308 #[must_use]
310 pub fn from_code(s: &str) -> Option<Self> {
311 match s { $($code => Some(Self::$variant),)+ _ => None }
312 }
313 }
314
315 impl core::fmt::Display for $name {
316 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
317 f.write_str(self.as_str())
318 }
319 }
320 };
321}
322
323#[cfg(test)]
324mod tests {
325 use super::*;
326
327 const NAME: TextSpec =
328 TextSpec { name: "Vorname", min: 1, max: 30, charset: Charset::Wbci, ws: Ws::Collapse, pattern: None };
329
330 #[test]
331 fn collapse_then_check() {
332 assert_eq!(NAME.parse(" Anna \t Marie ").as_deref(), Ok("Anna Marie"));
333 }
334
335 #[test]
336 fn umlauts_and_symbols_are_in_the_charset() {
337 assert!(NAME.parse("Jürgen-Øle § °").is_ok());
338 }
339
340 #[test]
342 fn control_character_is_refused_with_position() {
343 let err = NAME.parse("An\u{7}na").unwrap_err();
344 assert_eq!(err.kind, ValueErrorKind::Char { index: 2, codepoint: 7 });
345 assert_eq!(err.to_string(), "Vorname: character U+0007 at position 2 is outside the WBCI character set");
346 }
347
348 #[test]
349 fn characters_outside_latin1_and_excluded_ascii_are_refused() {
350 for bad in ["€", "`", "|", "~", "Ł", "\u{202E}"] {
351 assert!(NAME.parse(bad).is_err(), "{bad:?}");
352 }
353 }
354
355 #[test]
356 fn multiline_admits_line_breaks() {
357 let spec = TextSpec { charset: Charset::WbciMultiline, ws: Ws::Preserve, ..NAME };
358 assert!(spec.parse("a\r\nb").is_ok());
359 assert!(NAME.parse("a\u{0}b").is_err());
360 }
361
362 #[test]
363 fn length_is_counted_in_characters() {
364 let thirty = "ä".repeat(30);
365 assert!(NAME.parse(&thirty).is_ok());
366 let err = NAME.parse(&"ä".repeat(31)).unwrap_err();
367 assert_eq!(err.kind, ValueErrorKind::Length { min: 1, max: 30, actual: 31 });
368 assert!(NAME.parse(" ").is_err());
369 }
370
371 #[test]
372 fn xml_charset_admits_any_text_but_controls() {
373 let spec = TextSpec::xml("Freitext", 1, 30);
374 assert!(spec.parse("€ | ~ Ł 漢字\n").is_ok());
375 let err = spec.parse("a\u{1}").unwrap_err();
376 assert_eq!(err.kind, ValueErrorKind::XmlChar { index: 1, codepoint: 1 });
377 assert_eq!(err.to_string(), "Freitext: character U+0001 at position 1 is not permitted in XML text");
378 assert!(spec.parse("\u{FFFE}").is_err());
379 }
380}