alignment_exporter/lib.rs
1//! This crate provides alignment info for a user-defined struct, though this crate has increased in scope over time to include other information, such as the type name of struct fields.
2//!
3//! ```
4//! use alignment_exporter::{Alignment, AlignmentExporter, export_alignment};
5//!
6//! // `export_alignment` already annotates #[repr(C)] to the struct, so adding that yourself is not required. However, it is always better to include it in your code for the sake of explicitness.
7//! #[export_alignment]
8//! struct Example {
9//! a: u8,
10//! b: u32,
11//! c: u16
12//! }
13//!
14//! fn main() {
15//! let alignment = Example::get_alignment();
16//! assert_eq!(alignment, vec![
17//! Alignment { size: 1, offset: 0, ty_name: "u8" },
18//! Alignment { size: 4, offset: 1, ty_name: "u32" },
19//! Alignment { size: 2, offset: 8, ty_name: "u16" },
20//! ]);
21//! }
22//! ```
23
24pub use alignment_exporter_derive::export_alignment;
25
26/// Contains alignment info of a field in a struct.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub struct Alignment {
29 /// Size of the type in bytes
30 pub size: usize,
31 /// Starting index of a field in a struct
32 pub offset: usize,
33 /// Name of type
34 pub ty_name: &'static str,
35}
36
37/// Any type that uses the procedural macro automatically has this trait implemented for it. Use [`AlignmentExporter::get_alignment`] to get the alignment information of a struct.
38pub trait AlignmentExporter {
39 /// Get the alignment of a struct.
40 fn get_alignment() -> &'static [Alignment];
41}