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, Hash)]
11pub enum LengthUnit {
12 Chars,
13 Bytes,
14 Utf16,
15}
16
17impl LengthUnit {
18 #[must_use]
19 pub fn parse(value: &str) -> Option<Self> {
20 match value {
21 "chars" => Some(Self::Chars),
22 "bytes" => Some(Self::Bytes),
23 "utf16" => Some(Self::Utf16),
24 _ => None,
25 }
26 }
27
28 #[must_use]
29 pub const fn as_str(self) -> &'static str {
30 match self {
31 Self::Chars => "chars",
32 Self::Bytes => "bytes",
33 Self::Utf16 => "utf16",
34 }
35 }
36
37 fn bounded_len(self, value: &str, cap: Option<usize>) -> usize {
38 match (self, cap) {
39 (Self::Bytes, _) => value.len(),
40 (Self::Chars, Some(limit)) => {
41 if value.len() <= limit {
42 return value.chars().count();
43 }
44 value.chars().take(limit.saturating_add(1)).count()
45 }
46 (Self::Chars, None) => value.chars().count(),
47 (Self::Utf16, Some(limit)) => {
48 value.encode_utf16().take(limit.saturating_add(1)).count()
49 }
50 (Self::Utf16, None) => value.encode_utf16().count(),
51 }
52 }
53}
54
55pub fn string_len(
56 field: &str,
57 value: &str,
58 min: Option<usize>,
59 max: Option<usize>,
60 unit: LengthUnit,
61) -> Result<(), FieldIssue> {
62 let cap = match (min, max) {
63 (_, Some(max)) => Some(max),
64 (Some(min), None) => Some(min.saturating_sub(1)),
65 (None, None) => None,
66 };
67 let len = unit.bounded_len(value, cap);
68 if let Some(min) = min {
69 if len < min {
70 return Err(FieldIssue::new(
71 field,
72 "STRING_TOO_SHORT",
73 format!("must be at least {min} {}", unit.as_str()),
74 ));
75 }
76 }
77 if let Some(max) = max {
78 if len > max {
79 return Err(FieldIssue::new(
80 field,
81 "STRING_TOO_LONG",
82 format!("must be at most {max} {}", unit.as_str()),
83 ));
84 }
85 }
86 Ok(())
87}
88
89pub fn non_empty(field: &str, value: &str) -> Result<(), FieldIssue> {
90 if value.is_empty() {
91 Err(FieldIssue::new(
92 field,
93 "STRING_EMPTY",
94 "must not be empty",
95 ))
96 } else {
97 Ok(())
98 }
99}
100
101pub fn ascii(field: &str, value: &str) -> Result<(), FieldIssue> {
102 if value.is_ascii() {
103 Ok(())
104 } else {
105 Err(FieldIssue::new(
106 field,
107 "STRING_NOT_ASCII",
108 "must be ASCII",
109 ))
110 }
111}
112
113pub fn alphanumeric(field: &str, value: &str) -> Result<(), FieldIssue> {
114 if value.bytes().all(|b| b.is_ascii_alphanumeric()) {
115 Ok(())
116 } else {
117 Err(FieldIssue::new(
118 field,
119 "STRING_NOT_ALPHANUMERIC",
120 "must be alphanumeric",
121 ))
122 }
123}
124
125pub fn digits(field: &str, value: &str) -> Result<(), FieldIssue> {
126 if value.bytes().all(|b| b.is_ascii_digit()) {
127 Ok(())
128 } else {
129 Err(FieldIssue::new(
130 field,
131 "STRING_NOT_DIGITS",
132 "must be digits only",
133 ))
134 }
135}
136
137pub fn starts_with(field: &str, value: &str, prefix: &str) -> Result<(), FieldIssue> {
138 if value.starts_with(prefix) {
139 Ok(())
140 } else {
141 Err(FieldIssue::new(
142 field,
143 "STRING_PREFIX",
144 format!("must start with {prefix}"),
145 ))
146 }
147}
148
149pub fn ends_with(field: &str, value: &str, suffix: &str) -> Result<(), FieldIssue> {
150 if value.ends_with(suffix) {
151 Ok(())
152 } else {
153 Err(FieldIssue::new(
154 field,
155 "STRING_SUFFIX",
156 format!("must end with {suffix}"),
157 ))
158 }
159}
160
161pub fn one_of(field: &str, value: &str, allowed: &[&str]) -> Result<(), FieldIssue> {
162 if allowed.contains(&value) {
163 Ok(())
164 } else {
165 Err(FieldIssue::new(
166 field,
167 "STRING_ONE_OF",
168 format!("must be one of {allowed:?}"),
169 ))
170 }
171}
172
173pub trait NumericValue: Copy {
175 fn check_bounds(
176 self,
177 field: &str,
178 min: Option<f64>,
179 max: Option<f64>,
180 gt: Option<f64>,
181 lt: Option<f64>,
182 multiple_of: Option<i64>,
183 ) -> Result<(), FieldIssue>;
184
185 fn check_positive(self, field: &str) -> Result<(), FieldIssue>;
186 fn check_non_negative(self, field: &str) -> Result<(), FieldIssue>;
187 fn check_finite(self, field: &str) -> Result<(), FieldIssue>;
188}
189
190#[allow(clippy::cast_possible_truncation, clippy::float_cmp)]
192pub(crate) fn cmp_i128_f64(value: i128, bound: f64) -> Option<Ordering> {
193 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.is_nan() {
196 return None;
197 }
198 if bound < I128_MIN_F64 {
199 return Some(Ordering::Greater);
200 }
201 if bound >= I128_UPPER_EXCL_F64 {
202 return Some(Ordering::Less);
203 }
204 let floor_f = bound.floor();
205 let floor_i = floor_f as i128;
206 if bound == floor_f {
207 Some(value.cmp(&floor_i))
208 } else if value <= floor_i {
209 Some(Ordering::Less)
210 } else {
211 Some(Ordering::Greater)
212 }
213}
214
215#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss, clippy::float_cmp)]
217pub(crate) fn cmp_u128_f64(value: u128, bound: f64) -> Option<Ordering> {
218 const U128_UPPER_EXCL_F64: f64 = 340_282_366_920_938_463_463_374_607_431_768_211_456.0; if bound.is_nan() {
220 return None;
221 }
222 if bound < 0.0 {
223 return Some(Ordering::Greater);
224 }
225 if bound >= U128_UPPER_EXCL_F64 {
226 return Some(Ordering::Less);
227 }
228 let floor_f = bound.floor();
229 let floor_u = floor_f as u128;
230 if bound == floor_f {
231 Some(value.cmp(&floor_u))
232 } else if value <= floor_u {
233 Some(Ordering::Less)
234 } else {
235 Some(Ordering::Greater)
236 }
237}
238
239#[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
240fn check_float_multiple_of(
241 field: &str,
242 val: f64,
243 multiple_of: i64,
244 eps: f64,
245 max_tol: f64,
246) -> Result<(), FieldIssue> {
247 if multiple_of == 0 || !val.is_finite() {
248 return Err(FieldIssue::new(
249 field,
250 "NUMBER_NOT_MULTIPLE",
251 format!("must be a multiple of {multiple_of}"),
252 ));
253 }
254 let m_i128 = i128::from(multiple_of).abs();
255 if val == 0.0 {
256 return Ok(());
257 }
258 if m_i128 > (1_i128 << 53) {
260 if val.fract() == 0.0
261 && matches!(
262 cmp_i128_f64(i128::MIN, val),
263 Some(Ordering::Less | Ordering::Equal)
264 )
265 && matches!(
266 cmp_i128_f64(i128::MAX, val),
267 Some(Ordering::Greater | Ordering::Equal)
268 )
269 && (val as i128) % m_i128 == 0
270 {
271 return Ok(());
272 }
273 return Err(FieldIssue::new(
274 field,
275 "NUMBER_NOT_MULTIPLE",
276 format!("must be a multiple of {multiple_of}"),
277 ));
278 }
279
280 let abs_val = val.abs();
281 let m_abs = (m_i128 as f64).abs();
282 let rem = abs_val % m_abs;
284 let dist = rem.min(m_abs - rem);
285 let tol = (8.0 * eps * abs_val).min(max_tol);
286 if dist <= tol {
287 Ok(())
288 } else {
289 Err(FieldIssue::new(
290 field,
291 "NUMBER_NOT_MULTIPLE",
292 format!("must be a multiple of {multiple_of}"),
293 ))
294 }
295}
296
297macro_rules! impl_numeric_int {
298 ($($ty:ty),*) => {
299 $(
300 impl NumericValue for $ty {
301 fn check_bounds(
302 self,
303 field: &str,
304 min: Option<f64>,
305 max: Option<f64>,
306 gt: Option<f64>,
307 lt: Option<f64>,
308 multiple_of: Option<i64>,
309 ) -> Result<(), FieldIssue> {
310 let val = self as i128;
311 if let Some(min) = min {
312 if !matches!(cmp_i128_f64(val, min), Some(Ordering::Equal | Ordering::Greater)) {
313 return Err(FieldIssue::new(
314 field,
315 "NUMBER_TOO_SMALL",
316 format!("must be >= {min}"),
317 ));
318 }
319 }
320 if let Some(max) = max {
321 if !matches!(cmp_i128_f64(val, max), Some(Ordering::Equal | Ordering::Less)) {
322 return Err(FieldIssue::new(
323 field,
324 "NUMBER_TOO_LARGE",
325 format!("must be <= {max}"),
326 ));
327 }
328 }
329 if let Some(gt) = gt {
330 if !matches!(cmp_i128_f64(val, gt), Some(Ordering::Greater)) {
331 return Err(FieldIssue::new(
332 field,
333 "NUMBER_NOT_GT",
334 format!("must be > {gt}"),
335 ));
336 }
337 }
338 if let Some(lt) = lt {
339 if !matches!(cmp_i128_f64(val, lt), Some(Ordering::Less)) {
340 return Err(FieldIssue::new(
341 field,
342 "NUMBER_NOT_LT",
343 format!("must be < {lt}"),
344 ));
345 }
346 }
347 if let Some(multiple_of) = multiple_of {
348 let m = i128::from(multiple_of);
349 if m == 0 || val % m != 0 {
350 return Err(FieldIssue::new(
351 field,
352 "NUMBER_NOT_MULTIPLE",
353 format!("must be a multiple of {multiple_of}"),
354 ));
355 }
356 }
357 Ok(())
358 }
359
360 fn check_positive(self, field: &str) -> Result<(), FieldIssue> {
361 if self > 0 {
362 Ok(())
363 } else {
364 Err(FieldIssue::new(
365 field,
366 "NUMBER_NOT_POSITIVE",
367 "must be positive",
368 ))
369 }
370 }
371
372 fn check_non_negative(self, field: &str) -> Result<(), FieldIssue> {
373 if self >= 0 {
374 Ok(())
375 } else {
376 Err(FieldIssue::new(
377 field,
378 "NUMBER_NEGATIVE",
379 "must be non-negative",
380 ))
381 }
382 }
383
384 fn check_finite(self, _field: &str) -> Result<(), FieldIssue> {
385 Ok(())
386 }
387 }
388 )*
389 };
390}
391
392macro_rules! impl_numeric_uint {
393 ($($ty:ty),*) => {
394 $(
395 impl NumericValue for $ty {
396 fn check_bounds(
397 self,
398 field: &str,
399 min: Option<f64>,
400 max: Option<f64>,
401 gt: Option<f64>,
402 lt: Option<f64>,
403 multiple_of: Option<i64>,
404 ) -> Result<(), FieldIssue> {
405 let val = self as u128;
406 if let Some(min) = min {
407 if !matches!(cmp_u128_f64(val, min), Some(Ordering::Equal | Ordering::Greater)) {
408 return Err(FieldIssue::new(
409 field,
410 "NUMBER_TOO_SMALL",
411 format!("must be >= {min}"),
412 ));
413 }
414 }
415 if let Some(max) = max {
416 if !matches!(cmp_u128_f64(val, max), Some(Ordering::Equal | Ordering::Less)) {
417 return Err(FieldIssue::new(
418 field,
419 "NUMBER_TOO_LARGE",
420 format!("must be <= {max}"),
421 ));
422 }
423 }
424 if let Some(gt) = gt {
425 if !matches!(cmp_u128_f64(val, gt), Some(Ordering::Greater)) {
426 return Err(FieldIssue::new(
427 field,
428 "NUMBER_NOT_GT",
429 format!("must be > {gt}"),
430 ));
431 }
432 }
433 if let Some(lt) = lt {
434 if !matches!(cmp_u128_f64(val, lt), Some(Ordering::Less)) {
435 return Err(FieldIssue::new(
436 field,
437 "NUMBER_NOT_LT",
438 format!("must be < {lt}"),
439 ));
440 }
441 }
442 if let Some(multiple_of) = multiple_of {
443 let Ok(m) = u128::try_from(multiple_of) else {
444 return Err(FieldIssue::new(
445 field,
446 "NUMBER_NOT_MULTIPLE",
447 format!("must be a multiple of {multiple_of}"),
448 ));
449 };
450 if m == 0 || val % m != 0 {
451 return Err(FieldIssue::new(
452 field,
453 "NUMBER_NOT_MULTIPLE",
454 format!("must be a multiple of {multiple_of}"),
455 ));
456 }
457 }
458 Ok(())
459 }
460
461 fn check_positive(self, field: &str) -> Result<(), FieldIssue> {
462 if self > 0 {
463 Ok(())
464 } else {
465 Err(FieldIssue::new(
466 field,
467 "NUMBER_NOT_POSITIVE",
468 "must be positive",
469 ))
470 }
471 }
472
473 fn check_non_negative(self, _field: &str) -> Result<(), FieldIssue> {
474 Ok(())
475 }
476
477 fn check_finite(self, _field: &str) -> Result<(), FieldIssue> {
478 Ok(())
479 }
480 }
481 )*
482 };
483}
484
485impl_numeric_int!(i8, i16, i32, i64, i128, isize);
486impl_numeric_uint!(u8, u16, u32, u64, u128, usize);
487
488#[allow(clippy::cast_possible_truncation)]
489fn cmp_f32_bound(value: f32, bound: f64) -> Option<Ordering> {
490 if value.is_nan() || bound.is_nan() {
491 return None;
492 }
493 if bound > f64::from(f32::MAX) {
494 return Some(Ordering::Less);
495 }
496 if bound < f64::from(f32::MIN) {
497 return Some(Ordering::Greater);
498 }
499 value.partial_cmp(&(bound as f32))
500}
501
502impl NumericValue for f32 {
503 fn check_bounds(
504 self,
505 field: &str,
506 min: Option<f64>,
507 max: Option<f64>,
508 gt: Option<f64>,
509 lt: Option<f64>,
510 multiple_of: Option<i64>,
511 ) -> Result<(), FieldIssue> {
512 if !self.is_finite() {
513 return Err(FieldIssue::new(
514 field,
515 "NUMBER_NOT_FINITE",
516 "must be finite",
517 ));
518 }
519 if let Some(min) = min {
520 if !matches!(cmp_f32_bound(self, min), Some(Ordering::Equal | Ordering::Greater)) {
521 return Err(FieldIssue::new(
522 field,
523 "NUMBER_TOO_SMALL",
524 format!("must be >= {min}"),
525 ));
526 }
527 }
528 if let Some(max) = max {
529 if !matches!(cmp_f32_bound(self, max), Some(Ordering::Equal | Ordering::Less)) {
530 return Err(FieldIssue::new(
531 field,
532 "NUMBER_TOO_LARGE",
533 format!("must be <= {max}"),
534 ));
535 }
536 }
537 if let Some(gt) = gt {
538 if !matches!(cmp_f32_bound(self, gt), Some(Ordering::Greater)) {
539 return Err(FieldIssue::new(
540 field,
541 "NUMBER_NOT_GT",
542 format!("must be > {gt}"),
543 ));
544 }
545 }
546 if let Some(lt) = lt {
547 if !matches!(cmp_f32_bound(self, lt), Some(Ordering::Less)) {
548 return Err(FieldIssue::new(
549 field,
550 "NUMBER_NOT_LT",
551 format!("must be < {lt}"),
552 ));
553 }
554 }
555 if let Some(multiple_of) = multiple_of {
556 check_float_multiple_of(
557 field,
558 f64::from(self),
559 multiple_of,
560 f64::from(f32::EPSILON),
561 1e-5,
562 )?;
563 }
564 Ok(())
565 }
566
567 fn check_positive(self, field: &str) -> Result<(), FieldIssue> {
568 if self.is_finite() && self > 0.0 {
569 Ok(())
570 } else {
571 Err(FieldIssue::new(
572 field,
573 "NUMBER_NOT_POSITIVE",
574 "must be positive",
575 ))
576 }
577 }
578
579 fn check_non_negative(self, field: &str) -> Result<(), FieldIssue> {
580 if self.is_finite() && self >= 0.0 {
581 Ok(())
582 } else {
583 Err(FieldIssue::new(
584 field,
585 "NUMBER_NEGATIVE",
586 "must be non-negative",
587 ))
588 }
589 }
590
591 fn check_finite(self, field: &str) -> Result<(), FieldIssue> {
592 finite_f64(field, f64::from(self))
593 }
594}
595
596impl NumericValue for f64 {
597 fn check_bounds(
598 self,
599 field: &str,
600 min: Option<f64>,
601 max: Option<f64>,
602 gt: Option<f64>,
603 lt: Option<f64>,
604 multiple_of: Option<i64>,
605 ) -> Result<(), FieldIssue> {
606 number_f64(field, self, min, max, gt, lt)?;
607 if let Some(multiple_of) = multiple_of {
608 check_float_multiple_of(field, self, multiple_of, f64::EPSILON, 1e-9)?;
609 }
610 Ok(())
611 }
612
613 fn check_positive(self, field: &str) -> Result<(), FieldIssue> {
614 if self.is_finite() && self > 0.0 {
615 Ok(())
616 } else {
617 Err(FieldIssue::new(
618 field,
619 "NUMBER_NOT_POSITIVE",
620 "must be positive",
621 ))
622 }
623 }
624
625 fn check_non_negative(self, field: &str) -> Result<(), FieldIssue> {
626 if self.is_finite() && self >= 0.0 {
627 Ok(())
628 } else {
629 Err(FieldIssue::new(
630 field,
631 "NUMBER_NEGATIVE",
632 "must be non-negative",
633 ))
634 }
635 }
636
637 fn check_finite(self, field: &str) -> Result<(), FieldIssue> {
638 finite_f64(field, self)
639 }
640}
641
642pub fn number_i64(
643 field: &str,
644 value: i64,
645 min: Option<i64>,
646 max: Option<i64>,
647 gt: Option<i64>,
648 lt: Option<i64>,
649 multiple_of: Option<i64>,
650) -> Result<(), FieldIssue> {
651 if let Some(min) = min {
652 if value < min {
653 return Err(FieldIssue::new(
654 field,
655 "NUMBER_TOO_SMALL",
656 format!("must be >= {min}"),
657 ));
658 }
659 }
660 if let Some(max) = max {
661 if value > max {
662 return Err(FieldIssue::new(
663 field,
664 "NUMBER_TOO_LARGE",
665 format!("must be <= {max}"),
666 ));
667 }
668 }
669 if let Some(gt) = gt {
670 if value <= gt {
671 return Err(FieldIssue::new(
672 field,
673 "NUMBER_NOT_GT",
674 format!("must be > {gt}"),
675 ));
676 }
677 }
678 if let Some(lt) = lt {
679 if value >= lt {
680 return Err(FieldIssue::new(
681 field,
682 "NUMBER_NOT_LT",
683 format!("must be < {lt}"),
684 ));
685 }
686 }
687 if let Some(multiple_of) = multiple_of {
688 let m = i128::from(multiple_of);
689 if m == 0 || i128::from(value) % m != 0 {
690 return Err(FieldIssue::new(
691 field,
692 "NUMBER_NOT_MULTIPLE",
693 format!("must be a multiple of {multiple_of}"),
694 ));
695 }
696 }
697 Ok(())
698}
699
700pub fn number_f64(
701 field: &str,
702 value: f64,
703 min: Option<f64>,
704 max: Option<f64>,
705 gt: Option<f64>,
706 lt: Option<f64>,
707) -> Result<(), FieldIssue> {
708 if !value.is_finite() {
709 return Err(FieldIssue::new(
710 field,
711 "NUMBER_NOT_FINITE",
712 "must be finite",
713 ));
714 }
715 if let Some(min) = min {
716 if !matches!(
717 value.partial_cmp(&min),
718 Some(Ordering::Equal | Ordering::Greater)
719 ) {
720 return Err(FieldIssue::new(
721 field,
722 "NUMBER_TOO_SMALL",
723 format!("must be >= {min}"),
724 ));
725 }
726 }
727 if let Some(max) = max {
728 if !matches!(
729 value.partial_cmp(&max),
730 Some(Ordering::Equal | Ordering::Less)
731 ) {
732 return Err(FieldIssue::new(
733 field,
734 "NUMBER_TOO_LARGE",
735 format!("must be <= {max}"),
736 ));
737 }
738 }
739 if let Some(gt) = gt {
740 if !matches!(value.partial_cmp(>), Some(Ordering::Greater)) {
741 return Err(FieldIssue::new(
742 field,
743 "NUMBER_NOT_GT",
744 format!("must be > {gt}"),
745 ));
746 }
747 }
748 if let Some(lt) = lt {
749 if !matches!(value.partial_cmp(<), Some(Ordering::Less)) {
750 return Err(FieldIssue::new(
751 field,
752 "NUMBER_NOT_LT",
753 format!("must be < {lt}"),
754 ));
755 }
756 }
757 Ok(())
758}
759
760pub fn positive_i64(field: &str, value: i64) -> Result<(), FieldIssue> {
761 value.check_positive(field)
762}
763
764pub fn non_negative_i64(field: &str, value: i64) -> Result<(), FieldIssue> {
765 value.check_non_negative(field)
766}
767
768pub fn finite_f64(field: &str, value: f64) -> Result<(), FieldIssue> {
769 if value.is_finite() {
770 Ok(())
771 } else {
772 Err(FieldIssue::new(
773 field,
774 "NUMBER_NOT_FINITE",
775 "must be finite",
776 ))
777 }
778}
779
780pub fn bool_is_true(field: &str, value: bool) -> Result<(), FieldIssue> {
781 if value {
782 Ok(())
783 } else {
784 Err(FieldIssue::new(
785 field,
786 "BOOL_NOT_TRUE",
787 "must be true",
788 ))
789 }
790}
791
792pub fn list_len<T>(
793 field: &str,
794 value: &[T],
795 min: Option<usize>,
796 max: Option<usize>,
797) -> Result<(), FieldIssue> {
798 let len = value.len();
799 if let Some(min) = min {
800 if len < min {
801 return Err(FieldIssue::new(
802 field,
803 "LIST_TOO_SHORT",
804 format!("must have at least {min} items"),
805 ));
806 }
807 }
808 if let Some(max) = max {
809 if len > max {
810 return Err(FieldIssue::new(
811 field,
812 "LIST_TOO_LONG",
813 format!("must have at most {max} items"),
814 ));
815 }
816 }
817 Ok(())
818}
819
820pub fn list_unique<T: Eq + Hash>(field: &str, value: &[T]) -> Result<(), FieldIssue> {
821 let mut seen = HashSet::with_capacity(value.len().min(4096));
822 for item in value {
823 if !seen.insert(item) {
824 return Err(FieldIssue::new(
825 field,
826 "LIST_NOT_UNIQUE",
827 "items must be unique",
828 ));
829 }
830 }
831 Ok(())
832}
833
834pub fn list_unique_strings(field: &str, value: &[String]) -> Result<(), FieldIssue> {
835 list_unique(field, value)
836}
837
838pub fn timestamp_ms(
839 field: &str,
840 value: i64,
841 min: Option<i64>,
842 max: Option<i64>,
843 after_now: bool,
844 before_now: bool,
845 ctx: &ValidationContext,
846) -> Result<(), FieldIssue> {
847 if let Some(min) = min {
848 if value < min {
849 return Err(FieldIssue::new(
850 field,
851 "TIMESTAMP_TOO_SMALL",
852 format!("must be >= {min}"),
853 ));
854 }
855 }
856 if let Some(max) = max {
857 if value > max {
858 return Err(FieldIssue::new(
859 field,
860 "TIMESTAMP_TOO_LARGE",
861 format!("must be <= {max}"),
862 ));
863 }
864 }
865 if after_now || before_now {
866 let Some(now) = ctx.now_ms else {
867 return Err(FieldIssue::new(
868 field,
869 "TIMESTAMP_NO_CONTEXT",
870 "now_ms is required for relative timestamp checks",
871 ));
872 };
873 if after_now && value <= now {
874 return Err(FieldIssue::new(
875 field,
876 "TIMESTAMP_NOT_AFTER_NOW",
877 "must be after now",
878 ));
879 }
880 if before_now && value >= now {
881 return Err(FieldIssue::new(
882 field,
883 "TIMESTAMP_NOT_BEFORE_NOW",
884 "must be before now",
885 ));
886 }
887 }
888 Ok(())
889}
890
891#[must_use]
892pub fn prefix_nested(parent: &str, issues: Vec<FieldIssue>) -> Vec<FieldIssue> {
893 if parent.is_empty() {
894 return issues;
895 }
896 issues
897 .into_iter()
898 .map(|mut issue| {
899 if issue.field.is_empty() || issue.field == "body" {
900 issue.field = parent.to_string();
901 } else if issue.field.starts_with('[') {
902 issue.field = format!("{parent}{}", issue.field);
903 } else {
904 issue.field = format!("{parent}.{}", issue.field);
905 }
906 issue
907 })
908 .collect()
909}
910
911#[cfg(test)]
912mod tests {
913 use super::*;
914 use crate::norms::ClampNum;
915
916 #[test]
917 #[allow(clippy::cast_precision_loss)]
918 fn i64_bounds_above_2_pow_53_are_exact() {
919 let two_53 = 1i64 << 53;
920 let two_53_plus_1 = two_53 + 1;
921 assert!(two_53_plus_1
922 .check_bounds("v", None, None, Some(two_53 as f64), None, None)
923 .is_ok());
924 assert!(two_53
925 .check_bounds("v", None, None, Some(two_53 as f64), None, None)
926 .is_err());
927
928 assert!(number_i64("v", i64::MAX, None, Some(i64::MAX - 1), None, None, None).is_err());
929 assert!(number_i64("v", i64::MAX - 1, None, Some(i64::MAX - 1), None, None, None).is_ok());
930 }
931
932 #[test]
933 #[allow(clippy::cast_precision_loss)]
934 fn float_multiple_of_exact_and_rejects_large_scale_false_positives() {
935 assert!(9.999_999_999_999_998_f64
936 .check_bounds("v", None, None, None, None, Some(10))
937 .is_ok());
938 assert!(10.5_f64
939 .check_bounds("v", None, None, None, None, Some(10))
940 .is_err());
941 assert!(500.0_f64
942 .check_bounds("v", None, None, None, None, Some(1_000_000_000_000))
943 .is_err());
944 assert!(((1_i64 << 54) as f64)
945 .check_bounds("v", None, None, None, None, Some(10))
946 .is_err());
947 assert!((((1_i64 << 50) * 10) as f64)
948 .check_bounds("v", None, None, None, None, Some(10))
949 .is_ok());
950 }
951
952 #[test]
953 fn f32_bounds_and_clamp_round_trip_cleanly() {
954 assert!(0.3_f32
955 .check_bounds("v", None, Some(0.3), None, None, None)
956 .is_ok());
957 assert!(0.3_f32
958 .check_bounds("v", None, None, Some(0.3), None, None)
959 .is_err());
960 assert!(0.7_f32
961 .check_bounds("v", Some(0.7), None, None, None, None)
962 .is_ok());
963
964 let mut x = 0.0_f32;
965 x.clamp_in_place(0.7, 1.0);
966 assert!(x
967 .check_bounds("v", Some(0.7), Some(1.0), None, None, None)
968 .is_ok());
969 }
970}