Skip to contentSkip to conversation

rust: assertions: add const_assert

PATCH Superseded Paolo Bonzini 1 participant 1 message Mar 20, 2025 Rust

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 rust: assertions: add const_assert

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.

---
 rust/qemu-api/src/assertions.rs | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)
rust/qemu-api/src/assertions.rs +22 -0
index 104dec39774..1fa3955d867 100644
@@ -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 }] = [()];
+    };
+}
Signature · 1 line
2.48.1