oxicode 0.2.1

A modern binary serialization library - successor to bincode
Documentation
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! Constraint definitions for field validation.

use core::ops::RangeBounds;

#[cfg(feature = "alloc")]
extern crate alloc;

/// Result of a validation check.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationResult {
    /// Validation passed.
    Valid,
    /// Validation failed with a message.
    Invalid(&'static str),
}

impl ValidationResult {
    /// Check if the result is valid.
    #[inline]
    pub fn is_valid(&self) -> bool {
        matches!(self, ValidationResult::Valid)
    }

    /// Check if the result is invalid.
    #[inline]
    pub fn is_invalid(&self) -> bool {
        matches!(self, ValidationResult::Invalid(_))
    }

    /// Get the error message if invalid.
    pub fn error_message(&self) -> Option<&'static str> {
        match self {
            ValidationResult::Invalid(msg) => Some(msg),
            ValidationResult::Valid => None,
        }
    }
}

/// A constraint that can validate a value.
pub trait Constraint<T: ?Sized> {
    /// Validate the given value.
    fn validate(&self, value: &T) -> ValidationResult;

    /// Get a description of this constraint.
    fn description(&self) -> &'static str;
}

/// Maximum length constraint for strings and collections.
#[derive(Debug, Clone, Copy)]
pub struct MaxLength {
    max: usize,
}

impl MaxLength {
    /// Create a new maximum length constraint.
    pub const fn new(max: usize) -> Self {
        Self { max }
    }
}

impl Constraint<str> for MaxLength {
    fn validate(&self, value: &str) -> ValidationResult {
        if value.len() <= self.max {
            ValidationResult::Valid
        } else {
            ValidationResult::Invalid("string exceeds maximum length")
        }
    }

    fn description(&self) -> &'static str {
        "maximum length constraint"
    }
}

#[cfg(feature = "alloc")]
impl Constraint<alloc::string::String> for MaxLength {
    fn validate(&self, value: &alloc::string::String) -> ValidationResult {
        if value.len() <= self.max {
            ValidationResult::Valid
        } else {
            ValidationResult::Invalid("string exceeds maximum length")
        }
    }

    fn description(&self) -> &'static str {
        "maximum length constraint"
    }
}

impl<T> Constraint<[T]> for MaxLength {
    fn validate(&self, value: &[T]) -> ValidationResult {
        if value.len() <= self.max {
            ValidationResult::Valid
        } else {
            ValidationResult::Invalid("collection exceeds maximum length")
        }
    }

    fn description(&self) -> &'static str {
        "maximum length constraint"
    }
}

#[cfg(feature = "alloc")]
impl<T> Constraint<alloc::vec::Vec<T>> for MaxLength {
    fn validate(&self, value: &alloc::vec::Vec<T>) -> ValidationResult {
        if value.len() <= self.max {
            ValidationResult::Valid
        } else {
            ValidationResult::Invalid("collection exceeds maximum length")
        }
    }

    fn description(&self) -> &'static str {
        "maximum length constraint"
    }
}

/// Minimum length constraint for strings and collections.
#[derive(Debug, Clone, Copy)]
pub struct MinLength {
    min: usize,
}

impl MinLength {
    /// Create a new minimum length constraint.
    pub const fn new(min: usize) -> Self {
        Self { min }
    }
}

impl Constraint<str> for MinLength {
    fn validate(&self, value: &str) -> ValidationResult {
        if value.len() >= self.min {
            ValidationResult::Valid
        } else {
            ValidationResult::Invalid("string below minimum length")
        }
    }

    fn description(&self) -> &'static str {
        "minimum length constraint"
    }
}

#[cfg(feature = "alloc")]
impl Constraint<alloc::string::String> for MinLength {
    fn validate(&self, value: &alloc::string::String) -> ValidationResult {
        if value.len() >= self.min {
            ValidationResult::Valid
        } else {
            ValidationResult::Invalid("string below minimum length")
        }
    }

    fn description(&self) -> &'static str {
        "minimum length constraint"
    }
}

impl<T> Constraint<[T]> for MinLength {
    fn validate(&self, value: &[T]) -> ValidationResult {
        if value.len() >= self.min {
            ValidationResult::Valid
        } else {
            ValidationResult::Invalid("collection below minimum length")
        }
    }

    fn description(&self) -> &'static str {
        "minimum length constraint"
    }
}

#[cfg(feature = "alloc")]
impl<T> Constraint<alloc::vec::Vec<T>> for MinLength {
    fn validate(&self, value: &alloc::vec::Vec<T>) -> ValidationResult {
        if value.len() >= self.min {
            ValidationResult::Valid
        } else {
            ValidationResult::Invalid("collection below minimum length")
        }
    }

    fn description(&self) -> &'static str {
        "minimum length constraint"
    }
}

