utopia_validators/
text.rs1use php_std::{mb, pcre};
9
10use crate::decimal;
11
12pub fn is_blank(value: &[u8]) -> bool {
18 !matches!(
19 pcre::preg_match_bare(br"/[^\p{Z}\p{Cf}\s]/u", value),
20 Ok(result) if result.value == pcre::Value::Int(1)
21 )
22}
23
24pub fn chars(value: &[u8]) -> i64 {
26 i64::try_from(mb::mb_strlen(value)).unwrap_or(i64::MAX)
27}
28
29pub fn text_length(value: &[u8], min: i64, length: i64) -> bool {
33 let chars = chars(value);
34 chars >= min && !(chars > length && length != 0)
35}
36
37pub fn text_description(
42 length: i64,
43 min: i64,
44 allow_list: Option<&[u8]>,
45 require_non_blank: bool,
46 message: &mut Vec<u8>,
47) {
48 message.extend_from_slice(b"Value must be a valid string");
49 if min == length {
50 message.extend_from_slice(b" and exactly ");
51 decimal(length, message);
52 message.extend_from_slice(b" chars");
53 } else {
54 if min != 0 {
55 message.extend_from_slice(b" and at least ");
56 decimal(min, message);
57 message.extend_from_slice(b" chars");
58 }
59 if length != 0 {
60 message.extend_from_slice(b" and no longer than ");
61 decimal(length, message);
62 message.extend_from_slice(b" chars");
63 }
64 }
65 if let Some(list) = allow_list {
66 message.extend_from_slice(b" and only consist of '");
67 message.extend_from_slice(list);
68 message.extend_from_slice(b"' chars");
69 }
70 if require_non_blank {
71 message.extend_from_slice(b" and not be blank");
72 }
73}
74
75pub fn identifier(value: &[u8]) -> bool {
80 match value.split_first() {
81 Some((first, rest)) => {
82 (first.is_ascii_alphabetic() || *first == b'_')
83 && rest.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'_')
84 }
85 None => false,
86 }
87}
88
89pub fn identifier_description(length: i64, description: &mut Vec<u8>) {
91 description
92 .extend_from_slice(b"Value must contain only letters, digits and underscores and must not start with a digit");
93 if length != 0 {
94 description.extend_from_slice(b", and be at most ");
95 decimal(length, description);
96 description.extend_from_slice(b" chars");
97 }
98 description.push(b'.');
99}
100
101pub fn ascii_lower(value: &[u8]) -> Vec<u8> {
103 value.to_ascii_lowercase()
104}
105
106pub const WHITE_LIST_DESCRIPTION: (&str, &str) = ("Value must be one of (", ")");
108
109pub fn white_list_description(list: &[u8], message: &mut Vec<u8>) {
111 message.extend_from_slice(WHITE_LIST_DESCRIPTION.0.as_bytes());
112 message.extend_from_slice(list);
113 message.extend_from_slice(WHITE_LIST_DESCRIPTION.1.as_bytes());
114}
115
116pub fn lower(value: &[u8]) -> Vec<u8> {
121 mb::mb_strtolower(value)
122}
123
124pub fn contains(haystack: &[u8], needle: &[u8]) -> bool {
126 needle.is_empty() || haystack.windows(needle.len()).any(|window| window == needle)
127}
128
129pub fn contains_description(patterns: &[u8], strict: bool, message: &mut Vec<u8>) {
131 message.extend_from_slice(b"Value must contain one of (");
132 message.extend_from_slice(patterns);
133 message.push(b')');
134 message.extend_from_slice(if strict { b" (case-sensitive)" } else { b" (case-insensitive)" });
135}
136
137pub const LABEL_MAX_LENGTH: i64 = 63;
139
140pub fn label(value: &[u8]) -> bool {
144 if value.is_empty() || value.len() > LABEL_MAX_LENGTH as usize || value.starts_with(b"-") || value.ends_with(b"-") {
145 return false;
146 }
147 let rest: Vec<u8> = value.iter().copied().filter(|b| *b != b'-').collect();
148 !rest.is_empty() && rest.iter().all(u8::is_ascii_alphanumeric) && !value.iter().any(u8::is_ascii_uppercase)
149}
150
151pub const LABEL_DESCRIPTION: &str =
153 "Value must be 1 to 63 lowercase letters, digits and hyphens, and must not start or end with a hyphen.";
154
155#[cfg(test)]
156mod tests {
157 use super::*;
158
159 #[test]
160 fn blank() {
161 assert!(is_blank(b""));
162 assert!(is_blank(b" \t\n\r\x0b\x0c"));
163 assert!(is_blank("\u{00a0}\u{2028}\u{200b}\u{feff}".as_bytes()));
164 assert!(!is_blank(b" a "));
165 assert!(is_blank(b"a\xff"));
167 }
168
169 #[test]
170 fn lengths() {
171 assert!(text_length("héllo".as_bytes(), 5, 5));
172 assert!(!text_length("héllo".as_bytes(), 6, 0));
173 assert!(text_length(b"", 0, 0));
174 assert!(!text_length(b"abc", 1, 2));
175 assert!(text_length(b"abc", 1, 0));
176 }
177
178 #[test]
179 fn descriptions() {
180 fn described(describe: impl FnOnce(&mut Vec<u8>)) -> Vec<u8> {
181 let mut out = Vec::new();
182 describe(&mut out);
183 out
184 }
185 assert_eq!(
186 described(|out| text_description(10, 10, None, false, out)),
187 b"Value must be a valid string and exactly 10 chars"
188 );
189 assert_eq!(
190 described(|out| text_description(10, 1, Some(b"a, b"), true, out)),
191 b"Value must be a valid string and at least 1 chars and no longer than 10 chars and only consist of 'a, b' chars and not be blank"
192 );
193 assert_eq!(
194 described(|out| text_description(0, 0, None, false, out)),
195 b"Value must be a valid string and exactly 0 chars"
196 );
197 assert_eq!(
198 described(|out| text_description(-5, 2, None, false, out)),
199 b"Value must be a valid string and at least 2 chars and no longer than -5 chars"
200 );
201 assert_eq!(
202 described(|out| identifier_description(0, out)),
203 b"Value must contain only letters, digits and underscores and must not start with a digit."
204 );
205 assert_eq!(
206 described(|out| identifier_description(64, out)),
207 b"Value must contain only letters, digits and underscores and must not start with a digit, and be at most 64 chars."
208 );
209 assert_eq!(
210 described(|out| contains_description(b"a, b", false, out)),
211 b"Value must contain one of (a, b) (case-insensitive)"
212 );
213 assert_eq!(described(|out| white_list_description(b"a, b", out)), b"Value must be one of (a, b)");
214 assert_eq!(
215 LABEL_DESCRIPTION,
216 format!(
217 "Value must be 1 to {LABEL_MAX_LENGTH} lowercase letters, digits and hyphens, and must not start or end with a hyphen."
218 )
219 );
220 }
221
222 #[test]
223 fn identifiers() {
224 assert!(identifier(b"_a1"));
225 assert!(identifier(b"A"));
226 assert!(!identifier(b"1a"));
227 assert!(!identifier(b"a-b"));
228 assert!(!identifier(b"a\n"));
229 assert!(!identifier("é".as_bytes()));
230 assert!(!identifier(b""));
231 }
232
233 #[test]
234 fn labels() {
235 assert!(label(b"a-1"));
236 assert!(!label(b"A"));
237 assert!(!label(b"-a"));
238 assert!(!label(b"a-"));
239 assert!(!label(b"a.b"));
240 assert!(!label(&[b'a'; 64]));
241 assert!(label(&[b'a'; 63]));
242 assert!(!label(b""));
243 }
244
245 #[test]
246 fn contains_needles() {
247 assert!(contains(b"abc", b""));
248 assert!(contains(b"abc", b"bc"));
249 assert!(!contains(b"", b"a"));
250 assert_eq!(lower("ÀB\u{03a3}".as_bytes()), "àbς".as_bytes());
251 }
252}