Macro const_panic::inline_macro
source · [−]macro_rules! inline_macro {
(
$(($($args:tt)*)),* $(,)?;
($($params:tt)*)
=>
$($code:tt)*
) => { ... };
}
Available on crate feature
non_basic
only.Expand description
Helper macro for defining and using a macro_rules!
macro inline.
The reason this was defined is to work around a limitation in stable const-eval, where you can’t call methods on generic types.
Example
Implementing panic formatting for a generic struct with flatten_panicvals
.
use const_panic::{
fmt::{self, ComputePvCount, FmtArg},
ArrayString, PanicFmt, PanicVal, flatten_panicvals, inline_macro,
};
// Debug formatting
assert_eq!(
ArrayString::<99>::from_panicvals(
&Foo(10, 20).to_panicvals(FmtArg::DEBUG)
).unwrap(),
"Foo(10, 20)"
);
// Alternate-Debug formatting
assert_eq!(
ArrayString::<99>::from_panicvals(
&Foo(false, true).to_panicvals(FmtArg::ALT_DEBUG)
).unwrap(),
concat!(
"Foo(\n",
" false,\n",
" true,\n",
")",
),
);
// Display formatting
assert_eq!(
ArrayString::<99>::from_panicvals(
&Foo("hmm", "what?").to_panicvals(FmtArg::DISPLAY)
).unwrap(),
"Foo(hmm, what?)"
);
struct Foo<T>(T, T);
impl<T> PanicFmt for Foo<T>
where
T: PanicFmt,
{
type This = Self;
type Kind = const_panic::IsCustomType;
const PV_COUNT: usize = ComputePvCount{
field_amount: 2,
summed_pv_count: T::PV_COUNT * 2,
delimiter: fmt::TypeDelim::Tupled,
}.call();
}
// Because of limitations of stable const evaluation,
// this macro only implements panic formatting for
// - `Foo<bool>`
// - `Foo<u8>`
// - `Foo<&str>`
inline_macro!{
(bool), (u8), (&str);
($T:ty)=>
impl Foo<$T> {
const fn to_panicvals(&self, fmtarg: FmtArg) -> [PanicVal<'_>; Foo::<$T>::PV_COUNT] {
flatten_panicvals! {fmtarg;
"Foo",
open: fmt::OpenParen,
$T => self.0, fmt::COMMA_SEP,
$T => self.1, fmt::COMMA_TERM,
close: fmt::CloseParen,
}
}
}
}