ic_dbms_api/dbms/sanitize/
slug_sanitizer.rs

1use crate::prelude::{IcDbmsResult, Sanitize, Value};
2
3/// Sanitizer sluggifies strings by converting them to lowercase, replacing spaces with hyphens,
4/// and removing non-alphanumeric characters.
5///
6/// # Example
7///
8/// ```rust
9/// use ic_dbms_api::prelude::{SlugSanitizer, Value, Sanitize as _};
10///
11/// let value = Value::Text("  Hello,       World!  ".into());
12/// let sanitizer = SlugSanitizer;
13/// let sanitized_value = sanitizer.sanitize(value).unwrap();
14/// assert_eq!(sanitized_value, Value::Text("hello-world".into()));
15/// ```
16pub struct SlugSanitizer;
17
18impl Sanitize for SlugSanitizer {
19    fn sanitize(&self, value: Value) -> IcDbmsResult<Value> {
20        match value {
21            Value::Text(text) => {
22                let slug = text
23                    .as_str()
24                    .to_lowercase()
25                    .split_whitespace()
26                    .collect::<Vec<_>>()
27                    .join("-")
28                    .chars()
29                    .filter(|c| c.is_alphanumeric() || *c == '-')
30                    .collect::<String>();
31                Ok(Value::Text(slug.into()))
32            }
33            other => Ok(other),
34        }
35    }
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41
42    #[test]
43    fn test_slug_sanitizer() {
44        let sanitizer = SlugSanitizer;
45        let string_value = Value::Text("  Hello,          World!  ".into());
46        let number_value = Value::Int32(42.into());
47
48        let sanitized_string = sanitizer.sanitize(string_value).unwrap();
49        let sanitized_number = sanitizer.sanitize(number_value).unwrap();
50
51        assert_eq!(sanitized_string, Value::Text("hello-world".into()));
52        assert_eq!(sanitized_number, Value::Int32(42.into()));
53    }
54}