Skip to main content

wasm_dbms_api/dbms/validate/
color.rs

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