1#[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#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
19pub enum Warning {
20 ContainsEscapeCodes,
22
23 ContainsNonPrintableASCII,
25
26 InvalidLengthExact {
28 length: usize,
30 },
31
32 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#[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 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#[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 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
166pub(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#[derive(Copy, Clone)]
189pub(crate) struct ReasonableLen<'buf>(&'buf str);
190
191impl<'buf> ReasonableLen<'buf> {
192 const MEGA: usize = 1_000_000;
194
195 pub(crate) const FACTOR: usize = 5;
197
198 pub(crate) const MAX_STR_INPUT_LEN: usize = Self::FACTOR * Self::MEGA;
208
209 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 pub(crate) fn into_inner(self) -> &'buf str {
220 self.0
221 }
222}