2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rust の static assert

Posted at

最近(いつから?)の bindgen でこんなコードが出力されていた。

#[repr(C)]
struct Foo {
    bar: u8,
    hoge: u32,
    piyo: u8,
}

const _: () = {
    use std::mem::offset_of;
    ["Foo size"][size_of::<Foo> - 12];
    ["Foo::bar"][offset_of!(Foo, bar) - 0];
    ["Foo::hoge"][offset_of!(Foo, hoge) - 4];
    ["Foo::piyo"][offset_of!(Foo, piyo) - 8];
};

構造体サイズやメンバのオフセットが間違っていたらコンパイルエラーになる(というか rust-analyzer が教えてくれる)。["Foo size"][&str; 1]で、[size_of::<Foo> - 12]が 0 になるようにしてるのね。(長さ 1 の配列aa[0]にアクセスしてる)

UEFI スペックみながら構造体書いてたら、いつの間にかオフセットずれてて爆死なんてことが防げそう :blush:

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?