Skip to main content

ocpi_tariffs/
string.rs

1//! Case Insensitive String. Only printable ASCII allowed.
2
3#[cfg(test)]
4mod test_from_schema;
5
6#[cfg(test)]
7mod test_reasonable_str;
8
9use std::{fmt, ops::Deref};
10
11use crate::{
12    FromSchema as _, LowerSchema,
13    schema::{self, HasElement as _},
14    warning,
15};
16
17/// The warnings that can happen when parsing a case-insensitive string.
18#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
19pub enum Warning {
20    /// There should be no escape codes in a `CiString`.
21    ContainsEscapeCodes,
22
23    /// There should only be printable ASCII bytes in a `CiString`.
24    ContainsNonPrintableASCII,
25
26    /// The length of the string is not equal to the specs constraint.
27    InvalidLengthExact {
28        /// The exact length the spec requires.
29        length: usize,
30    },
31
32    /// The casing of the string is not common practice.
33    ///
34    /// Note: This is not enforced by the string types in this module, but can be used
35    /// by linting code to signal that the casing of a given string is unorthodox.
36    IncorrectCase,
37}
38
39impl fmt::Display for Warning {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        match self {
42            Self::ContainsEscapeCodes => f.write_str("The string contains escape codes."),
43            Self::ContainsNonPrintableASCII => {
44                f.write_str("The string contains non-printable bytes.")
45            }
46            Self::InvalidLengthExact { length } => {
47                write!(f, "The string should be length `{length}`.")
48            }
49            Self::IncorrectCase => {
50                write!(f, "Upper case is preferred")
51            }
52        }
53    }
54}
55
56impl crate::Warning for Warning {
57    fn id(&self) -> warning::Id {
58        match self {
59            Self::ContainsEscapeCodes => warning::Id::from_static("contains_escape_codes"),
60            Self::ContainsNonPrintableASCII => {
61                warning::Id::from_static("contains_non_printable_ascii")
62            }
63            Self::InvalidLengthExact { length: _ } => {
64                warning::Id::from_static("invalid_length_exact")
65            }
66            Self::IncorrectCase => warning::Id::from_static("incorrect_case"),
67        }
68    }
69}
70
71/// String that must decode to exactly `LEN` characters.
72///
73/// Only printable ASCII allowed. Non-printable characters like: Carriage returns, Tabs, Line breaks, etc. are not allowed.
74/// Case insensitivity is not enforced.
75///
76/// See: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/types.asciidoc#types_cistring_type>.
77/// See: <https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/types.md#11-cistring-type>.
78#[derive(Copy, Clone, Debug)]
79pub(crate) struct AsciiExactLen<'buf, const LEN: usize>(&'buf str);
80
81impl<const LEN: usize> Deref for AsciiExactLen<'_, LEN> {
82    type Target = str;
83
84    fn deref(&self) -> &Self::Target {
85        self.0
86    }
87}
88
89impl<const LEN: usize> fmt::Display for AsciiExactLen<'_, LEN> {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        write!(f, "{}", self.0)
92    }
93}
94
95impl<'buf, const LEN: usize> LowerSchema<'buf, schema::Str<'buf>> for AsciiExactLen<'buf, LEN> {
96    type Warning = Warning;
97
98    fn lower_schema(
99        source: &schema::Str<'buf>,
100        warnings: &mut dyn warning::Gather<Warning>,
101    ) -> Result<Self, warning::Error<Warning>> {
102        let s = AsciiPrintable::from_schema(source, warnings)?;
103
104        // The spec's length refers to the characters the value decodes to,
105        // not the bytes it was written with. `\u0054DR` is the three characters `TDR`.
106        let (decoded, _warning) = source.value().decode_escapes();
107        let len = decoded.chars().count();
108
109        if len != LEN {
110            warnings.insert(
111                source.element(),
112                Warning::InvalidLengthExact { length: LEN },
113            );
114        }
115
116        Ok(Self(s.0))
117    }
118}
119
120/// Case Insensitive String. Only printable ASCII allowed. (Non-printable characters like: Carriage returns, Tabs, Line breaks, etc. are not allowed).
121///
122/// See: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/types.asciidoc#types_cistring_type>.
123/// See: <https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/types.md#11-cistring-type>.
124#[derive(Copy, Clone, Debug)]
125pub(crate) struct AsciiPrintable<'buf>(&'buf str);
126
127impl Deref for AsciiPrintable<'_> {
128    type Target = str;
129
130    fn deref(&self) -> &Self::Target {
131        self.0
132    }
133}
134
135impl fmt::Display for AsciiPrintable<'_> {
136    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137        write!(f, "{}", self.0)
138    }
139}
140
141impl<'buf> LowerSchema<'buf, schema::Str<'buf>> for AsciiPrintable<'buf> {
142    type Warning = Warning;
143
144    fn lower_schema(
145        source: &schema::Str<'buf>,
146        warnings: &mut dyn warning::Gather<Warning>,
147    ) -> Result<Self, warning::Error<Warning>> {
148        let elem = source.element();
149        let raw = source.value();
150
151        // The schema confirmed the value is a string, so there is no kind check. A
152        // `CiString` should contain neither escapes nor non-printable ASCII. `lexical_issues`
153        // detects both in a single pass, without decoding into a fresh allocation.
154        let issues = raw.lexical_issues();
155        if issues.escapes {
156            warnings.insert(elem, Warning::ContainsEscapeCodes);
157        }
158        if issues.non_printable_ascii {
159            warnings.insert(elem, Warning::ContainsNonPrintableASCII);
160        }
161
162        Ok(Self(raw.as_unescaped_str()))
163    }
164}
165
166/// The size of the input `str` exceeds the maximum deemed reasonable.
167pub(crate) struct SizeExceedsMax(());
168
169impl std::error::Error for SizeExceedsMax {}
170
171impl fmt::Debug for SizeExceedsMax {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        f.debug_tuple("SizeExceedsMax").finish()
174    }
175}
176
177impl fmt::Display for SizeExceedsMax {
178    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179        write!(
180            f,
181            "The size of the input string exceeds the maximum length of {} megabytes",
182            ReasonableLen::FACTOR
183        )
184    }
185}
186
187/// A `str` that is checked for having a reasonable size.
188#[derive(Copy, Clone)]
189pub(crate) struct ReasonableLen<'buf>(&'buf str);
190
191impl<'buf> ReasonableLen<'buf> {
192    /// One million bytes of information.
193    const MEGA: usize = 1_000_000;
194
195    /// Limit the string to this many megabyte.
196    pub(crate) const FACTOR: usize = 5;
197
198    /// The maximum allowed size for a `str` given to a parse function.
199    ///
200    /// If the input `str` exceeds this size, a [`SizeExceedsMax`] is returned.
201    ///
202    /// NOTE: Currently the largest tariff at `NLENE` is ~440 kilobyte and the largest CDR is ~1.1 megabytes.
203    ///
204    /// NOTE: The motivation for a limit is to avoid parsing unseasonably large JSON objects
205    /// whether supplied through incompetence or maliciousness. Large JSON objects can be constructed
206    /// to have many warnings. This could bog down the function processing the JSON object.
207    pub(crate) const MAX_STR_INPUT_LEN: usize = Self::FACTOR * Self::MEGA;
208
209    /// Create new `ReasonableLen` object.
210    pub(crate) fn new(s: &'buf str) -> Result<ReasonableLen<'buf>, SizeExceedsMax> {
211        if s.len() >= Self::MAX_STR_INPUT_LEN {
212            return Err(SizeExceedsMax(()));
213        }
214
215        Ok(Self(s))
216    }
217
218    /// Unpack the contained `str`.
219    pub(crate) fn into_inner(self) -> &'buf str {
220        self.0
221    }
222}