1# memoffset # 2 3[![](http://meritbadge.herokuapp.com/memoffset)](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 * `span_of!` for obtaining the range that a field, or fields, span. 11 12`memoffset` works under `no_std` environments. 13 14## Usage ## 15Add the following dependency to your `Cargo.toml`: 16 17```toml 18[dependencies] 19memoffset = "0.6" 20``` 21 22These versions will compile fine with rustc versions greater or equal to 1.19. 23 24Add the following lines at the top of your `main.rs` or `lib.rs` files. 25 26```rust,ignore 27#[macro_use] 28extern crate memoffset; 29``` 30 31## Examples ## 32```rust 33#[macro_use] 34extern crate memoffset; 35 36#[repr(C, packed)] 37struct Foo { 38 a: u32, 39 b: u32, 40 c: [u8; 5], 41 d: u32, 42} 43 44fn main() { 45 assert_eq!(offset_of!(Foo, b), 4); 46 assert_eq!(offset_of!(Foo, d), 4+4+5); 47 48 assert_eq!(span_of!(Foo, a), 0..4); 49 assert_eq!(span_of!(Foo, a .. c), 0..8); 50 assert_eq!(span_of!(Foo, a ..= c), 0..13); 51 assert_eq!(span_of!(Foo, ..= d), 0..17); 52 assert_eq!(span_of!(Foo, b ..), 4..17); 53} 54``` 55 56## Feature flags ## 57 58### Usage in constants ### 59`memoffset` has **experimental** support for compile-time `offset_of!` on a nightly compiler. 60 61In order to use it, you must enable the `unstable_const` crate feature and several compiler features. 62 63Cargo.toml: 64```toml 65[dependencies.memoffset] 66version = "0.6" 67features = ["unstable_const"] 68``` 69 70Your crate root: (`lib.rs`/`main.rs`) 71```rust,ignore 72#![feature(ptr_offset_from, const_ptr_offset_from, const_maybe_uninit_as_ptr, const_raw_ptr_deref)] 73``` 74 75If you intend to use `offset_of!` inside a `const fn`, also add the `const_fn` compiler feature. 76