#layout #struct #type #struct-fields #field-name

type-layout

Derivable trait to view the layout of a struct, useful for debugging

2 unstable releases

0.2.0 Sep 19, 2020
0.1.0 Sep 13, 2020

#2343 in Rust patterns

Download history 5781/week @ 2024-07-20 4297/week @ 2024-07-27 3978/week @ 2024-08-03 4353/week @ 2024-08-10 4295/week @ 2024-08-17 3597/week @ 2024-08-24 3934/week @ 2024-08-31 3861/week @ 2024-09-07 2699/week @ 2024-09-14 3956/week @ 2024-09-21 3308/week @ 2024-09-28 3207/week @ 2024-10-05 4126/week @ 2024-10-12 4860/week @ 2024-10-19 4105/week @ 2024-10-26 4375/week @ 2024-11-02

18,143 downloads per month
Used in 8 crates

MIT/Apache

11KB
132 lines

type-layout

GitHub CI Status type-layout on crates.io type-layout docs

type-layout is a type layout debugging aid, providing a #[derive]able trait that reports:

  • The type's name, size, and minimum alignment
  • Each field's name, type, offset, and size
  • Padding due to alignment requirements

type-layout currently only functions on structs with named fields. This is a temporary limitation.

Examples

The layout of types is only defined if they're #[repr(C)]. This crate works on non-#[repr(C)] types, but their layout is unpredictable.

use type_layout::TypeLayout;

#[derive(TypeLayout)]
#[repr(C)]
struct Foo {
    a: u8,
    b: u32,
}

println!("{}", Foo::type_layout());
// prints:
// Foo (size 8, alignment 4)
// | Offset | Name      | Size |
// | ------ | --------- | ---- |
// | 0      | a         | 1    |
// | 1      | [padding] | 3    |
// | 4      | b         | 4    |

Over-aligned types have trailing padding, which can be a source of bugs in some FFI scenarios:

use type_layout::TypeLayout;

#[derive(TypeLayout)]
#[repr(C, align(128))]
struct OverAligned {
    value: u8,
}

println!("{}", OverAligned::type_layout());
// prints:
// OverAligned (size 128, alignment 128)
// | Offset | Name      | Size |
// | ------ | --------- | ---- |
// | 0      | value     | 1    |
// | 1      | [padding] | 127  |

Minimum Supported Rust Version (MSRV)

type-layout supports Rust 1.34.1 and newer. Until type-layout reaches 1.0, changes to the MSRV will require major version bumps. After 1.0, MSRV changes will only require minor version bumps, but will need significant justification.

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~1.5MB
~39K SLoC