Simplify `parse_param`

pull/1063/merge
Tamir Duberstein 3 weeks ago
parent 4f0559f2af
commit 1bf6a38619

@ -55,39 +55,27 @@ fn push_literal(frag: &mut Vec<Fragment>, unescaped_literal: &str) -> Result<(),
Ok(()) Ok(())
} }
/// Parses the display hint (e.g. the `ipv4` in `{:ipv4}`).
fn parse_display_hint(s: &str) -> Result<DisplayHint, String> {
Ok(match s {
"p" | "x" => DisplayHint::LowerHex,
"X" => DisplayHint::UpperHex,
"i" => DisplayHint::Ip,
"mac" => DisplayHint::LowerMac,
"MAC" => DisplayHint::UpperMac,
_ => return Err(format!("unknown display hint: {s:?}")),
})
}
/// Parse `Param` from the given `&str` which can specify an optional format /// Parse `Param` from the given `&str` which can specify an optional format
/// like `:x` or `:ipv4` (without curly braces, which are parsed by the `parse` /// like `:x` or `:ipv4` (without curly braces, which are parsed by the `parse`
/// function). /// function).
fn parse_param(mut input: &str) -> Result<Parameter, String> { fn parse_param(input: &str) -> Result<Parameter, String> {
const HINT_PREFIX: &str = ":"; let hint = match input.strip_prefix(":") {
Some(input) => match input {
// Then, optional hint "" => return Err("malformed format string (missing display hint after ':')".into()),
let mut hint = DisplayHint::Default; "p" | "x" => DisplayHint::LowerHex,
"X" => DisplayHint::UpperHex,
if input.starts_with(HINT_PREFIX) { "i" => DisplayHint::Ip,
// skip the prefix "mac" => DisplayHint::LowerMac,
input = &input[HINT_PREFIX.len()..]; "MAC" => DisplayHint::UpperMac,
if input.is_empty() { input => return Err(format!("unknown display hint: {input:?}")),
return Err("malformed format string (missing display hint after ':')".into()); },
None => {
if !input.is_empty() {
return Err(format!("unexpected content {input:?} in format string"));
}
DisplayHint::Default
} }
};
hint = parse_display_hint(input)?;
} else if !input.is_empty() {
return Err(format!("unexpected content {input:?} in format string"));
}
Ok(Parameter { hint }) Ok(Parameter { hint })
} }

Loading…
Cancel
Save