Skip to content

Commit 38c0160

Browse files
committed
Add assert_eq_align! macro
1 parent f6623e9 commit 38c0160

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/assert_eq_align.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/// Asserts that types are equal in alignment.
2+
///
3+
/// This is useful when ensuring that pointer arithmetic is done correctly, or
4+
/// when [FFI] requires a type to have the same alignment as some foreign type.
5+
///
6+
/// # Examples
7+
///
8+
/// A `usize` has the same alignment as any pointer type:
9+
///
10+
/// ```
11+
/// # #[macro_use] extern crate static_assertions; fn main() {}
12+
/// assert_eq_align!(usize, *const u8, *mut u8);
13+
/// ```
14+
///
15+
/// The following passes because `[i32; 4]` has the same alignment as `i32`:
16+
///
17+
/// ```
18+
/// # #[macro_use] extern crate static_assertions; fn main() {}
19+
/// assert_eq_align!([i32; 4], i32);
20+
/// ```
21+
///
22+
/// The following example fails to compile because `i32x4` explicitly has 4
23+
/// times the alignment as `[i32; 4]`:
24+
///
25+
/// ```compile_fail
26+
/// # #[macro_use] extern crate static_assertions; fn main() {}
27+
/// # #[allow(non_camel_case_types)]
28+
/// #[repr(align(16))]
29+
/// struct i32x4([i32; 4]);
30+
///
31+
/// assert_eq_align!(i32x4, [i32; 4]);
32+
/// ```
33+
///
34+
/// [FFI]: https://en.wikipedia.org/wiki/Foreign_function_interface
35+
#[macro_export]
36+
macro_rules! assert_eq_align {
37+
($x:ty, $($xs:ty),+ $(,)?) => {
38+
const _: fn() = || {
39+
// Assigned instance must match the annotated type or else it will
40+
// fail to compile
41+
use $crate::_core::mem::align_of;
42+
$(let _: [(); align_of::<$x>()] = [(); align_of::<$xs>()];)+
43+
};
44+
};
45+
}

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@
6666
pub extern crate core as _core;
6767

6868
mod assert_cfg;
69+
mod assert_eq_align;
6970
mod assert_eq_size;
7071
mod assert_fields;
7172
mod assert_impl;

0 commit comments

Comments
 (0)