Message ID | 20250320133248.1679485-2-peter.maydell@linaro.org |
---|---|
State | Superseded |
Headers | show |
Series | rust: Fix PL011State size mismatch assert | expand |
On 20/3/25 14:32, Peter Maydell wrote: > From: Paolo Bonzini <pbonzini@redhat.com> > > 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 <peter.maydell@linaro.org> > Supersedes: <20250320113356.799412-1-pbonzini@redhat.com> ^ extraneous tag > Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> > Signed-off-by: Peter Maydell <peter.maydell@linaro.org> > --- > rust/qemu-api/src/assertions.rs | 22 ++++++++++++++++++++++ > 1 file changed, 22 insertions(+)
On Thu, Mar 20, 2025 at 01:32:46PM +0000, Peter Maydell wrote: > Date: Thu, 20 Mar 2025 13:32:46 +0000 > From: Peter Maydell <peter.maydell@linaro.org> > Subject: [PATCH 1/3] rust: assertions: add static_assert > X-Mailer: git-send-email 2.43.0 > > From: Paolo Bonzini <pbonzini@redhat.com> > > 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 <peter.maydell@linaro.org> > Supersedes: <20250320113356.799412-1-pbonzini@redhat.com> > Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> > Signed-off-by: Peter Maydell <peter.maydell@linaro.org> > --- > rust/qemu-api/src/assertions.rs | 22 ++++++++++++++++++++++ > 1 file changed, 22 insertions(+) Reviewed-by: Zhao Liu <zhao1.liu@intel.com>
diff --git a/rust/qemu-api/src/assertions.rs b/rust/qemu-api/src/assertions.rs index 104dec39774..bba38cfda11 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); + }; +}