| 1 | //! strfmt crate |
| 2 | |
| 3 | use std::collections::HashMap; |
| 4 | use std::fmt; |
| 5 | use std::fmt::Write; |
| 6 | use std::hash::Hash; |
| 7 | use std::str::FromStr; |
| 8 | use std::string::String; |
| 9 | |
| 10 | mod fmtstr; |
| 11 | mod formatter; |
| 12 | #[cfg(test)] |
| 13 | mod tests; |
| 14 | mod types; |
| 15 | |
| 16 | #[macro_use] |
| 17 | mod fmtnum; |
| 18 | mod macros; |
| 19 | |
| 20 | pub use fmtstr::strfmt_map; |
| 21 | pub use formatter::Formatter; |
| 22 | pub use types::{Alignment, FmtError, Result, Sign}; |
| 23 | |
| 24 | // u128 & i128 unstable (see https://github.com/rust-lang/rust/issues/35118) |
| 25 | fmtint!(u8 i8 u16 i16 u32 i32 u64 i64 usize isize); |
| 26 | fmtfloat!(f32 f64); |
| 27 | |
| 28 | /// Rust-style format a string given a `HashMap` of the variables. |
| 29 | /// # Arguments |
| 30 | /// |
| 31 | /// * `fmtstr` - A string defining the format |
| 32 | /// * `vars` - A `HashMap` holding the variables to use |
| 33 | /// |
| 34 | /// # Exceptions |
| 35 | /// |
| 36 | /// * [FmtError::Invalid] - The format string is structured incorrectly |
| 37 | /// * [FmtError::KeyError] - `vars` contains an invalid key |
| 38 | /// * [FmtError::TypeError] - the given format code for a section contains an unexpected option |
| 39 | /// |
| 40 | /// # Examples |
| 41 | /// |
| 42 | /// ``` |
| 43 | /// use std::collections::HashMap; |
| 44 | /// use std::f64::consts::PI; |
| 45 | /// use strfmt::strfmt; |
| 46 | /// |
| 47 | /// let mut my_vars: HashMap<String, f64> = HashMap::new(); |
| 48 | /// my_vars.insert("Alpha".to_string(),42.0); |
| 49 | /// my_vars.insert("Beta".to_string(),PI); |
| 50 | /// |
| 51 | /// println!("{}", strfmt("{Alpha} {Beta:<5.2}",&my_vars).unwrap()); |
| 52 | /// ``` |
| 53 | pub fn strfmt<'a, K, T: DisplayStr>(fmtstr: &str, vars: &HashMap<K, T>) -> Result<String> |
| 54 | where |
| 55 | K: Hash + Eq + FromStr, |
| 56 | { |
| 57 | let formatter = |mut fmt: Formatter| { |
| 58 | let k: K = match fmt.key.parse() { |
| 59 | Ok(k) => k, |
| 60 | Err(_) => { |
| 61 | return Err(new_key_error(fmt.key)); |
| 62 | } |
| 63 | }; |
| 64 | let v = match vars.get(&k) { |
| 65 | Some(v) => v, |
| 66 | None => { |
| 67 | return Err(new_key_error(fmt.key)); |
| 68 | } |
| 69 | }; |
| 70 | v.display_str(&mut fmt) |
| 71 | }; |
| 72 | strfmt_map(fmtstr, &formatter) |
| 73 | } |
| 74 | |
| 75 | /// Rust-style format a string given a `HashMap` of the variables. |
| 76 | /// see [strfmt] for details |
| 77 | #[deprecated( |
| 78 | since = "0.2.0", |
| 79 | note = "This function contains a bug when formatting numbers. Use strfmt instead" |
| 80 | )] |
| 81 | pub fn strfmt_display<'a, K, T: fmt::Display>(fmtstr: &str, vars: &HashMap<K, T>) -> Result<String> |
| 82 | where |
| 83 | K: Hash + Eq + FromStr, |
| 84 | { |
| 85 | let formatter = |mut fmt: Formatter| { |
| 86 | let k: K = match fmt.key.parse() { |
| 87 | Ok(k) => k, |
| 88 | Err(_) => { |
| 89 | return Err(new_key_error(fmt.key)); |
| 90 | } |
| 91 | }; |
| 92 | let v = match vars.get(&k) { |
| 93 | Some(v) => v, |
| 94 | None => { |
| 95 | return Err(new_key_error(fmt.key)); |
| 96 | } |
| 97 | }; |
| 98 | fmt.str(v.to_string().as_str()) |
| 99 | }; |
| 100 | strfmt_map(fmtstr, &formatter) |
| 101 | } |
| 102 | |
| 103 | macro_rules! display_str_impl { |
| 104 | ($($t:ident)*) => ($( |
| 105 | impl DisplayStr for $t { |
| 106 | fn display_str(&self,f:&mut Formatter) -> Result<()> { |
| 107 | f.$t(*self) |
| 108 | } |
| 109 | } |
| 110 | )*) |
| 111 | } |
| 112 | |
| 113 | display_str_impl!(u8 i8 u16 i16 u32 i32 u64 i64 usize isize); |
| 114 | display_str_impl!(f32 f64); |
| 115 | |
| 116 | impl DisplayStr for String { |
| 117 | fn display_str(&self, f: &mut Formatter) -> Result<()> { |
| 118 | f.str(self.as_str()) |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | impl DisplayStr for &str { |
| 123 | fn display_str(&self, f: &mut Formatter) -> Result<()> { |
| 124 | f.str(self) |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | impl DisplayStr for &dyn DisplayStr { |
| 129 | fn display_str(&self, f: &mut Formatter) -> Result<()> { |
| 130 | (*self).display_str(f) |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | impl DisplayStr for Box<dyn DisplayStr> { |
| 135 | fn display_str(&self, f: &mut Formatter) -> Result<()> { |
| 136 | self.as_ref().display_str(f) |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | /// This trait is effectively an re-implementation for [std::fmt::Display] |
| 141 | /// It is used to disguise between the value types that should be formatted |
| 142 | pub trait DisplayStr { |
| 143 | fn display_str(&self, f: &mut Formatter) -> Result<()>; |
| 144 | } |
| 145 | |
| 146 | /// This trait is a shortcut for [strfmt] |
| 147 | /// for an example see [Format::format] |
| 148 | pub trait Format { |
| 149 | /// format a string using strfmt |
| 150 | /// # Arguments |
| 151 | /// |
| 152 | /// * `vars` - A `HashMap` holding the variables to use |
| 153 | /// |
| 154 | /// # Errors |
| 155 | /// Errors are passed directly from strfmt, for details see [strfmt] |
| 156 | /// |
| 157 | /// # Examples |
| 158 | /// |
| 159 | /// ``` |
| 160 | /// use std::collections::HashMap; |
| 161 | /// use std::f64::consts::PI; |
| 162 | /// use strfmt::Format; |
| 163 | /// |
| 164 | /// let mut my_vars: HashMap<String, f64> = HashMap::new(); |
| 165 | /// my_vars.insert("Alpha".to_string(),42.0); |
| 166 | /// my_vars.insert("Beta".to_string(),PI); |
| 167 | /// |
| 168 | /// println!("{}", "|{Alpha}|{Beta:<5.2}|".format(&my_vars).unwrap()); |
| 169 | /// ``` |
| 170 | fn format<K, D: DisplayStr>(&self, vars: &HashMap<K, D>) -> Result<String> |
| 171 | where |
| 172 | K: Hash + Eq + FromStr; |
| 173 | |
| 174 | /// format a string using strfmt_display |
| 175 | /// see [Format::format] for usage |
| 176 | #[deprecated( |
| 177 | since = "0.2.0", |
| 178 | note = "This function contains a bug when formatting numbers. Use format instead" |
| 179 | )] |
| 180 | fn format_display<K, D: fmt::Display>(&self, vars: &HashMap<K, D>) -> Result<String> |
| 181 | where |
| 182 | K: Hash + Eq + FromStr; |
| 183 | } |
| 184 | |
| 185 | impl Format for String { |
| 186 | fn format<'a, K, D: DisplayStr>(&self, vars: &HashMap<K, D>) -> Result<String> |
| 187 | where |
| 188 | K: Hash + Eq + FromStr, |
| 189 | { |
| 190 | strfmt(self.as_str(), vars) |
| 191 | } |
| 192 | fn format_display<'a, K, D: fmt::Display>(&self, vars: &HashMap<K, D>) -> Result<String> |
| 193 | where |
| 194 | K: Hash + Eq + FromStr, |
| 195 | { |
| 196 | #[allow(deprecated)] |
| 197 | strfmt_display(self.as_str(), vars) |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | impl Format for str { |
| 202 | fn format<K, D: DisplayStr>(&self, vars: &HashMap<K, D>) -> Result<String> |
| 203 | where |
| 204 | K: Hash + Eq + FromStr, |
| 205 | { |
| 206 | strfmt(self, vars) |
| 207 | } |
| 208 | fn format_display<'a, K, D: fmt::Display>(&self, vars: &HashMap<K, D>) -> Result<String> |
| 209 | where |
| 210 | K: Hash + Eq + FromStr, |
| 211 | { |
| 212 | #[allow(deprecated)] |
| 213 | strfmt_display(self, vars) |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | fn new_key_error(key: &str) -> FmtError { |
| 218 | let mut msg = String::new(); |
| 219 | write!(msg, "Invalid key: {}", key).unwrap(); |
| 220 | FmtError::KeyError(msg) |
| 221 | } |