Skip to main content

carrier_core/
text.rs

1//! Lexical facets of the carrier schemas: the permitted character set, whitespace handling and
2//! lengths, and the macros that turn them into newtypes and code enumerations.
3//!
4//! Sources: XSD `wbci-type-simple.xsd` (V2.00, schema version 01.00.02),
5//! `ErlaubterZeichenBereichType` and `ErlaubterZeichenBereichMehrzeiligType`; the S/PRI schema
6//! 4.00.03 restricts `xsd:string` by length only ([`Charset::Xml`]).
7
8use core::fmt;
9
10/// A value that does not satisfy its schema type.
11///
12/// The error never contains the rejected text: values may be personal data, and errors end
13/// up in logs. It names the type, the facet and, for a character, its position.
14#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
15#[error("{type_name}: {kind}")]
16pub struct ValueError {
17    /// The schema type, e.g. `Nachname`.
18    pub type_name: &'static str,
19    /// Which facet was violated.
20    pub kind: ValueErrorKind,
21}
22
23/// The facet a [`ValueError`] reports.
24#[derive(Debug, Clone, PartialEq, Eq)]
25#[non_exhaustive]
26pub enum ValueErrorKind {
27    /// Too short or too long, counted in characters as XSD does.
28    Length {
29        /// Minimum length.
30        min: usize,
31        /// Maximum length.
32        max: usize,
33        /// Actual length.
34        actual: usize,
35    },
36    /// The value does not have the required shape.
37    Pattern {
38        /// The shape, in the XSD's notation.
39        expected: &'static str,
40    },
41    /// A character outside the WBCI character set.
42    Char {
43        /// Zero-based character position.
44        index: usize,
45        /// The Unicode scalar value.
46        codepoint: u32,
47    },
48    /// A sequence number too large for nine digits.
49    Sequence {
50        /// The largest permitted number.
51        max: u64,
52    },
53    /// A character that XML text may not carry (a control character other than tab, line feed
54    /// and carriage return, or a non-character).
55    XmlChar {
56        /// Zero-based character position.
57        index: usize,
58        /// The Unicode scalar value.
59        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/// Which characters a type admits.
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub enum Charset {
87    /// WBCI `ErlaubterZeichenBereichType`.
88    Wbci,
89    /// WBCI `ErlaubterZeichenBereichMehrzeiligType`: adds line feed and carriage return.
90    WbciMultiline,
91    /// `xsd:string` without further restriction: XML characters, no control characters
92    /// other than tab, line feed and carriage return.
93    Xml,
94}
95
96/// The XSD `whiteSpace` facet.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum Ws {
99    /// Kept as written.
100    Preserve,
101    /// Tab, line feed and carriage return become spaces.
102    Replace,
103    /// `Replace`, then runs of spaces become one and the ends are trimmed.
104    Collapse,
105}
106
107/// Whether `c` is in WBCI's `ErlaubterZeichenBereichType` (with line breaks if `multiline`).
108///
109/// The pattern admits U+007F although the schema's prose list does not name it; peers
110/// validate against the pattern, so this follows the pattern (an interpretation).
111#[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
125/// Whether `c` may appear in an XML 1.0 document at all.
126fn 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
130/// A shape check and its description in the XSD's notation.
131pub type Shape = (fn(&str) -> bool, &'static str);
132
133/// The lexical rules of one schema type.
134#[derive(Debug, Clone, Copy)]
135pub struct TextSpec {
136    /// The type's name in errors.
137    pub name: &'static str,
138    /// Minimum length in characters.
139    pub min: usize,
140    /// Maximum length in characters.
141    pub max: usize,
142    /// The permitted characters.
143    pub charset: Charset,
144    /// The whitespace facet.
145    pub ws: Ws,
146    /// An extra shape check and its description, for patterned types.
147    pub pattern: Option<Shape>,
148}
149
150impl TextSpec {
151    /// A length-only `xsd:string` restriction: XML characters, whitespace preserved.
152    #[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    /// Normalises whitespace as the facet says, then checks characters, length and shape.
158    ///
159    /// # Errors
160    ///
161    /// [`ValueError`] naming the first violated facet.
162    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/// `n` to `m` ASCII digits.
200#[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/// `[0-9A-Z]{n,m}`.
206#[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/// Declares a newtype over `String` with a [`TextSpec`].
212///
213/// `redact` makes `Debug` print only the length: the type may hold personal data. The
214/// invoking crate must export `ValueError` at its root.
215#[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            /// Parses a value, applying the schema's whitespace facet first.
229            ///
230            /// # Errors
231            ///
232            /// [`ValueError`](crate::ValueError) naming the violated facet.
233            pub fn new(value: impl AsRef<str>) -> Result<Self, $crate::ValueError> {
234                Self::SPEC.parse(value.as_ref()).map(Self)
235            }
236
237            /// The value as written on the wire.
238            #[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/// Declares a `Copy` enum of schema codes with `as_str`, `from_code` and `Display`.
289#[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            /// Every value, in the schema's order.
300            pub const ALL: &'static [$name] = &[$(Self::$variant),+];
301
302            /// The code on the wire.
303            #[must_use]
304            pub const fn as_str(self) -> &'static str {
305                match self { $(Self::$variant => $code),+ }
306            }
307
308            /// Parses the code on the wire.
309            #[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    // wbci-switch/SR-004: a control character is refused, naming character and position.
341    #[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}