| 1 | use std::collections::HashMap; |
| 2 | use std::fmt::{Debug, Display}; |
| 3 | use std::str::FromStr; |
| 4 | |
| 5 | use crate::error::Error; |
| 6 | use crate::placeholder::Placeholder; |
| 7 | |
| 8 | /// String template with [std::fmt](std::fmt) syntax. |
| 9 | /// |
| 10 | /// # Example |
| 11 | /// |
| 12 | /// ``` |
| 13 | /// use formatx::Template; |
| 14 | /// |
| 15 | /// let mut template = "{percentage:.2}".parse::<Template>().unwrap(); |
| 16 | /// template.replace("percentage", 67.7892); |
| 17 | /// assert_eq!(template.text().unwrap(), "67.79"); |
| 18 | /// ``` |
| 19 | #[derive(Debug, Clone)] |
| 20 | pub struct Template { |
| 21 | template: String, |
| 22 | position: usize, |
| 23 | placeholders: HashMap<String, Vec<Placeholder>>, |
| 24 | } |
| 25 | |
| 26 | impl Display for Template { |
| 27 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 28 | write!(f, "{}", self.unchecked_text()) |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | impl FromStr for Template { |
| 33 | type Err = Error; |
| 34 | |
| 35 | fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 36 | Self::new(s) |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | impl Template { |
| 41 | /// Create a new instance of `format_template::Template`. |
| 42 | /// |
| 43 | /// # Example |
| 44 | /// |
| 45 | /// ``` |
| 46 | /// use formatx::Template; |
| 47 | /// |
| 48 | /// let template = Template::new("{percentage:.2}").unwrap(); |
| 49 | /// ``` |
| 50 | pub fn new<T: Into<String>>(template: T) -> Result<Self, Error> { |
| 51 | let mut template_struct = Self { |
| 52 | template: { |
| 53 | // Escaping curly braces |
| 54 | let mut template = template.into().replace("{{", "[curly=open]"); |
| 55 | |
| 56 | while let Some(curly_close) = template.rfind("}}") { |
| 57 | template.replace_range(curly_close..=(curly_close + 1), "[curly=close]"); |
| 58 | } |
| 59 | |
| 60 | template |
| 61 | }, |
| 62 | position: 0, |
| 63 | placeholders: HashMap::new(), |
| 64 | }; |
| 65 | |
| 66 | // Checking number curly braces |
| 67 | let curly_open_count = template_struct |
| 68 | .template |
| 69 | .chars() |
| 70 | .filter(|x| x.to_string() == "{") |
| 71 | .count(); |
| 72 | let curly_close_count = template_struct |
| 73 | .template |
| 74 | .chars() |
| 75 | .filter(|x| x.to_string() == "}") |
| 76 | .count(); |
| 77 | |
| 78 | if curly_open_count != curly_close_count { |
| 79 | return Err(Error::new_parse(format!( |
| 80 | "number of opening and closing curly braces are not equal i.e. {} != {}", |
| 81 | curly_open_count, curly_close_count |
| 82 | ))); |
| 83 | } |
| 84 | |
| 85 | // Adding position for positional placeholders. |
| 86 | let mut position = 0; |
| 87 | let placeholders = template_struct.get_placeholders(); |
| 88 | |
| 89 | while template_struct.template.contains("{}") || template_struct.template.contains("{:") { |
| 90 | while placeholders.contains(&position.to_string()) { |
| 91 | position += 1; |
| 92 | } |
| 93 | |
| 94 | match ( |
| 95 | template_struct.template.find("{}"), |
| 96 | template_struct.template.find("{:"), |
| 97 | ) { |
| 98 | (Some(_), None) => { |
| 99 | template_struct.template = |
| 100 | template_struct |
| 101 | .template |
| 102 | .replacen("{}", &format!("{{{}}}", position), 1); |
| 103 | position += 1; |
| 104 | } |
| 105 | (None, Some(_)) => { |
| 106 | template_struct.template = |
| 107 | template_struct |
| 108 | .template |
| 109 | .replacen("{:", &format!("{{{}:", position), 1); |
| 110 | position += 1; |
| 111 | } |
| 112 | (Some(x), Some(y)) => { |
| 113 | if y > x { |
| 114 | template_struct.template = template_struct.template.replacen( |
| 115 | "{}", |
| 116 | &format!("{{{}}}", position), |
| 117 | 1, |
| 118 | ); |
| 119 | } else { |
| 120 | template_struct.template = |
| 121 | template_struct |
| 122 | .template |
| 123 | .replacen("{:", &format!("{{{}:", position), 1); |
| 124 | } |
| 125 | |
| 126 | position += 1; |
| 127 | } |
| 128 | (None, None) => (), |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | // Parsing placeholders |
| 133 | let mut query_template = template_struct.template.clone(); |
| 134 | |
| 135 | for name in template_struct.get_placeholders() { |
| 136 | let placeholder = Placeholder::new(&query_template, &name); |
| 137 | let placeholder = placeholder?.unwrap(); |
| 138 | query_template = query_template.replacen(&placeholder.replacer, "", 1); |
| 139 | |
| 140 | if let Some(children) = template_struct.placeholders.get_mut(&name) { |
| 141 | children.push(placeholder); |
| 142 | } else { |
| 143 | template_struct |
| 144 | .placeholders |
| 145 | .insert(name.to_owned(), vec![placeholder]); |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | Ok(template_struct) |
| 150 | } |
| 151 | |
| 152 | /// Returns list of template placeholders names. |
| 153 | fn get_placeholders(&self) -> Vec<String> { |
| 154 | let mut placeholders = vec![]; |
| 155 | let mut template = self.template.clone(); |
| 156 | |
| 157 | while template.contains('{') && template.contains('}') { |
| 158 | if let (Some(start), Some(end)) = (template.find('{'), template.find('}')) { |
| 159 | let placeholder = template[(start + 1)..end].to_owned(); |
| 160 | template.replace_range(start..=end, ""); |
| 161 | |
| 162 | if let Some(colon) = placeholder.find(':') { |
| 163 | placeholders.push(placeholder[..colon].split(' ').next().unwrap().to_owned()); |
| 164 | } else { |
| 165 | placeholders.push(placeholder.split(' ').next().unwrap().to_owned()); |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | placeholders |
| 171 | } |
| 172 | |
| 173 | /// Checks wheter template contains placeholder or not. |
| 174 | pub fn contains<T: ToString>(&self, placeholder: T) -> bool { |
| 175 | self.placeholders.contains_key(&placeholder.to_string()) |
| 176 | } |
| 177 | |
| 178 | /// Returns unchecked formatted template. |
| 179 | /// For `Result` version of fomatted template use `.text` method. |
| 180 | pub fn unchecked_text(&self) -> String { |
| 181 | self.template |
| 182 | .replace("[curly=open]", "{") |
| 183 | .replace("[curly=close]", "}") |
| 184 | } |
| 185 | |
| 186 | /// Checks wheter all placeholders are replaced or not and returns formatted template. |
| 187 | pub fn text(&self) -> Result<String, Error> { |
| 188 | if self.placeholders.is_empty() { |
| 189 | Ok(self.unchecked_text()) |
| 190 | } else { |
| 191 | Err(Error::new_values(format!( |
| 192 | "missing placeholders values for: {}", |
| 193 | self.placeholders |
| 194 | .keys() |
| 195 | .map(|x| { |
| 196 | if x.parse::<usize>().is_ok() { |
| 197 | format!("{} (positional)", x) |
| 198 | } else { |
| 199 | format!("{} (named)", x) |
| 200 | } |
| 201 | }) |
| 202 | .collect::<Vec<String>>() |
| 203 | .join(", ") |
| 204 | ))) |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | /// Replace a template placeholder with a value. |
| 209 | /// This change is inplace. |
| 210 | pub fn replace<T, U>(&mut self, placeholder: T, value: U) |
| 211 | where |
| 212 | T: ToString, |
| 213 | U: Display + Debug, |
| 214 | { |
| 215 | self.replace_with_callback(placeholder, value, |formatted_value, _| formatted_value) |
| 216 | } |
| 217 | |
| 218 | /// Replace a template positional placeholder with a value. |
| 219 | /// This change is inplace. |
| 220 | pub fn replace_positional<T>(&mut self, value: T) |
| 221 | where |
| 222 | T: Display + Debug, |
| 223 | { |
| 224 | self.replace_with_callback(self.position.to_string(), value, |formatted_value, _| { |
| 225 | formatted_value |
| 226 | }); |
| 227 | self.position += 1; |
| 228 | } |
| 229 | |
| 230 | /// Replace a template placeholder from a callback `String`. |
| 231 | /// This change is inplace. |
| 232 | pub fn replace_from_callback<T, U>(&mut self, placeholder: T, callback: U) |
| 233 | where |
| 234 | T: ToString, |
| 235 | U: Fn(&Placeholder) -> String, |
| 236 | { |
| 237 | let placeholder = placeholder.to_string(); |
| 238 | |
| 239 | if let Some(placeholders) = self.placeholders.get(&placeholder) { |
| 240 | for holder in placeholders { |
| 241 | self.template = self.template.replace(&holder.replacer, &callback(holder)); |
| 242 | } |
| 243 | |
| 244 | let _ = self.placeholders.remove(&placeholder); |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | /// Replace a template placeholder with a value and do additional formatting using callback. |
| 249 | /// This change is inplace. |
| 250 | pub fn replace_with_callback<T, U, V>(&mut self, placeholder: T, value: U, callback: V) |
| 251 | where |
| 252 | T: ToString, |
| 253 | U: Display + Debug, |
| 254 | V: Fn(String, &Placeholder) -> String, |
| 255 | { |
| 256 | let placeholder = placeholder.to_string(); |
| 257 | |
| 258 | if let Some(placeholders) = self.placeholders.get(&placeholder) { |
| 259 | for holder in placeholders { |
| 260 | self.template = self.template.replace( |
| 261 | &holder.replacer, |
| 262 | &callback(holder.format_spec.format(&value), holder), |
| 263 | ); |
| 264 | } |
| 265 | |
| 266 | let _ = self.placeholders.remove(&placeholder); |
| 267 | } |
| 268 | } |
| 269 | } |