Skip to main content

overpass_lib/query/
util.rs

1use std::fmt::{Display, Formatter, Result as FResult};
2
3/// Handles string sanitization for OverpassQL queries.
4/// 
5/// Wraps the input string in double-quotes and escapes any double-quotes in the original string.
6/// 
7/// Example:
8/// ```
9/// # use overpass_lib::SaniStr;
10/// let sani = SaniStr(r#"Dwayne "The Rock" Johnson"#);
11/// assert_eq!(sani.to_string(), String::from(r#""Dwayne \"The Rock\" Johnson""#))
12/// ```
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub struct SaniStr<'a>(pub &'a str);
15
16impl<'a> From<&'a str> for SaniStr<'a> {
17    fn from(value: &'a str) -> Self {
18        Self(value)
19    }
20}
21
22impl Display for SaniStr<'_> {
23    fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
24        let mut iter = self.0.split('"');
25        write!(f, r#""{}"#, iter.next().unwrap())?;
26        for i in iter {
27            write!(f, r#"\"{i}"#)?;
28        }
29        write!(f, r#"""#)
30    }
31}
32