From 9d116f42a38cb95a33da837e0b0b50d91e28906b Mon Sep 17 00:00:00 2001 From: Paolo Bonzini Date: Fri, 21 Mar 2025 11:25:21 +0000 Subject: [PATCH] rust: assertions: add static_assert Add a new assertion that is similar to "const { assert!(...) }" but can be used outside functions and with older versions of Rust. A similar macro is found in Linux, whereas the "static_assertions" crate has a const_assert macro that produces worse error messages. Suggested-by: Peter Maydell Signed-off-by: Paolo Bonzini Reviewed-by: Zhao Liu Reviewed-by: Peter Maydell Signed-off-by: Peter Maydell Link: https://lore.kernel.org/r/20250321112523.1774131-2-peter.maydell@linaro.org Signed-off-by: Paolo Bonzini --- rust/qemu-api/src/assertions.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/rust/qemu-api/src/assertions.rs b/rust/qemu-api/src/assertions.rs index 104dec3977..bba38cfda1 100644 --- a/rust/qemu-api/src/assertions.rs +++ b/rust/qemu-api/src/assertions.rs @@ -120,3 +120,25 @@ macro_rules! assert_match { ); }; } + +/// Assert at compile time that an expression is true. This is similar +/// to `const { assert!(...); }` but it works outside functions, as well as +/// on versions of Rust before 1.79. +/// +/// # Examples +/// +/// ``` +/// # use qemu_api::static_assert; +/// static_assert!("abc".len() == 3); +/// ``` +/// +/// ```compile_fail +/// # use qemu_api::static_assert; +/// static_assert!("abc".len() == 2); // does not compile +/// ``` +#[macro_export] +macro_rules! static_assert { + ($x:expr) => { + const _: () = assert!($x); + }; +} -- 2.39.5