From 2fb052d68cb46680c081f5a0e25e2c3fbdc9e204 Mon Sep 17 00:00:00 2001 From: heyrict Date: Wed, 22 Apr 2020 17:02:09 +0800 Subject: [PATCH] feat: Add map_style method to feed values in style string --- src/formatter/string_formatter.rs | 88 ++++++++++++++++++++++++------- 1 file changed, 69 insertions(+), 19 deletions(-) diff --git a/src/formatter/string_formatter.rs b/src/formatter/string_formatter.rs index 62843f156..88dfaa52a 100644 --- a/src/formatter/string_formatter.rs +++ b/src/formatter/string_formatter.rs @@ -22,10 +22,12 @@ impl Default for VariableValue { } type VariableMapType = BTreeMap>; +type StyleVariableMapType = BTreeMap>; pub struct StringFormatter<'a> { format: Vec>, variables: VariableMapType, + style_variables: StyleVariableMapType, } impl<'a> StringFormatter<'a> { @@ -33,10 +35,14 @@ impl<'a> StringFormatter<'a> { pub fn new(format: &'a str) -> Result> { parse(format) .map(|format| { - let variables = _get_variables(&format); - (format, variables) + let (variables, style_variables) = _get_variables(&format); + (format, variables, style_variables) + }) + .map(|(format, variables, style_variables)| Self { + format, + variables, + style_variables, }) - .map(|(format, variables)| Self { format, variables }) } /// Maps variable name to its value @@ -58,27 +64,43 @@ impl<'a> StringFormatter<'a> { self } + /// Maps variable name in a style string to its value + pub fn map_style(mut self, mapper: impl Fn(&str) -> Option + Sync) -> Self { + self.style_variables + .par_iter_mut() + .for_each(|(key, value)| { + *value = mapper(key); + }); + self + } + /// Parse the format string and consume self. pub fn parse(self, default_style: Option