Heng30的博客
搜索 分类 关于 订阅

如何在编译器检查Rust类型和参数对齐?

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);
}