Trait FormatKey

Source
pub trait FormatKey {
    // Required method
    fn fmt(
        &self,
        key: &str,
        f: &mut Formatter<'_>,
    ) -> Result<(), FormatKeyError>;
}
Expand description

A trait like fmt::Display or fmt::Debug by with a keyed field.

It has a fmt method that accepts a fmt::Formatter argument. The important feature is the key field which indicates what value should be written to the formatter.

use runtime_format::{FormatArgs, FormatKey, FormatKeyError};
use core::fmt;
impl FormatKey for DateTime {
    fn fmt(&self, key: &str, f: &mut fmt::Formatter<'_>) -> Result<(), FormatKeyError> {
        use core::fmt::Write;
        match key {
            "year"    => write!(f, "{}", self.year()).map_err(FormatKeyError::Fmt),
            "month"   => write!(f, "{}", self.short_month_name()).map_err(FormatKeyError::Fmt),
            "day"     => write!(f, "{}", self.day()).map_err(FormatKeyError::Fmt),
            "hours"   => write!(f, "{}", self.hours()).map_err(FormatKeyError::Fmt),
            "minutes" => write!(f, "{}", self.minutes()).map_err(FormatKeyError::Fmt),
            "seconds" => write!(f, "{}", self.seconds()).map_err(FormatKeyError::Fmt),
            _ => Err(FormatKeyError::UnknownKey),
        }
    }
}

let now = DateTime::now();
let fmt = "{month} {day} {year} {hours}:{minutes}:{seconds}";
let args = FormatArgs::new(fmt, &now);
let expected = "Jan 25 2023 16:27:53";
assert_eq!(args.to_string(), expected);

Required Methods§

Source

fn fmt(&self, key: &str, f: &mut Formatter<'_>) -> Result<(), FormatKeyError>

Write the value with the associated with the given key to the formatter.

§Errors

If the formatter returns an error, or if the key is unknown.

Implementations on Foreign Types§

Source§

impl<K, V> FormatKey for BTreeMap<K, V>
where K: Borrow<str> + Ord, V: Display,

Source§

fn fmt(&self, key: &str, f: &mut Formatter<'_>) -> Result<(), FormatKeyError>

Source§

impl<K, V, S> FormatKey for HashMap<K, V, S>
where K: Borrow<str> + Eq + Hash, V: Display, S: BuildHasher,

Source§

fn fmt(&self, key: &str, f: &mut Formatter<'_>) -> Result<(), FormatKeyError>

Implementors§