2 releases

0.1.1 Jan 4, 2022
0.1.0 Feb 11, 2021

#1954 in Data structures

Download history 6/week @ 2024-01-29 66/week @ 2024-02-05 65/week @ 2024-02-12 88/week @ 2024-02-19 90/week @ 2024-02-26 47/week @ 2024-03-04 47/week @ 2024-03-11 30/week @ 2024-03-18

216 downloads per month

MIT/Apache

130KB
2.5K SLoC

repc

crates.io docs.rs

This crate contains APIs to calculate the layout of C data structures.

Example

See http://docs.rs/repc.

Supported Targets

This crate supports all targets that are also supported by Rust.

Tests

This crate is tested by comparing its output to the output of the target's C compiler. See ../tests for more details.

License

This crate is licensed under either of

  • Apache License, Version 2.0
  • MIT License

at your option.


lib.rs:

This crate contains APIs that allow you to calculate the layout of C types.

Example

Consider the C type

struct __attribute__((packed)) X {
    char c;
    int i:2 __attribute__((aligned(16)));
};

You can compute the layout of this type as follows:

let ty = Type::<()> {
    layout: (),
    annotations: vec![Annotation::AttrPacked],
    variant: TypeVariant::Record(Record {
        kind: RecordKind::Struct,
        fields: vec![
            RecordField {
                layout: None,
                annotations: vec![],
                named: true,
                bit_width: None,
                ty: Type {
                    layout: (),
                    annotations: vec![],
                    variant: TypeVariant::Builtin(BuiltinType::Char),
                },
            },
            RecordField {
                layout: None,
                annotations: vec![Annotation::Align(Some(128))],
                named: true,
                bit_width: Some(2),
                ty: Type {
                    layout: (),
                    annotations: vec![],
                    variant: TypeVariant::Builtin(BuiltinType::Int),
                },
            },
        ]
    }),
};
let layout = compute_layout(Target::X86_64UnknownLinuxGnu, &ty).unwrap();
assert_eq!(layout.layout, TypeLayout {
    size_bits: 256,
    field_alignment_bits: 128,
    pointer_alignment_bits: 128,
    required_alignment_bits: 8,
});
let fields = match &layout.variant {
    TypeVariant::Record(r) => &r.fields,
    _ => unreachable!(),
};
assert_eq!(fields[0].layout.unwrap(), FieldLayout {
    offset_bits: 0,
    size_bits: 8,
});
assert_eq!(fields[1].layout.unwrap(), FieldLayout {
    offset_bits: 128,
    size_bits: 2,
});
println!("{:#?}", layout);

Types describing the structure and layout of C types.

Maybe of these types take a Layout type parameter. The two predominant implementations of Layout are TypeLayout and (). Type<TypeLayout> can be converted to Type<()> by calling Type::<TypeLayout>::into(). Types and functions allowing you to traverse a Type.

Dependencies