1use std::cmp::Ordering;
4use std::collections::HashSet;
5use std::hash::Hash;
6
7use crate::context::ValidationContext;
8use crate::error::FieldIssue;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum LengthUnit {
12 Chars,
13 Bytes,
14 Utf16,
15}
16
17impl LengthUnit {
18 pub fn parse(value: &str) -> Option<Self> {
19 match value {
20 "chars" => Some(Self::Chars),
21 "bytes" => Some(Self::Bytes),
22 "utf16" => Some(Self::Utf16),
23 _ => None,
24 }
25 }
26
27 pub fn as_str(self) -> &'static str {
28 match self {
29 Self::Chars => "chars",
30 Self::Bytes => "bytes",
31 Self::Utf16 => "utf16",
32 }
33 }
34
35 fn len(self, value: &str) -> usize {
36 match self {
37 Self::Chars => value.chars().count(),
38 Self::Bytes => value.len(),
39 Self::Utf16 => value.encode_utf16().count(),
40 }
41 }
42}
43
44pub fn string_len(
45 field: &str,
46 value: &str,
47 min: Option<usize>,
48 max: Option<usize>,
49 unit: LengthUnit,
50) -> Result<(), FieldIssue> {
51 let len = unit.len(value);
52 if let Some(min) = min {
53 if len < min {
54 return Err(FieldIssue::new(
55 field,
56 "STRING_TOO_SHORT",
57 format!("must be at least {min} {}", unit.as_str()),
58 ));
59 }
60 }
61 if let Some(max) = max {
62 if len > max {
63 return Err(FieldIssue::new(
64 field,
65 "STRING_TOO_LONG",
66 format!("must be at most {max} {}", unit.as_str()),
67 ));
68 }
69 }
70 Ok(())
71}
72
73pub fn non_empty(field: &str, value: &str) -> Result<(), FieldIssue> {
74 if value.is_empty() {
75 Err(FieldIssue::new(
76 field,
77 "STRING_EMPTY",
78 "must not be empty",
79 ))
80 } else {
81 Ok(())
82 }
83}
84
85pub fn ascii(field: &str, value: &str) -> Result<(), FieldIssue> {
86 if value.is_ascii() {
87 Ok(())
88 } else {
89 Err(FieldIssue::new(
90 field,
91 "STRING_NOT_ASCII",
92 "must be ASCII",
93 ))
94 }
95}
96
97pub fn alphanumeric(field: &str, value: &str) -> Result<(), FieldIssue> {
98 if value.chars().all(|ch| ch.is_ascii_alphanumeric()) {
99 Ok(())
100 } else {
101 Err(FieldIssue::new(
102 field,
103 "STRING_NOT_ALPHANUMERIC",
104 "must be alphanumeric",
105 ))
106 }
107}
108
109pub fn digits(field: &str, value: &str) -> Result<(), FieldIssue> {
110 if value.bytes().all(|b| b.is_ascii_digit()) {
111 Ok(())
112 } else {
113 Err(FieldIssue::new(
114 field,
115 "STRING_NOT_DIGITS",
116 "must be digits only",
117 ))
118 }
119}
120
121pub fn starts_with(field: &str, value: &str, prefix: &str) -> Result<(), FieldIssue> {
122 if value.starts_with(prefix) {
123 Ok(())
124 } else {
125 Err(FieldIssue::new(
126 field,
127 "STRING_PREFIX",
128 format!("must start with {prefix}"),
129 ))
130 }
131}
132
133pub fn ends_with(field: &str, value: &str, suffix: &str) -> Result<(), FieldIssue> {
134 if value.ends_with(suffix) {
135 Ok(())
136 } else {
137 Err(FieldIssue::new(
138 field,
139 "STRING_SUFFIX",
140 format!("must end with {suffix}"),
141 ))
142 }
143}
144
145pub fn one_of(field: &str, value: &str, allowed: &[&str]) -> Result<(), FieldIssue> {
146 if allowed.contains(&value) {
147 Ok(())
148 } else {
149 Err(FieldIssue::new(
150 field,
151 "STRING_ONE_OF",
152 format!("must be one of {allowed:?}"),
153 ))
154 }
155}
156
157pub trait NumericValue: Copy {
159 fn check_bounds(
160 self,
161 field: &str,
162 min: Option<f64>,
163 max: Option<f64>,
164 gt: Option<f64>,
165 lt: Option<f64>,
166 multiple_of: Option<i64>,
167 ) -> Result<(), FieldIssue>;
168
169 fn check_positive(self, field: &str) -> Result<(), FieldIssue>;
170 fn check_non_negative(self, field: &str) -> Result<(), FieldIssue>;
171 fn check_finite(self, field: &str) -> Result<(), FieldIssue>;
172}
173
174pub(crate) fn cmp_i128_f64(value: i128, bound: f64) -> Option<Ordering> {
176 if bound.is_nan() {
177 return None;
178 }
179 const I128_MIN_F64: f64 = -170_141_183_460_469_231_731_687_303_715_884_105_728.0; const I128_UPPER_EXCL_F64: f64 = 170_141_183_460_469_231_731_687_303_715_884_105_728.0; if bound < I128_MIN_F64 {
182 return Some(Ordering::Greater);
183 }
184 if bound >= I128_UPPER_EXCL_F64 {
185 return Some(Ordering::Less);
186 }
187 let floor_f = bound.floor();
188 let floor_i = floor_f as i128;
189 if bound == floor_f {
190 Some(value.cmp(&floor_i))
191 } else if value <= floor_i {
192 Some(Ordering::Less)
193 } else {
194 Some(Ordering::Greater)
195 }
196}
197
198pub(crate) fn cmp_u128_f64(value: u128, bound: f64) -> Option<Ordering> {
200 if bound.is_nan() {
201 return None;
202 }
203 const U128_UPPER_EXCL_F64: f64 = 340_282_366_920_938_463_463_374_607_431_768_211_456.0; if bound < 0.0 {
205 return Some(Ordering::Greater);
206 }
207 if bound >= U128_UPPER_EXCL_F64 {
208 return Some(Ordering::Less);
209 }
210 let floor_f = bound.floor();
211 let floor_u = floor_f as u128;
212 if bound == floor_f {
213 Some(value.cmp(&floor_u))
214 } else if value <= floor_u {
215 Some(Ordering::Less)
216 } else {
217 Some(Ordering::Greater)
218 }
219}
220
221macro_rules! impl_numeric_int {
222 ($($ty:ty),*) => {
223 $(
224 impl NumericValue for $ty {
225 fn check_bounds(
226 self,
227 field: &str,
228 min: Option<f64>,
229 max: Option<f64>,
230 gt: Option<f64>,
231 lt: Option<f64>,
232 multiple_of: Option<i64>,
233 ) -> Result<(), FieldIssue> {
234 let val = self as i128;
235 if let Some(min) = min {
236 if !matches!(cmp_i128_f64(val, min), Some(Ordering::Equal | Ordering::Greater)) {
237 return Err(FieldIssue::new(
238 field,
239 "NUMBER_TOO_SMALL",
240 format!("must be >= {min}"),
241 ));
242 }
243 }
244 if let Some(max) = max {
245 if !matches!(cmp_i128_f64(val, max), Some(Ordering::Equal | Ordering::Less)) {
246 return Err(FieldIssue::new(
247 field,
248 "NUMBER_TOO_LARGE",
249 format!("must be <= {max}"),
250 ));
251 }
252 }
253 if let Some(gt) = gt {
254 if !matches!(cmp_i128_f64(val, gt), Some(Ordering::Greater)) {
255 return Err(FieldIssue::new(
256 field,
257 "NUMBER_NOT_GT",
258 format!("must be > {gt}"),
259 ));
260 }
261 }
262 if let Some(lt) = lt {
263 if !matches!(cmp_i128_f64(val, lt), Some(Ordering::Less)) {
264 return Err(FieldIssue::new(
265 field,
266 "NUMBER_NOT_LT",
267 format!("must be < {lt}"),
268 ));
269 }
270 }
271 if let Some(multiple_of) = multiple_of {
272 let m = multiple_of as i128;
273 if m == 0 || val % m != 0 {
274 return Err(FieldIssue::new(
275 field,
276 "NUMBER_NOT_MULTIPLE",
277 format!("must be a multiple of {multiple_of}"),
278 ));
279 }
280 }
281 Ok(())
282 }
283
284 fn check_positive(self, field: &str) -> Result<(), FieldIssue> {
285 if self > 0 {
286 Ok(())
287 } else {
288 Err(FieldIssue::new(
289 field,
290 "NUMBER_NOT_POSITIVE",
291 "must be positive",
292 ))
293 }
294 }
295
296 fn check_non_negative(self, field: &str) -> Result<(), FieldIssue> {
297 if self >= 0 {
298 Ok(())
299 } else {
300 Err(FieldIssue::new(
301 field,
302 "NUMBER_NEGATIVE",
303 "must be non-negative",
304 ))
305 }
306 }
307
308 fn check_finite(self, _field: &str) -> Result<(), FieldIssue> {
309 Ok(())
310 }
311 }
312 )*
313 };
314}
315
316macro_rules! impl_numeric_uint {
317 ($($ty:ty),*) => {
318 $(
319 impl NumericValue for $ty {
320 fn check_bounds(
321 self,
322 field: &str,
323 min: Option<f64>,
324 max: Option<f64>,
325 gt: Option<f64>,
326 lt: Option<f64>,
327 multiple_of: Option<i64>,
328 ) -> Result<(), FieldIssue> {
329 let val = self as u128;
330 if let Some(min) = min {
331 if !matches!(cmp_u128_f64(val, min), Some(Ordering::Equal | Ordering::Greater)) {
332 return Err(FieldIssue::new(
333 field,
334 "NUMBER_TOO_SMALL",
335 format!("must be >= {min}"),
336 ));
337 }
338 }
339 if let Some(max) = max {
340 if !matches!(cmp_u128_f64(val, max), Some(Ordering::Equal | Ordering::Less)) {
341 return Err(FieldIssue::new(
342 field,
343 "NUMBER_TOO_LARGE",
344 format!("must be <= {max}"),
345 ));
346 }
347 }
348 if let Some(gt) = gt {
349 if !matches!(cmp_u128_f64(val, gt), Some(Ordering::Greater)) {
350 return Err(FieldIssue::new(
351 field,
352 "NUMBER_NOT_GT",
353 format!("must be > {gt}"),
354 ));
355 }
356 }
357 if let Some(lt) = lt {
358 if !matches!(cmp_u128_f64(val, lt), Some(Ordering::Less)) {
359 return Err(FieldIssue::new(
360 field,
361 "NUMBER_NOT_LT",
362 format!("must be < {lt}"),
363 ));
364 }
365 }
366 if let Some(multiple_of) = multiple_of {
367 if multiple_of <= 0 || val % (multiple_of as u128) != 0 {
368 return Err(FieldIssue::new(
369 field,
370 "NUMBER_NOT_MULTIPLE",
371 format!("must be a multiple of {multiple_of}"),
372 ));
373 }
374 }
375 Ok(())
376 }
377
378 fn check_positive(self, field: &str) -> Result<(), FieldIssue> {
379 if self > 0 {
380 Ok(())
381 } else {
382 Err(FieldIssue::new(
383 field,
384 "NUMBER_NOT_POSITIVE",
385 "must be positive",
386 ))
387 }
388 }
389
390 fn check_non_negative(self, _field: &str) -> Result<(), FieldIssue> {
391 Ok(())
392 }
393
394 fn check_finite(self, _field: &str) -> Result<(), FieldIssue> {
395 Ok(())
396 }
397 }
398 )*
399 };
400}
401
402macro_rules! impl_numeric_float {
403 ($($ty:ty),*) => {
404 $(
405 impl NumericValue for $ty {
406 fn check_bounds(
407 self,
408 field: &str,
409 min: Option<f64>,
410 max: Option<f64>,
411 gt: Option<f64>,
412 lt: Option<f64>,
413 multiple_of: Option<i64>,
414 ) -> Result<(), FieldIssue> {
415 let val = self as f64;
416 number_f64(field, val, min, max, gt, lt)?;
417 if let Some(multiple_of) = multiple_of {
418 let m = multiple_of as f64;
419 if m == 0.0 || !m.is_finite() {
420 return Err(FieldIssue::new(
421 field,
422 "NUMBER_NOT_MULTIPLE",
423 format!("must be a multiple of {multiple_of}"),
424 ));
425 }
426 let q = val / m;
427 if !q.is_finite() || (q - q.round()).abs() > 1e-9 {
428 return Err(FieldIssue::new(
429 field,
430 "NUMBER_NOT_MULTIPLE",
431 format!("must be a multiple of {multiple_of}"),
432 ));
433 }
434 }
435 Ok(())
436 }
437
438 fn check_positive(self, field: &str) -> Result<(), FieldIssue> {
439 if self.is_finite() && (self as f64) > 0.0 {
440 Ok(())
441 } else {
442 Err(FieldIssue::new(
443 field,
444 "NUMBER_NOT_POSITIVE",
445 "must be positive",
446 ))
447 }
448 }
449
450 fn check_non_negative(self, field: &str) -> Result<(), FieldIssue> {
451 if self.is_finite() && (self as f64) >= 0.0 {
452 Ok(())
453 } else {
454 Err(FieldIssue::new(
455 field,
456 "NUMBER_NEGATIVE",
457 "must be non-negative",
458 ))
459 }
460 }
461
462 fn check_finite(self, field: &str) -> Result<(), FieldIssue> {
463 finite_f64(field, self as f64)
464 }
465 }
466 )*
467 };
468}
469
470impl_numeric_int!(i8, i16, i32, i64, i128, isize);
471impl_numeric_uint!(u8, u16, u32, u64, u128, usize);
472impl_numeric_float!(f32, f64);
473
474pub fn number_i64(
475 field: &str,
476 value: i64,
477 min: Option<i64>,
478 max: Option<i64>,
479 gt: Option<i64>,
480 lt: Option<i64>,
481 multiple_of: Option<i64>,
482) -> Result<(), FieldIssue> {
483 if let Some(min) = min {
484 if value < min {
485 return Err(FieldIssue::new(
486 field,
487 "NUMBER_TOO_SMALL",
488 format!("must be >= {min}"),
489 ));
490 }
491 }
492 if let Some(max) = max {
493 if value > max {
494 return Err(FieldIssue::new(
495 field,
496 "NUMBER_TOO_LARGE",
497 format!("must be <= {max}"),
498 ));
499 }
500 }
501 if let Some(gt) = gt {
502 if value <= gt {
503 return Err(FieldIssue::new(
504 field,
505 "NUMBER_NOT_GT",
506 format!("must be > {gt}"),
507 ));
508 }
509 }
510 if let Some(lt) = lt {
511 if value >= lt {
512 return Err(FieldIssue::new(
513 field,
514 "NUMBER_NOT_LT",
515 format!("must be < {lt}"),
516 ));
517 }
518 }
519 if let Some(multiple_of) = multiple_of {
520 let m = multiple_of as i128;
521 if m == 0 || (value as i128) % m != 0 {
522 return Err(FieldIssue::new(
523 field,
524 "NUMBER_NOT_MULTIPLE",
525 format!("must be a multiple of {multiple_of}"),
526 ));
527 }
528 }
529 Ok(())
530}
531
532pub fn number_f64(
533 field: &str,
534 value: f64,
535 min: Option<f64>,
536 max: Option<f64>,
537 gt: Option<f64>,
538 lt: Option<f64>,
539) -> Result<(), FieldIssue> {
540 if !value.is_finite() {
541 return Err(FieldIssue::new(
542 field,
543 "NUMBER_NOT_FINITE",
544 "must be finite",
545 ));
546 }
547 if let Some(min) = min {
548 if !matches!(
549 value.partial_cmp(&min),
550 Some(Ordering::Equal | Ordering::Greater)
551 ) {
552 return Err(FieldIssue::new(
553 field,
554 "NUMBER_TOO_SMALL",
555 format!("must be >= {min}"),
556 ));
557 }
558 }
559 if let Some(max) = max {
560 if !matches!(
561 value.partial_cmp(&max),
562 Some(Ordering::Equal | Ordering::Less)
563 ) {
564 return Err(FieldIssue::new(
565 field,
566 "NUMBER_TOO_LARGE",
567 format!("must be <= {max}"),
568 ));
569 }
570 }
571 if let Some(gt) = gt {
572 if !matches!(value.partial_cmp(>), Some(Ordering::Greater)) {
573 return Err(FieldIssue::new(
574 field,
575 "NUMBER_NOT_GT",
576 format!("must be > {gt}"),
577 ));
578 }
579 }
580 if let Some(lt) = lt {
581 if !matches!(value.partial_cmp(<), Some(Ordering::Less)) {
582 return Err(FieldIssue::new(
583 field,
584 "NUMBER_NOT_LT",
585 format!("must be < {lt}"),
586 ));
587 }
588 }
589 Ok(())
590}
591
592pub fn positive_i64(field: &str, value: i64) -> Result<(), FieldIssue> {
593 value.check_positive(field)
594}
595
596pub fn non_negative_i64(field: &str, value: i64) -> Result<(), FieldIssue> {
597 value.check_non_negative(field)
598}
599
600pub fn finite_f64(field: &str, value: f64) -> Result<(), FieldIssue> {
601 if value.is_finite() {
602 Ok(())
603 } else {
604 Err(FieldIssue::new(
605 field,
606 "NUMBER_NOT_FINITE",
607 "must be finite",
608 ))
609 }
610}
611
612pub fn bool_is_true(field: &str, value: bool) -> Result<(), FieldIssue> {
613 if value {
614 Ok(())
615 } else {
616 Err(FieldIssue::new(
617 field,
618 "BOOL_NOT_TRUE",
619 "must be true",
620 ))
621 }
622}
623
624pub fn list_len<T>(
625 field: &str,
626 value: &[T],
627 min: Option<usize>,
628 max: Option<usize>,
629) -> Result<(), FieldIssue> {
630 let len = value.len();
631 if let Some(min) = min {
632 if len < min {
633 return Err(FieldIssue::new(
634 field,
635 "LIST_TOO_SHORT",
636 format!("must have at least {min} items"),
637 ));
638 }
639 }
640 if let Some(max) = max {
641 if len > max {
642 return Err(FieldIssue::new(
643 field,
644 "LIST_TOO_LONG",
645 format!("must have at most {max} items"),
646 ));
647 }
648 }
649 Ok(())
650}
651
652pub fn list_unique<T: Eq + Hash>(field: &str, value: &[T]) -> Result<(), FieldIssue> {
653 let mut seen = HashSet::with_capacity(value.len());
654 for item in value {
655 if !seen.insert(item) {
656 return Err(FieldIssue::new(
657 field,
658 "LIST_NOT_UNIQUE",
659 "items must be unique",
660 ));
661 }
662 }
663 Ok(())
664}
665
666pub fn list_unique_strings(field: &str, value: &[String]) -> Result<(), FieldIssue> {
667 list_unique(field, value)
668}
669
670pub fn timestamp_ms(
671 field: &str,
672 value: i64,
673 min: Option<i64>,
674 max: Option<i64>,
675 after_now: bool,
676 before_now: bool,
677 ctx: &ValidationContext,
678) -> Result<(), FieldIssue> {
679 if let Some(min) = min {
680 if value < min {
681 return Err(FieldIssue::new(
682 field,
683 "TIMESTAMP_TOO_SMALL",
684 format!("must be >= {min}"),
685 ));
686 }
687 }
688 if let Some(max) = max {
689 if value > max {
690 return Err(FieldIssue::new(
691 field,
692 "TIMESTAMP_TOO_LARGE",
693 format!("must be <= {max}"),
694 ));
695 }
696 }
697 if after_now || before_now {
698 let Some(now) = ctx.now_ms else {
699 return Err(FieldIssue::new(
700 field,
701 "TIMESTAMP_NO_CONTEXT",
702 "now_ms is required for relative timestamp checks",
703 ));
704 };
705 if after_now && value <= now {
706 return Err(FieldIssue::new(
707 field,
708 "TIMESTAMP_NOT_AFTER_NOW",
709 "must be after now",
710 ));
711 }
712 if before_now && value >= now {
713 return Err(FieldIssue::new(
714 field,
715 "TIMESTAMP_NOT_BEFORE_NOW",
716 "must be before now",
717 ));
718 }
719 }
720 Ok(())
721}
722
723pub fn prefix_nested(parent: &str, issues: Vec<FieldIssue>) -> Vec<FieldIssue> {
724 if parent.is_empty() {
725 return issues;
726 }
727 issues
728 .into_iter()
729 .map(|mut issue| {
730 if issue.field.is_empty() || issue.field == "body" {
731 issue.field = parent.to_string();
732 } else if issue.field.starts_with('[') {
733 issue.field = format!("{parent}{}", issue.field);
734 } else {
735 issue.field = format!("{parent}.{}", issue.field);
736 }
737 issue
738 })
739 .collect()
740}
741
742#[cfg(test)]
743mod tests {
744 use super::*;
745
746 #[test]
747 fn i64_bounds_above_2_pow_53_are_exact() {
748 let two_53 = 1i64 << 53;
749 let two_53_plus_1 = two_53 + 1;
750 assert!(two_53_plus_1
751 .check_bounds("v", None, None, Some(two_53 as f64), None, None)
752 .is_ok());
753 assert!(two_53
754 .check_bounds("v", None, None, Some(two_53 as f64), None, None)
755 .is_err());
756
757 assert!(number_i64("v", i64::MAX, None, Some(i64::MAX - 1), None, None, None).is_err());
758 assert!(number_i64("v", i64::MAX - 1, None, Some(i64::MAX - 1), None, None, None).is_ok());
759 }
760
761 #[test]
762 fn float_multiple_of_symmetric_near_multiples() {
763 assert!(9.999_999_999_999_998_f64
764 .check_bounds("v", None, None, None, None, Some(10))
765 .is_ok());
766 assert!(10.5_f64
767 .check_bounds("v", None, None, None, None, Some(10))
768 .is_err());
769 }
770}