README.md
1# memoffset #
2
3[](https://crates.io/crates/memoffset)
4
5C-Like `offset_of` functionality for Rust structs.
6
7Introduces the following macros:
8 * `offset_of!` for obtaining the offset of a member of a struct.
9 * `offset_of_tuple!` for obtaining the offset of a member of a tuple. (Requires Rust 1.20+)
10 * `offset_of_union!` for obtaining the offset of a member of a union.
11 * `span_of!` for obtaining the range that a field, or fields, span.
12
13`memoffset` works under `no_std` environments.
14
15If you're using a rustc version greater or equal to 1.77, this crate's `offset_of!()` macro simply forwards to `core::mem::offset_of!()`.
16
17## Usage ##
18Add the following dependency to your `Cargo.toml`:
19
20```toml
21[dependencies]
22memoffset = "0.9"
23```
24
25These versions will compile fine with rustc versions greater or equal to 1.19.
26
27## Examples ##
28```rust
29use memoffset::{offset_of, span_of};
30
31#[repr(C, packed)]
32struct Foo {
33 a: u32,
34 b: u32,
35 c: [u8; 5],
36 d: u32,
37}
38
39fn main() {
40 assert_eq!(offset_of!(Foo, b), 4);
41 assert_eq!(offset_of!(Foo, d), 4+4+5);
42
43 assert_eq!(span_of!(Foo, a), 0..4);
44 assert_eq!(span_of!(Foo, a .. c), 0..8);
45 assert_eq!(span_of!(Foo, a ..= c), 0..13);
46 assert_eq!(span_of!(Foo, ..= d), 0..17);
47 assert_eq!(span_of!(Foo, b ..), 4..17);
48}
49```
50
51## Usage in constants ##
52`memoffset` has support for compile-time `offset_of!` on rust>=1.65.
53
54On versions below 1.77, this is an incomplete implementation with one caveat:
55Due to dependence on [`#![feature(const_refs_to_cell)]`](https://github.com/rust-lang/rust/issues/80384), you cannot get the offset of a `Cell` field in a const-context.
56