Skip to main content

header/
header.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Print field placement and compare pointer layouts across targets.
6
7use binlayout::{Layout, LayoutError, StructLayout, TargetLayout, Type};
8
9fn main() -> Result<(), LayoutError> {
10    let header = StructLayout::builder()
11        .field("tag", Layout::new(1, 1)?)
12        .field("length", Layout::new(4, 4)?)
13        .field("flags", Layout::new(2, 2)?)
14        .build()?;
15
16    println!("Header: size={}, align={}", header.size(), header.align());
17    for field in header.fields() {
18        println!(
19            "  {:<8} offset={}, size={}, align={}, padding_before={}",
20            field.name(),
21            field.offset(),
22            field.layout().size(),
23            field.align(),
24            field.padding_before(),
25        );
26    }
27    println!("  tail padding={}", header.tail_padding());
28
29    for (name, target) in [
30        ("wasm32", TargetLayout::wasm32()),
31        ("x86_64", TargetLayout::x86_64()),
32    ] {
33        let pointer_record = target.struct_layout([("tag", Type::U8), ("data", Type::Pointer)])?;
34        println!(
35            "{name}: Foo size={}, align={}, data offset={}",
36            pointer_record.size(),
37            pointer_record.align(),
38            pointer_record.offset("data").expect("data field exists"),
39        );
40    }
41    Ok(())
42}