Crate runtime_format

Source
Expand description

Formatting, but processed at runtime.

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);

See ParsedFmt if you need to repeatedly format a given string, but with different args.

Structs§

FormatArgs
Performs formatting.
FromStr
An Iterator of ParseSegments. Returned by of str::to_parser.
ParsedFmt
Preparsed formatting terms.

Enums§

FormatError
Error returned when formatting or parsing.
FormatKeyError
Error produced when formatting
ParseSegment
An enum representing the parsed portion of a format string

Traits§

FormatKey
A trait like fmt::Display or fmt::Debug by with a keyed field.
ToFormatParser
Turn a value into parsed formatting segments on the fly.