Skip to main content

ic_dbms_api/dbms/sanitize/
trim.rs

1use crate::prelude::{IcDbmsResult, Sanitize, Value};
2
3/// Sanitizer that trims leading and trailing whitespace from strings.
4///
5/// # Example
6///
7/// ```rust
8/// use ic_dbms_api::prelude::{TrimSanitizer, Value, Sanitize as _};
9///
10/// let value = Value::Text("  Hello, World!  ".into());
11/// let sanitizer = TrimSanitizer;
12/// let sanitized_value = sanitizer.sanitize(value).unwrap();
13/// assert_eq!(sanitized_value, Value::Text("Hello, World!".into()));
14/// ```
15pub struct TrimSanitizer;
16
17impl Sanitize for TrimSanitizer {
18    fn sanitize(&self, value: Value) -> IcDbmsResult<Value> {
19        match value {
20            Value::Text(text) => Ok(Value::Text(text.as_str().trim().into())),
21            other => Ok(other),
22        }
23    }
24}
25
26#[cfg(test)]
27mod tests {
28
29    use super::*;
30
31    #[test]
32    fn test_trim_sanitizer() {
33        let sanitizer = TrimSanitizer;
34        let string_with_whitespace = Value::Text("  Hello, World!  ".into());
35        let string_without_whitespace = Value::Text("Hello".into());
36        let number_value = Value::Int32(42.into());
37
38        let sanitized_with_whitespace = sanitizer.sanitize(string_with_whitespace).unwrap();
39        let sanitized_without_whitespace = sanitizer.sanitize(string_without_whitespace).unwrap();
40        let sanitized_number = sanitizer.sanitize(number_value).unwrap();
41
42        assert_eq!(
43            sanitized_with_whitespace,
44            Value::Text("Hello, World!".into())
45        );
46        assert_eq!(sanitized_without_whitespace, Value::Text("Hello".into()));
47        assert_eq!(sanitized_number, Value::Int32(42.into()));
48    }
49}