ic_dbms_api/dbms/sanitize/
slug_sanitizer.rs1use crate::prelude::{IcDbmsResult, Sanitize, Value};
2
3pub 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}