2025-07-23
Rust是一门强类型的语言,并且有强大的类型检查机制。如果能在编译器就检查出类型和地址是否对齐?就能够有效的避免程序崩溃。
use std::marker::PhantomData;
trait IsCompatible<const ADDRESS: u32> {
const RESULT: ();
}
impl<T: Sized, const ADDRESS: u32> IsCompatible<ADDRESS> for T {
const RESULT: () = {
if core::mem::size_of::<T>() % 4 != 0 {
panic!("The size of type T is not multiple of 4 bytes");
}
if ADDRESS % 4 != 0 {
panic!("ADDRESS is not align with 4 bytes");
}
};
}
#[derive(Debug, Clone)]
struct AlignValue<T> {
addr: u32,
phantom: PhantomData<T>,
}
impl<T> AlignValue<T>
where
T: Sized + PartialEq,
{
pub fn new<const ADDRESS: u32>() -> Self {
let _ = <T as IsCompatible<ADDRESS>>::RESULT;
AlignValue::<T> {
addr: ADDRESS,
phantom: PhantomData,
}
}
}
fn main() {
let x = AlignValue::<u32>::new::<8>();
println!("x = {:?}", x.addr);
}
// 类型没对齐
fn main() {
let x = AlignValue::<u8>::new::<8>();
println!("x = {:?}", x.addr);
}
// 地址没对齐
fn main() {
let x = AlignValue::<u32>::new::<1>();
println!("x = {:?}", x.addr);
}