Skip to content

Set a custom message for failing assertionsΒ #49

@NoraCodes

Description

@NoraCodes

I'm not sure if this is possible on the MSRV of 1.37, but on 1.57 we can do something like this:

macro_rules! const_assert {
    ($x:expr $(,)?) => {
        const_assert!($x, "const assertion failed",);
    };
    ($x:expr, $es:expr $(,)?) => {
        const _: () = {
            const fn assert_internal () {
                if !$x {
                    core::panic!($es);
                }
            }
            const _: () = assert_internal();
        };
    };
}

And you can call that like so:

const_assert!(BUFFER_LEN < 1024, "BUFFER_LEN > 1024 will overrun PROGMEM");

And get a message like this:

error[E0080]: evaluation of constant value failed
 --> src/const_assert.rs:55:1
  |
5 | const_assert!(BUFFER_LEN < 1024, "BUFFER_LEN > 1024 will overrun PROGMEM");
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  | |
  | the evaluated program panicked at 'BUFFER_LEN > 1024 will overrun PROGMEM', src/const_assert.rs:5:1
  | inside `assert_internal` at /rustc/8f36334ca939a67cce3f37f24953ff6f2d3f3d33/library/core/src/panic.rs:28:9
  | inside `_::_` at /home/nora/src/noracodes/static-assertions-rs/src/const_assert.rs:71:27
  |
  = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info)

Obviously this won't work for any other macros here, because of their variadics, but it would be lovely if we could get custom messages at least for const_assert. Perhaps it could be opt-in through a Cargo feature?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions