[−][src]Macro const_format::assertc
Compile-time assertions with formatting.
This macro requires the "assert" feature to be exported,
because it uses some nightly Rust features.
It uses std::panic
for panicking due to an unforseen limitation
in core::panic
, which doesn't allow passing non-literal strings at compile-time.
Syntax
This macro uses the same syntax
for the format string and formatting arguments as the
formatc
macro.
Error message
const_format
uses some workarounds to avoid requiring users to enable the
#![feature(const_panic)]
feature themselves,
as a result, the error message isn't as good as it could possibly be.
Compile-time errors with this macro include the formatted error message, and the module path + line where this macro was invoked.
Limitations
This macro has these limitations:
-
It can only use constants that involve concrete types, so while a
Type::<u8>::FOO
in an argument would be fine,Type::<T>::FOO
would not be (T
being a type parameter). -
Integer arguments must have a type inferrable from context, as described in the integer arguments section in the root module .
Examples
Passing assertion
#![feature(const_mut_refs)] use const_format::assertc; use std::mem::size_of; assertc!( size_of::<&str>() == size_of::<&[u8]>(), "The size of `&str`({} bytes) and `&[u8]`({} bytes) aren't the same?!?!", size_of::<&str>(), size_of::<&[u8]>(), );
Failing assertion
This example demonstrates a failing assertion, and how the compiler error looks like as of 2020-09-XX.
#![feature(const_mut_refs)] use const_format::assertc; use std::mem::size_of; const L: u64 = 2; const R: u64 = 2; assertc!(L + R == 5, "{} plus {} isn't 5 buddy", L, R);
This is the compiler output, the first compilation error is there to have an indicator of what assertion failed, and the second is the assertion failure.
error: any use of this value will cause an error
--> src/macros/assertions.rs:59:1
|
13 | assertc!(L + R == 5, "{} plus {} isn't 5 buddy", L, R);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ exceeded interpreter step limit (see `#[const_eval_limit]`)
|
= note: `#[deny(const_err)]` on by default
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0080]: could not evaluate constant
--> /const_format/src/panicking.rs:32:5
|
32 | .
| ^ the evaluated program panicked at '
--------------------------------------------------------------------------------
module_path: rust_out
line: 13
assertion failed: L + R == 5
2 plus 2 isn't 5 buddy
--------------------------------------------------------------------------------
', const_format/src/panicking.rs:31:1
|
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)