Skip to content

Commit

Permalink
Create const_assert_eq_usize! macro
Browse files Browse the repository at this point in the history
Emits better error messages when asserting `usize` equality.
  • Loading branch information
nvzqz committed Dec 29, 2019
1 parent dd8befe commit f0b707e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
6 changes: 2 additions & 4 deletions src/assert_align.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,12 @@
/// ```
///
/// [FFI]: https://en.wikipedia.org/wiki/Foreign_function_interface
#[macro_export]
#[macro_export(local_inner_macros)]
macro_rules! assert_align_eq {
($x:ty, $($xs:ty),+ $(,)?) => {
const _: fn() = || {
// Assigned instance must match the annotated type or else it will
// fail to compile
use $crate::_core::mem::align_of;
$(let _: [(); align_of::<$x>()] = [(); align_of::<$xs>()];)+
const_assert_eq_usize!(align_of::<$x>() $(, align_of::<$xs>())+);
};
};
}
Expand Down
20 changes: 19 additions & 1 deletion src/const_assert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,17 @@ macro_rules! const_assert {

/// Asserts that constants are equal in value.
///
/// Use [`const_assert_eq_usize!`](macro.const_assert_eq_usize.html) for better
/// error messages when asserting
/// [`usize`](https://doc.rust-lang.org/std/primitive.usize.html) equality.
///
/// # Examples
///
/// This works as a shorthand for `const_assert!(a == b)`:
///
/// ```
/// # #[macro_use] extern crate static_assertions; fn main() {}
/// const TWO: usize = 2;
/// const TWO: i32 = 2;
///
/// const_assert_eq!(TWO * TWO, TWO + TWO);
/// ```
Expand All @@ -81,6 +85,20 @@ macro_rules! const_assert_eq {
};
}

/// Asserts that constants of type
/// [`usize`](https://doc.rust-lang.org/std/primitive.usize.html) are equal in
/// value.
///
/// This is equivalent to [`const_assert_eq!`](macro.const_assert_eq.html) but
/// allows for inspecting the values in error messages.
#[macro_export]
macro_rules! const_assert_eq_usize {
($x:expr, $($y:expr),+ $(,)?) => {
// Assigned instance must match the annotated type or else it will fail.
$(const _: [(); $x] = [(); $y];)+
};
}

/// Asserts that constants are **not** equal in value.
///
/// # Examples
Expand Down

0 comments on commit f0b707e

Please sign in to comment.