/// Range constraint for numeric values.
#[derive(Debug, Clone)]
pub struct Range<T> {
    min: Option<T>,
    max: Option<T>,
}

impl<T: PartialOrd + Clone> Range<T> {
    /// Create a new range constraint.
    pub fn new(min: Option<T>, max: Option<T>) -> Self {
        Self { min, max }
    }

    /// Create a range from a RangeBounds.
    pub fn from_bounds<R: RangeBounds<T>>(bounds: &R) -> Self
    where
        T: Clone,
    {
        use core::ops::Bound;

        let min = match bounds.start_bound() {
            Bound::Included(v) => Some(v.clone()),
            Bound::Excluded(_) => None, // Excluded bounds are tricky for generic types
            Bound::Unbounded => None,
        };

        let max = match bounds.end_bound() {
            Bound::Included(v) => Some(v.clone()),
            Bound::Excluded(_) => None,
            Bound::Unbounded => None,
        };

        Self { min, max }
    }
}

impl<T: PartialOrd> Constraint<T> for Range<T> {
    fn validate(&self, value: &T) -> ValidationResult {
        if let Some(ref min) = self.min {
            if value < min {
                return ValidationResult::Invalid("value below minimum");
            }
        }

        if let Some(ref max) = self.max {
            if value > max {
                return ValidationResult::Invalid("value above maximum");
            }
        }

        ValidationResult::Valid
    }

    fn description(&self) -> &'static str {
        "range constraint"
    }
}

/// Non-empty constraint for strings and collections.
#[derive(Debug, Clone, Copy, Default)]
pub struct NonEmpty;

impl NonEmpty {
    /// Create a new non-empty constraint.
    pub const fn new() -> Self {
        Self
    }
}

impl Constraint<str> for NonEmpty {
    fn validate(&self, value: &str) -> ValidationResult {
        if !value.is_empty() {
            ValidationResult::Valid
        } else {
            ValidationResult::Invalid("string must not be empty")
        }
    }

    fn description(&self) -> &'static str {
        "non-empty constraint"
    }
}

#[cfg(feature = "alloc")]
impl Constraint<alloc::string::String> for NonEmpty {
    fn validate(&self, value: &alloc::string::String) -> ValidationResult {
        if !value.is_empty() {
            ValidationResult::Valid
        } else {
            ValidationResult::Invalid("string must not be empty")
        }
    }

    fn description(&self) -> &'static str {
        "non-empty constraint"
    }
}

impl<T> Constraint<[T]> for NonEmpty {
    fn validate(&self, value: &[T]) -> ValidationResult {
        if !value.is_empty() {
            ValidationResult::Valid
        } else {
            ValidationResult::Invalid("collection must not be empty")
        }
    }

    fn description(&self) -> &'static str {
        "non-empty constraint"
    }
}

#[cfg(feature = "alloc")]
impl<T> Constraint<alloc::vec::Vec<T>> for NonEmpty {
    fn validate(&self, value: &alloc::vec::Vec<T>) -> ValidationResult {
        if !value.is_empty() {
            ValidationResult::Valid
        } else {
            ValidationResult::Invalid("collection must not be empty")
        }
    }

    fn description(&self) -> &'static str {
        "non-empty constraint"
    }
}

/// Pattern constraint for ASCII strings.
#[derive(Debug, Clone, Copy)]
pub struct AsciiOnly;

impl AsciiOnly {
    /// Create a new ASCII-only constraint.
    pub const fn new() -> Self {
        Self
    }
}

impl Default for AsciiOnly {
    fn default() -> Self {
        Self::new()
    }
}

impl Constraint<str> for AsciiOnly {
    fn validate(&self, value: &str) -> ValidationResult {
        if value.is_ascii() {
            ValidationResult::Valid
        } else {
            ValidationResult::Invalid("string must contain only ASCII characters")
        }
    }

    fn description(&self) -> &'static str {
        "ASCII-only constraint"
    }
}

#[cfg(feature = "alloc")]
impl Constraint<alloc::string::String> for AsciiOnly {
    fn validate(&self, value: &alloc::string::String) -> ValidationResult {
        if value.is_ascii() {
            ValidationResult::Valid
        } else {
            ValidationResult::Invalid("string must contain only ASCII characters")
        }
    }

    fn description(&self) -> &'static str {
        "ASCII-only constraint"
    }
}

/// Constraint that validates using a custom function.
pub struct CustomValidator<T, F>
where
    F: Fn(&T) -> bool,
{
    validator: F,
    error_message: &'static str,
    description: &'static str,
    _phantom: core::marker::PhantomData<T>,
}

impl<T, F> CustomValidator<T, F>
where
    F: Fn(&T) -> bool,
{
    /// Create a new custom validator.
    pub const fn new(validator: F, error_message: &'static str, description: &'static str) -> Self {
        Self {
            validator,
            error_message,
            description,
            _phantom: core::marker::PhantomData,
        }
    }
}

