Expand description
§pstruct
A Rust procedural macro for generating pointer struct implementations with field offset access. The purpose of this crate is to minimize stack space, preventing struct copies1, while still allowing ergonomic field access. This macro abstracts away a lot of the pain of interacting with pointers to structs, such as casting, pointer arithmetic, transmutation, etc.
A big inspiration for need for this crate was minimizing stack space for functions which use WinAPI structs, as they are often massive in size.
§Features
- Generate pointer structs with field offset access methods
- Support for arrays of pointers with indexing
- Pointer reinterpretation capabilities
- Safe and ergonomic field access
§Attributes
§offset
The main attribute for specifying field offsets and behavior:
- Basic usage:
#[offset(0x1)]
- Specifies the offset from base address - Reinterpret:
#[offset(0x1, reinterpret)]
- Reinterprets the pointer at the given offset as another pointer type. - Array:
#[offset(0x1, array(size))]
- Defines an array of pointers and generates a getter method for indexing into the array.
§Safety
This crate involves heavy unsafe operations when accessing fields. Consumers of this crate are responsible for:
- Ensuring correct memory layout, alignment, bounds, etc.
- Ensuring offsets are valid for the data structure and all memory is readable.
- Proper lifetime management when constructing a PStruct from a raw pointer. Lifetimes are enforced for you when creating a PStruct from a &[T].
- Bounds checking when accessing array fields.
§License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
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.
§Notes
1 You could always use references to prevent the copy, but this still doesn’t solve the problem of manually defining structs with padding bytes which gets very tedious and is very common for those working with WinAPI (PEB, TEB, etc).
Macros§
- p_
struct - Generates a pointer struct from a struct definition.