use std::collections::HashMap;
use lazy_regex::*;
pub trait LateFormat {
fn lateformat(&self, arguments: HashMap<String, String>) -> String;
}
impl LateFormat for &str {
fn lateformat(&self, arguments: HashMap<String, String>) -> String {
regex_replace_all!(
r#"(?x)
\{\s*(
([a-zA-Z_0-9\-\.\$]+) | # parameter
("([^\u{22}])*") # escaped
)\s*\}
"#,
self,
|_, s: &str, _, _, _| {
if s.starts_with('"') {
return s[1..s.len() - 1].to_owned().clone();
}
arguments.get(s).map_or("None".to_owned(), |v| v.clone())
}
).into_owned()
}
}
impl LateFormat for String {
fn lateformat(&self, arguments: HashMap<String, String>) -> String {
self.as_str().lateformat(arguments)
}
}
#[cfg(test)]
mod test {
use super::*;
use maplit::hashmap;
#[test]
fn formatting() {
let user_string: String = "some user string: {id}".into();
assert_eq!("some user string: x", user_string.lateformat(hashmap!{"id".into() => "x".into()}));
let user_string: String = r#"some user string: {"id"}"#.into();
assert_eq!("some user string: id", user_string.lateformat(hashmap!{"id".into() => "x".into()}));
let user_string: String = r#"some user string: { "id" }"#.into();
assert_eq!("some user string: id", user_string.lateformat(hashmap!{"id".into() => "x".into()}));
let user_string: String = "some user string: {id}".into();
assert_eq!("some user string: None", user_string.lateformat(hashmap!{}));
}
}