ic_dbms_api/validate/
color.rs

1use ic_dbms_api::prelude::Value;
2
3use crate::prelude::Validate;
4
5/// A validator for RGB color strings.
6///
7/// An RGB color string must be in the format `#RRGGBB`, where `RR`, `GG`, and `BB` are
8/// two-digit hexadecimal numbers representing the red, green, and blue components of the color.
9///
10/// # Examples
11///
12/// ```rust
13/// use ic_dbms_api::prelude::{RgbColorValidator, Value, Validate};
14///
15/// let validator = RgbColorValidator;
16/// let valid_color = Value::Text(ic_dbms_api::prelude::Text("#1A2B3C".into()));
17/// assert!(validator.validate(&valid_color).is_ok());
18/// ```
19pub struct RgbColorValidator;
20
21impl Validate for RgbColorValidator {
22    fn validate(&self, value: &Value) -> ic_dbms_api::prelude::IcDbmsResult<()> {
23        let Value::Text(text) = value else {
24            return Err(ic_dbms_api::prelude::IcDbmsError::Validation(
25                "RGB color validation requires a text value".to_string(),
26            ));
27        };
28
29        let s = &text.0;
30        if s.len() != 7 || !s.starts_with('#') {
31            return Err(ic_dbms_api::prelude::IcDbmsError::Validation(
32                "Invalid RGB color format".to_string(),
33            ));
34        }
35        for c in s.chars().skip(1) {
36            if !c.is_ascii_hexdigit() {
37                return Err(ic_dbms_api::prelude::IcDbmsError::Validation(
38                    "Invalid RGB color format".to_string(),
39                ));
40            }
41        }
42
43        Ok(())
44    }
45}
46
47#[cfg(test)]
48mod tests {
49
50    use ic_dbms_api::prelude::Value;
51
52    use super::*;
53
54    #[test]
55    fn test_rgb_color_validator() {
56        let validator = RgbColorValidator;
57
58        // Valid RGB color
59        let value = Value::Text(ic_dbms_api::prelude::Text("#1A2B3C".to_string()));
60        assert!(validator.validate(&value).is_ok());
61
62        // Invalid RGB color (wrong length)
63        let value = Value::Text(ic_dbms_api::prelude::Text("#1A2B3".to_string()));
64        assert!(validator.validate(&value).is_err());
65
66        // Invalid RGB color (missing #)
67        let value = Value::Text(ic_dbms_api::prelude::Text("1A2B3C".to_string()));
68        assert!(validator.validate(&value).is_err());
69
70        // Invalid RGB color (non-hex character)
71        let value = Value::Text(ic_dbms_api::prelude::Text("#1A2B3G".to_string()));
72        assert!(validator.validate(&value).is_err());
73
74        // Invalid type
75        let value = Value::Int32(123i32.into());
76        assert!(validator.validate(&value).is_err());
77    }
78}