repr_offset allows computing and safely using field offsets from types
with a defined layout.
Currently only #[repr(C)]/#[repr(C,packed)]/#[repr(C,align)] structs are supported.
Features
These are some of the features this library provides:
-
The
ReprOffsetderive macro, which outputs associated constants with the offsets of fields, and implements theGetFieldOffsettrait for each field. -
The
FieldOffsettype (how offsets are represented), with methods for operating on a field through a pointer to the struct, including getting a reference(or pointer) to the field. -
The
unsafe_struct_field_offsetsmacro as an alternative to theReprOffsetderive macro, most useful when the "derive" feature is disabled. -
The
GetFieldOffsettrait, for getting theFieldOffsetfor a field, and theOFF!,off,PUB_OFF!, andpub_offmacros for getting theFieldOffsetfor a field with a convenient syntax. -
The extension traits from the
extmodule, which define methods for operating on a field, given aFieldOffset.
Examples
Derivation
This example demonstrates:
-
Deriving the field offset constants and
GetFieldOffsettrait with theReprOffsetderive macro. -
Moving out unaligned fields through a raw pointer.
use ;
use ManuallyDrop;
let mut this = new;
let ptr: *mut Packed = &mut *this;
unsafe
Initialization
This example demonstrates how you can:
-
Use the
unsafe_struct_field_offsetsmacro to declare associated constants with the field offsets, and implement theGetFieldOffsettrait. -
Initialize an uninitialized struct with a functino that takes a raw pointer.
use MaybeUninit;
use ;
/// Initializes a `Foo` through a raw pointer.
///
/// # Safety
///
/// Callers must pass a pointer to uninitialized memory with the
/// size and alignment of `Foo`
unsafe
// This macro is unsafe to invoke because you have to ensure that:
// - All field types are listed,in declaration order.
// - The `alignment` parameter is `Unaligned` if the struct is `#[repr(C,packed)]`,
// and `Aligned` if it's not.
unsafe_struct_field_offsets!
Dependencies
This library re-exports the ReprOffset derive macro from the
repr_offset_derive crate when the "derive" feature is enabled,
this is disabled by default.
It also reexports the tstr crate unconditionally, to use its TS macro
as the type parameter of the GetFieldOffset trait.
Cargo features
These are the cargo features in repr_offset:
-
derive(disabled by default): Re-exports theReprOffsetderive macro from therepr_offset_derivecrate. -
"for_examples"(disabled by default): Enables thefor_examplesmodule, with types used in documentation examples.
Example of using the "derive" feature::
= { = "0.2", = ["derive"] }
no-std support
This library is unconditionally #![no_std], and that is unlikely to change in the future.
Minimum Rust version
This crate support Rust back to 1.41.0.