oxicode/validation/
mod.rs

1//! Validation middleware for oxicode.
2//!
3//! This module provides validation constraints for deserialization,
4//! ensuring data integrity and security during decoding.
5//!
6//! ## Features
7//!
8//! - **Size Limits**: Limit string/collection lengths
9//! - **Range Constraints**: Validate numeric values
10//! - **Custom Validators**: User-defined validation functions
11//! - **Checksum Verification**: Optional integrity checking
12//!
13//! ## Example
14//!
15//! ```rust,ignore
16//! use oxicode::validation::{Validator, Constraints};
17//!
18//! // Create a validator with constraints
19//! let mut validator = Validator::new();
20//! validator.add_constraint("name", Constraints::max_len(100));
21//! validator.add_constraint("age", Constraints::range(0..=120));
22//!
23//! // Validate data
24//! let result = validator.validate(&data)?;
25//! ```
26
27mod constraints;
28mod validator;
29
30pub use constraints::{Constraint, Constraints, ValidationResult};
31pub use validator::{FieldValidation, ValidationError, Validator};
32
33/// Configuration for validation behavior.
34#[derive(Debug, Clone)]
35pub struct ValidationConfig {
36    /// Whether to fail fast on the first validation error.
37    pub fail_fast: bool,
38
39    /// Maximum depth for nested structure validation.
40    pub max_depth: usize,
41
42    /// Whether to enable checksum verification.
43    pub verify_checksum: bool,
44}
45
46impl Default for ValidationConfig {
47    fn default() -> Self {
48        Self {
49            fail_fast: true,
50            max_depth: 64,
51            verify_checksum: false,
52        }
53    }
54}
55
56impl ValidationConfig {
57    /// Create a new validation configuration.
58    pub fn new() -> Self {
59        Self::default()
60    }
61
62    /// Set fail-fast behavior.
63    #[inline]
64    pub fn with_fail_fast(mut self, fail_fast: bool) -> Self {
65        self.fail_fast = fail_fast;
66        self
67    }
68
69    /// Set maximum validation depth.
70    #[inline]
71    pub fn with_max_depth(mut self, depth: usize) -> Self {
72        self.max_depth = depth;
73        self
74    }
75
76    /// Enable or disable checksum verification.
77    #[inline]
78    pub fn with_checksum(mut self, verify: bool) -> Self {
79        self.verify_checksum = verify;
80        self
81    }
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87
88    #[test]
89    fn test_config_defaults() {
90        let config = ValidationConfig::default();
91        assert!(config.fail_fast);
92        assert_eq!(config.max_depth, 64);
93        assert!(!config.verify_checksum);
94    }
95
96    #[test]
97    fn test_config_builder() {
98        let config = ValidationConfig::new()
99            .with_fail_fast(false)
100            .with_max_depth(128)
101            .with_checksum(true);
102
103        assert!(!config.fail_fast);
104        assert_eq!(config.max_depth, 128);
105        assert!(config.verify_checksum);
106    }
107}