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