skp_validator_rules/transform/
whitespace.rs

1//! Whitespace transformation rules (trim).
2
3use skp_validator_core::Transform;
4
5/// Trim transformation - removes leading and trailing whitespace.
6///
7/// # Example
8///
9/// ```rust
10/// use skp_validator_rules::transform::whitespace::TrimTransform;
11/// use skp_validator_core::Transform;
12///
13/// let transform = TrimTransform;
14/// assert_eq!(transform.transform("  hello  ".to_string()), "hello");
15/// ```
16#[derive(Debug, Clone, Copy, Default)]
17pub struct TrimTransform;
18
19impl Transform<String> for TrimTransform {
20    fn transform(&self, value: String) -> String {
21        value.trim().to_string()
22    }
23
24    fn name(&self) -> &'static str {
25        "trim"
26    }
27}
28
29/// Trim start transformation - removes leading whitespace.
30#[derive(Debug, Clone, Copy, Default)]
31pub struct TrimStartTransform;
32
33impl Transform<String> for TrimStartTransform {
34    fn transform(&self, value: String) -> String {
35        value.trim_start().to_string()
36    }
37
38    fn name(&self) -> &'static str {
39        "trim_start"
40    }
41}
42
43/// Trim end transformation - removes trailing whitespace.
44#[derive(Debug, Clone, Copy, Default)]
45pub struct TrimEndTransform;
46
47impl Transform<String> for TrimEndTransform {
48    fn transform(&self, value: String) -> String {
49        value.trim_end().to_string()
50    }
51
52    fn name(&self) -> &'static str {
53        "trim_end"
54    }
55}
56
57/// Collapse whitespace transformation - replaces multiple spaces with single space.
58#[derive(Debug, Clone, Copy, Default)]
59pub struct CollapseWhitespaceTransform;
60
61impl Transform<String> for CollapseWhitespaceTransform {
62    fn transform(&self, value: String) -> String {
63        value.split_whitespace().collect::<Vec<_>>().join(" ")
64    }
65
66    fn name(&self) -> &'static str {
67        "collapse_whitespace"
68    }
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74
75    #[test]
76    fn test_trim() {
77        let transform = TrimTransform;
78        assert_eq!(transform.transform("  hello  ".to_string()), "hello");
79        assert_eq!(transform.transform("\t\nhello\n\t".to_string()), "hello");
80        assert_eq!(transform.transform("hello".to_string()), "hello");
81    }
82
83    #[test]
84    fn test_trim_start() {
85        let transform = TrimStartTransform;
86        assert_eq!(transform.transform("  hello  ".to_string()), "hello  ");
87    }
88
89    #[test]
90    fn test_trim_end() {
91        let transform = TrimEndTransform;
92        assert_eq!(transform.transform("  hello  ".to_string()), "  hello");
93    }
94
95    #[test]
96    fn test_collapse_whitespace() {
97        let transform = CollapseWhitespaceTransform;
98        assert_eq!(transform.transform("hello   world".to_string()), "hello world");
99        assert_eq!(transform.transform("  hello   world  ".to_string()), "hello world");
100    }
101}