impl<T, F> Constraint<T> for CustomValidator<T, F>
where
    F: Fn(&T) -> bool,
{
    fn validate(&self, value: &T) -> ValidationResult {
        if (self.validator)(value) {
            ValidationResult::Valid
        } else {
            ValidationResult::Invalid(self.error_message)
        }
    }

    fn description(&self) -> &'static str {
        self.description
    }
}

/// Builder for common constraints.
pub struct Constraints;

impl Constraints {
    /// Create a maximum length constraint.
    pub const fn max_len(max: usize) -> MaxLength {
        MaxLength::new(max)
    }

    /// Create a minimum length constraint.
    pub const fn min_len(min: usize) -> MinLength {
        MinLength::new(min)
    }

    /// Create a non-empty constraint.
    pub const fn non_empty() -> NonEmpty {
        NonEmpty::new()
    }

    /// Create an ASCII-only constraint.
    pub const fn ascii_only() -> AsciiOnly {
        AsciiOnly::new()
    }

    /// Create a range constraint.
    pub fn range<T: PartialOrd + Clone>(min: Option<T>, max: Option<T>) -> Range<T> {
        Range::new(min, max)
    }

    /// Create a custom validator.
    pub const fn custom<T, F: Fn(&T) -> bool>(
        validator: F,
        error_message: &'static str,
        description: &'static str,
    ) -> CustomValidator<T, F> {
        CustomValidator::new(validator, error_message, description)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_max_length_str() {
        let constraint = MaxLength::new(10);

        assert!(constraint.validate("hello").is_valid());
        assert!(constraint.validate("0123456789").is_valid());
        assert!(constraint.validate("01234567890").is_invalid());
    }

    #[test]
    fn test_min_length_str() {
        let constraint = MinLength::new(3);

        assert!(constraint.validate("abc").is_valid());
        assert!(constraint.validate("abcd").is_valid());
        assert!(constraint.validate("ab").is_invalid());
    }

    #[test]
    fn test_range_i32() {
        let constraint = Range::new(Some(0i32), Some(100i32));

        assert!(constraint.validate(&0).is_valid());
        assert!(constraint.validate(&50).is_valid());
        assert!(constraint.validate(&100).is_valid());
        assert!(constraint.validate(&-1).is_invalid());
        assert!(constraint.validate(&101).is_invalid());
    }

    #[test]
    fn test_non_empty() {
        let constraint = NonEmpty::new();

        assert!(constraint.validate("hello").is_valid());
        assert!(constraint.validate("").is_invalid());
    }

    #[test]
    fn test_ascii_only() {
        let constraint = AsciiOnly::new();

        assert!(constraint.validate("hello world").is_valid());
        assert!(constraint.validate("hello 世界").is_invalid());
    }

    #[test]
    fn test_custom_validator() {
        let is_even = Constraints::custom(
            |x: &i32| x % 2 == 0,
            "value must be even",
            "even number constraint",
        );

        assert!(is_even.validate(&2).is_valid());
        assert!(is_even.validate(&4).is_valid());
        assert!(is_even.validate(&3).is_invalid());
    }

    #[test]
    fn test_validation_result() {
        let valid = ValidationResult::Valid;
        let invalid = ValidationResult::Invalid("test error");

        assert!(valid.is_valid());
        assert!(!valid.is_invalid());
        assert!(valid.error_message().is_none());

        assert!(!invalid.is_valid());
        assert!(invalid.is_invalid());
        assert_eq!(invalid.error_message(), Some("test error"));
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn test_vec_constraints() {
        let max_len = MaxLength::new(5);
        let min_len = MinLength::new(2);
        let non_empty = NonEmpty::new();

        let vec_short: alloc::vec::Vec<i32> = alloc::vec![1, 2];
        let vec_long: alloc::vec::Vec<i32> = alloc::vec![1, 2, 3, 4, 5, 6];
        let vec_empty: alloc::vec::Vec<i32> = alloc::vec![];

        assert!(max_len.validate(&vec_short).is_valid());
        assert!(max_len.validate(&vec_long).is_invalid());

        assert!(min_len.validate(&vec_short).is_valid());
        assert!(min_len.validate(&vec_empty).is_invalid());

        assert!(non_empty.validate(&vec_short).is_valid());
        assert!(non_empty.validate(&vec_empty).is_invalid());
    }

    #[test]
    fn test_constraints_builder() {
        let max = Constraints::max_len(100);
        let min = Constraints::min_len(1);
        let non_empty = Constraints::non_empty();
        let ascii = Constraints::ascii_only();
        let range = Constraints::range(Some(0u8), Some(255u8));

        assert!(max.validate("hello").is_valid());
        assert!(min.validate("h").is_valid());
        assert!(non_empty.validate("x").is_valid());
        assert!(ascii.validate("hello").is_valid());
        assert!(range.validate(&100u8).is_valid());
    }
}