-
Notifications
You must be signed in to change notification settings - Fork 253
/
string.rs
289 lines (257 loc) · 9.24 KB
/
string.rs
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
use pyo3::intern;
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyString};
use pyo3::IntoPyObjectExt;
use regex::Regex;
use crate::build_tools::{is_strict, py_schema_error_type, schema_or_config, schema_or_config_same};
use crate::errors::{ErrorType, ValError, ValResult};
use crate::input::Input;
use crate::tools::SchemaDict;
use super::{BuildValidator, CombinedValidator, DefinitionsBuilder, ValidationState, Validator};
#[derive(Debug)]
pub struct StrValidator {
strict: bool,
coerce_numbers_to_str: bool,
}
impl BuildValidator for StrValidator {
const EXPECTED_TYPE: &'static str = "str";
fn build(
schema: &Bound<'_, PyDict>,
config: Option<&Bound<'_, PyDict>>,
_definitions: &mut DefinitionsBuilder<CombinedValidator>,
) -> PyResult<CombinedValidator> {
let con_str_validator = StrConstrainedValidator::build(schema, config)?;
if con_str_validator.has_constraints_set() {
Ok(con_str_validator.into())
} else {
Ok(Self {
strict: con_str_validator.strict,
coerce_numbers_to_str: con_str_validator.coerce_numbers_to_str,
}
.into())
}
}
}
impl_py_gc_traverse!(StrValidator {});
impl Validator for StrValidator {
fn validate<'py>(
&self,
py: Python<'py>,
input: &(impl Input<'py> + ?Sized),
state: &mut ValidationState<'_, 'py>,
) -> ValResult<PyObject> {
input
.validate_str(state.strict_or(self.strict), self.coerce_numbers_to_str)
.and_then(|val_match| {
Ok(val_match
.unpack(state)
.as_py_string(py, state.cache_str())
.into_py_any(py)?)
})
}
fn get_name(&self) -> &str {
Self::EXPECTED_TYPE
}
}
/// Any new properties set here must be reflected in `has_constraints_set`
#[derive(Debug, Clone, Default)]
pub struct StrConstrainedValidator {
strict: bool,
pattern: Option<Pattern>,
max_length: Option<usize>,
min_length: Option<usize>,
strip_whitespace: bool,
to_lower: bool,
to_upper: bool,
coerce_numbers_to_str: bool,
}
impl_py_gc_traverse!(StrConstrainedValidator {});
impl Validator for StrConstrainedValidator {
fn validate<'py>(
&self,
py: Python<'py>,
input: &(impl Input<'py> + ?Sized),
state: &mut ValidationState<'_, 'py>,
) -> ValResult<PyObject> {
let either_str = input
.validate_str(state.strict_or(self.strict), self.coerce_numbers_to_str)?
.unpack(state);
let cow = either_str.as_cow()?;
let mut str = cow.as_ref();
if self.strip_whitespace {
str = str.trim();
}
let str_len: Option<usize> = if self.min_length.is_some() | self.max_length.is_some() {
Some(str.chars().count())
} else {
None
};
if let Some(min_length) = self.min_length {
if str_len.unwrap() < min_length {
return Err(ValError::new(
ErrorType::StringTooShort {
min_length,
context: None,
},
input,
));
}
}
if let Some(max_length) = self.max_length {
if str_len.unwrap() > max_length {
return Err(ValError::new(
ErrorType::StringTooLong {
max_length,
context: None,
},
input,
));
}
}
if let Some(pattern) = &self.pattern {
if !pattern.is_match(py, str)? {
return Err(ValError::new(
ErrorType::StringPatternMismatch {
pattern: pattern.pattern.clone(),
context: None,
},
input,
));
}
}
let py_string = if self.to_lower {
state.maybe_cached_str(py, &str.to_lowercase())
} else if self.to_upper {
state.maybe_cached_str(py, &str.to_uppercase())
} else if self.strip_whitespace {
state.maybe_cached_str(py, str)
} else {
// we haven't modified the string, return the original as it might be a PyString
either_str.as_py_string(py, state.cache_str())
};
Ok(py_string.into_py_any(py)?)
}
fn get_name(&self) -> &str {
"constrained-str"
}
}
impl StrConstrainedValidator {
fn build(schema: &Bound<'_, PyDict>, config: Option<&Bound<'_, PyDict>>) -> PyResult<Self> {
let py = schema.py();
let pattern = schema
.get_as(intern!(py, "pattern"))?
.map(|s| {
let regex_engine = schema_or_config::<Bound<'_, PyString>>(
schema,
config,
intern!(py, "regex_engine"),
intern!(py, "regex_engine"),
)?;
let regex_engine = regex_engine
.as_ref()
.map(|s| s.to_str())
.transpose()?
.unwrap_or(RegexEngine::RUST_REGEX);
Pattern::compile(s, regex_engine)
})
.transpose()?;
let min_length: Option<usize> =
schema_or_config(schema, config, intern!(py, "min_length"), intern!(py, "str_min_length"))?;
let max_length: Option<usize> =
schema_or_config(schema, config, intern!(py, "max_length"), intern!(py, "str_max_length"))?;
let strip_whitespace: bool = schema_or_config(
schema,
config,
intern!(py, "strip_whitespace"),
intern!(py, "str_strip_whitespace"),
)?
.unwrap_or(false);
let to_lower: bool =
schema_or_config(schema, config, intern!(py, "to_lower"), intern!(py, "str_to_lower"))?.unwrap_or(false);
let to_upper: bool =
schema_or_config(schema, config, intern!(py, "to_upper"), intern!(py, "str_to_upper"))?.unwrap_or(false);
let coerce_numbers_to_str: bool =
schema_or_config_same(schema, config, intern!(py, "coerce_numbers_to_str"))?.unwrap_or(false);
Ok(Self {
strict: is_strict(schema, config)?,
pattern,
min_length,
max_length,
strip_whitespace,
to_lower,
to_upper,
coerce_numbers_to_str,
})
}
// whether any of the constraints/customisations are actually enabled
// except strict and coerce_numbers_to_str which can be set on StrValidator
fn has_constraints_set(&self) -> bool {
self.pattern.is_some()
|| self.max_length.is_some()
|| self.min_length.is_some()
|| self.strip_whitespace
|| self.to_lower
|| self.to_upper
}
}
#[derive(Debug, Clone)]
struct Pattern {
pattern: String,
engine: RegexEngine,
}
#[derive(Debug, Clone)]
enum RegexEngine {
RustRegex(Regex),
PythonRe(PyObject),
}
impl RegexEngine {
const RUST_REGEX: &'static str = "rust-regex";
const PYTHON_RE: &'static str = "python-re";
}
impl Pattern {
fn extract_pattern_str(pattern: &Bound<'_, PyAny>) -> PyResult<String> {
if pattern.is_instance_of::<PyString>() {
Ok(pattern.to_string())
} else {
pattern
.getattr("pattern")
.and_then(|attr| attr.extract::<String>())
.map_err(|_| py_schema_error_type!("Invalid pattern, must be str or re.Pattern: {}", pattern))
}
}
fn compile(pattern: Bound<'_, PyAny>, engine: &str) -> PyResult<Self> {
let pattern_str = Self::extract_pattern_str(&pattern)?;
let py = pattern.py();
let re_module = py.import(intern!(py, "re"))?;
let re_compile = re_module.getattr(intern!(py, "compile"))?;
let re_pattern = re_module.getattr(intern!(py, "Pattern"))?;
if pattern.is_instance(&re_pattern)? {
// if the pattern is already a compiled regex object, we default to using the python re engine
// so that any flags, etc. are preserved
Ok(Self {
pattern: pattern_str,
engine: RegexEngine::PythonRe(pattern.to_object(py)),
})
} else {
let engine = match engine {
RegexEngine::RUST_REGEX => {
RegexEngine::RustRegex(Regex::new(&pattern_str).map_err(|e| py_schema_error_type!("{}", e))?)
}
RegexEngine::PYTHON_RE => RegexEngine::PythonRe(re_compile.call1((pattern,))?.into()),
_ => return Err(py_schema_error_type!("Invalid regex engine: {}", engine)),
};
Ok(Self {
pattern: pattern_str,
engine,
})
}
}
fn is_match(&self, py: Python<'_>, target: &str) -> PyResult<bool> {
match &self.engine {
RegexEngine::RustRegex(regex) => Ok(regex.is_match(target)),
RegexEngine::PythonRe(py_regex) => {
Ok(!py_regex.call_method1(py, intern!(py, "search"), (target,))?.is_none(py))
}
}
}
}