Skip to content

Commit 9d116f4

Browse files
committed
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 <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> Reviewed-by: Zhao Liu <[email protected]> Reviewed-by: Peter Maydell <[email protected]> Signed-off-by: Peter Maydell <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Paolo Bonzini <[email protected]>
1 parent 7bda68e commit 9d116f4

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

rust/qemu-api/src/assertions.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,3 +120,25 @@ macro_rules! assert_match {
120120
);
121121
};
122122
}
123+
124+
/// Assert at compile time that an expression is true. This is similar
125+
/// to `const { assert!(...); }` but it works outside functions, as well as
126+
/// on versions of Rust before 1.79.
127+
///
128+
/// # Examples
129+
///
130+
/// ```
131+
/// # use qemu_api::static_assert;
132+
/// static_assert!("abc".len() == 3);
133+
/// ```
134+
///
135+
/// ```compile_fail
136+
/// # use qemu_api::static_assert;
137+
/// static_assert!("abc".len() == 2); // does not compile
138+
/// ```
139+
#[macro_export]
140+
macro_rules! static_assert {
141+
($x:expr) => {
142+
const _: () = assert!($x);
143+
};
144+
}

0 commit comments

Comments
 (0)