Macro const_panic::coerce_fmt

source ·
macro_rules! coerce_fmt {
    ($reff:expr) => { ... };
}
Expand description

Coerces $reff to a type that has a to_panicvals method, which is expected to return a [PanicVal<'_>; LEN].

§Limitations

Arguments to the formatting/panicking macros must have a fully inferred concrete type, because const_panic macros use duck typing to call methods on those arguments.

One effect of that limitation is that you will have to pass suffixed integer literals (eg: 100u8) when those integers aren’t inferred to be a concrete type.

§Example

This example uses const_panic::ArrayString to show what the values format into, which requires the "non_basic" crate feature (enabled by default).

use const_panic::{ArrayString, FmtArg, IsCustomType, PanicFmt, PanicVal, coerce_fmt};

type AS = ArrayString<100>;

assert_eq!(
    AS::from_panicvals(&coerce_fmt!(100u8).to_panicvals(FmtArg::DEBUG)).unwrap(),
    "100",
);

assert_eq!(
    AS::from_panicvals(&coerce_fmt!("hello\n").to_panicvals(FmtArg::DEBUG)).unwrap(),
    r#""hello\n""#,
);

assert_eq!(
    AS::from_panicvals(&coerce_fmt!(IsReal::No).to_panicvals(FmtArg::DEBUG)).unwrap(),
    "No",
);

assert_eq!(
    AS::from_panicvals(&coerce_fmt!(IsReal::Yes).to_panicvals(FmtArg::DEBUG)).unwrap(),
    "Yes",
);



enum IsReal{Yes, No}

// All the code below manually implements panic formatting for a field-less enum.
// This can be written concisely with the `PanicFmt` derive or `impl_panicfmt` macro.
impl PanicFmt for IsReal {
    type This = Self;
    type Kind = IsCustomType;
    const PV_COUNT: usize = 1;
}

impl IsReal {
    pub const fn to_panicvals(&self, _f: FmtArg) -> [PanicVal<'_>; IsReal::PV_COUNT] {
        let x = match self {
            Self::Yes => "Yes",
            Self::No => "No",
        };
        [PanicVal::write_str(x)]
    }
}