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 15## Usage ## 16Add the following dependency to your `Cargo.toml`: 17 18```toml 19[dependencies] 20memoffset = "0.8" 21``` 22 23These versions will compile fine with rustc versions greater or equal to 1.19. 24 25## Examples ## 26```rust 27use memoffset::{offset_of, span_of}; 28 29#[repr(C, packed)] 30struct Foo { 31 a: u32, 32 b: u32, 33 c: [u8; 5], 34 d: u32, 35} 36 37fn main() { 38 assert_eq!(offset_of!(Foo, b), 4); 39 assert_eq!(offset_of!(Foo, d), 4+4+5); 40 41 assert_eq!(span_of!(Foo, a), 0..4); 42 assert_eq!(span_of!(Foo, a .. c), 0..8); 43 assert_eq!(span_of!(Foo, a ..= c), 0..13); 44 assert_eq!(span_of!(Foo, ..= d), 0..17); 45 assert_eq!(span_of!(Foo, b ..), 4..17); 46} 47``` 48 49## Usage in constants ## 50`memoffset` has support for compile-time `offset_of!` on rust>=1.65, or on older nightly compilers. 51 52### Usage on stable Rust ### 53Constant evaluation is automatically enabled and avilable on stable compilers starting with rustc 1.65. 54 55This is an incomplete implementation with one caveat: 56Due 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. 57 58This means that if need to get the offset of a cell, you'll have to remain on nightly for now. 59 60### Usage on recent nightlies ### 61 62If you're using a new-enough nightly and you require the ability to get the offset of a `Cell`, 63you'll have to enable the `unstable_const` cargo feature, as well as enabling `const_refs_to_cell` in your crate root. 64 65Do note that `unstable_const` is an unstable feature that is set to be removed in a future version of `memoffset`. 66 67Cargo.toml: 68```toml 69[dependencies.memoffset] 70version = "0.8" 71features = ["unstable_const"] 72``` 73 74Your crate root: (`lib.rs`/`main.rs`) 75```rust,ignore 76#![feature(const_refs_to_cell)] 77``` 78 79### Usage on older nightlies ### 80In order to use it on an older nightly compiler, you must enable the `unstable_const` crate feature and several compiler features. 81 82Your crate root: (`lib.rs`/`main.rs`) 83```rust,ignore 84#![feature(const_ptr_offset_from, const_refs_to_cell)] 85``` 86