* [PATCH] rust: assertions: add const_assert
@ 2025-03-20 11:33 Paolo Bonzini
0 siblings, 0 replies; only message in thread
From: Paolo Bonzini @ 2025-03-20 11:33 UTC (permalink / raw)
To: qemu-devel; +Cc: Peter Maydell
Add a new assertion that is similar to "const { assert!(...) }" but can be used
outside functions and with older versions of Rust. Similar in concept (but
not in code) to the homonymous macro of the "static_assertions" crate.
Suggested-by: Peter Maydell <peter.maydell@linaro.org>
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
---
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 104dec39774..1fa3955d867 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::const_assert;
+/// const_assert!("abc".len() == 3);
+/// ```
+///
+/// ```compile_fail
+/// # use qemu_api::const_assert;
+/// const_assert!("abc".len() == 2); // does not compile
+/// ```
+#[macro_export]
+macro_rules! const_assert {
+ ($x:expr) => {
+ const _: [(); { const VALUE__: bool = $x; VALUE__ as usize }] = [()];
+ };
+}
--
2.48.1
^ permalink raw reply related [flat|nested] only message in thread
only message in thread, other threads:[~2025-03-20 11:35 UTC | newest]
Thread overview: (only message) (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-03-20 11:33 [PATCH] rust: assertions: add const_assert Paolo Bonzini
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).