Trait CustomFormat

Source
pub trait CustomFormat {
    // Required method
    fn fmt(&self, f: &mut Formatter<'_>, spec: &str) -> Result;
}
Available on crate feature runtime only.
Expand description

Trait for custom formatting with runtime format checking

Required Methods§

Source

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

Formats the value using the given formatter.

§Examples
use custom_format as cfmt;

use core::fmt;

#[derive(Debug)]
struct Hex(u8);

impl cfmt::runtime::CustomFormat for Hex {
    fn fmt(&self, f: &mut fmt::Formatter, spec: &str) -> fmt::Result {
        match spec {
            "x" => write!(f, "{:#02x}", self.0),
            "X" => write!(f, "{:#02X}", self.0),
            _ => Err(fmt::Error),
        }
    }
}

// The custom format specifier is interpreted as a runtime specifier when it is inside "<>"
assert_eq!(cfmt::format!("{0:X?}, {0 :<x>}, {0 :<X>}", Hex(0xAB)), "Hex(AB), 0xab, 0xAB");

The following statement panics at runtime since "z" is not a valid format specifier:

cfmt::println!("{ :<z>}", Hex(0));

Implementors§