1 //! Convenience macros.
5 sync::atomic::{AtomicUsize, Ordering::SeqCst},
8 macro_rules! eprintln {
11 panic!("Forgot to remove debug-print?")
13 std::eprintln!($($tt)*)
17 /// Appends formatted string to a `String`.
19 macro_rules! format_to {
21 ($buf:expr, $lit:literal $($arg:tt)*) => {
22 { use ::std::fmt::Write as _; let _ = ::std::write!($buf, $lit $($arg)*); }
26 /// Generates `From` impls for `Enum E { Foo(Foo), Bar(Bar) }` enums
31 /// impl_from!(Struct, Union, Enum for Adt);
34 macro_rules! impl_from {
35 ($($variant:ident $(($($sub_variant:ident),*))?),* for $enum:ident) => {
37 impl From<$variant> for $enum {
38 fn from(it: $variant) -> $enum {
43 impl From<$sub_variant> for $enum {
44 fn from(it: $sub_variant) -> $enum {
45 $enum::$variant($variant::$sub_variant(it))
53 /// A version of `assert!` macro which allows to handle an assertion failure.
55 /// In release mode, it returns the condition and logs an error.
58 /// if assert_never!(impossible) {
59 /// // Heh, this shouldn't have happened, but lets try to soldier on...
64 /// Rust analyzer is a long-running process, and crashing really isn't an option.
66 /// Shamelessly stolen from: https://www.sqlite.org/assert.html
68 macro_rules! assert_never {
69 ($cond:expr) => { $crate::assert_never!($cond, "") };
70 ($cond:expr, $($fmt:tt)*) => {{
73 $crate::on_assert_failure(
74 format_args!($($fmt)*)
81 type AssertHook = fn(&panic::Location<'_>, fmt::Arguments<'_>);
82 static HOOK: AtomicUsize = AtomicUsize::new(0);
84 pub fn set_assert_hook(hook: AssertHook) {
85 HOOK.store(hook as usize, SeqCst);
90 pub fn on_assert_failure(args: fmt::Arguments) {
91 let hook: usize = HOOK.load(SeqCst);
93 panic!("\n assertion failed: {}\n", args);
96 let hook: AssertHook = unsafe { mem::transmute::<usize, AssertHook>(hook) };
97 hook(panic::Location::caller(), args)