garde/rules/
length.rs

1//! Length validation.
2//!
3//! ```rust
4//! #[derive(garde::Validate)]
5//! struct Test {
6//!     #[garde(length(min=1, max=100))]
7//!     v: String,
8//! }
9//! ```
10//!
11//! The concept of "length" is somewhat complicated, especially for strings. Therefore, the `length` rule currently supports different modes:
12//! - [`Simple`][simple::Simple], which is the default
13//! - [`Bytes`][bytes::Bytes]
14//! - [`Chars`][chars::Chars]
15//! - [`Graphemes`][graphemes::Graphemes]
16//! - [`Utf16CodeUnits`][utf16::Utf16CodeUnits]
17//!
18//! The mode is configured on the `length` rule:
19//! ```rust
20//! #[derive(garde::Validate)]
21//! struct Test {
22//!     #[garde(
23//!         length(graphemes, min=1, max=25),
24//!         length(bytes, min=1, max=100),
25//!     )]
26//!     v: String,
27//! }
28//! ```
29//!
30//! Here's what implementing the trait for a custom string-like type might look like:
31//! ```rust
32//! #[repr(transparent)]
33//! struct MyString(String);
34//!
35//! impl garde::rules::length::HasSimpleLength for MyString {
36//!     fn length(&self) -> usize {
37//!         self.0.len()
38//!     }
39//! }
40//! ```
41//!
42//! See each trait for more information.
43//!
44
45pub mod bytes;
46pub use bytes::HasBytes;
47
48pub mod chars;
49pub use chars::HasChars;
50
51#[cfg(feature = "unicode")]
52pub mod graphemes;
53#[cfg(feature = "unicode")]
54pub use graphemes::HasGraphemes;
55
56pub mod simple;
57pub use simple::HasSimpleLength;
58
59pub mod utf16;
60pub use utf16::HasUtf16CodeUnits;
61
62use crate::error::Error;
63
64fn check_len(len: usize, min: usize, max: usize) -> Result<(), Error> {
65    if len < min {
66        Err(Error::new(format!("length is lower than {min}")))
67    } else if len > max {
68        Err(Error::new(format!("length is greater than {max}")))
69    } else {
70        Ok(())
71    }
72}