| Victor Hsieh | f32bc36 | 2020-12-15 13:56:41 -0800 | [diff] [blame] | 1 | # memoffset # |
| 2 | |
| David LeGare | 7d73837 | 2022-03-02 16:21:27 +0000 | [diff] [blame] | 3 | [](https://crates.io/crates/memoffset) |
| Victor Hsieh | f32bc36 | 2020-12-15 13:56:41 -0800 | [diff] [blame] | 4 | |
| 5 | C-Like `offset_of` functionality for Rust structs. |
| 6 | |
| 7 | Introduces 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 ## |
| 15 | Add the following dependency to your `Cargo.toml`: |
| 16 | |
| 17 | ```toml |
| 18 | [dependencies] |
| 19 | memoffset = "0.6" |
| 20 | ``` |
| 21 | |
| 22 | These versions will compile fine with rustc versions greater or equal to 1.19. |
| 23 | |
| Victor Hsieh | f32bc36 | 2020-12-15 13:56:41 -0800 | [diff] [blame] | 24 | ## Examples ## |
| 25 | ```rust |
| David LeGare | 7d73837 | 2022-03-02 16:21:27 +0000 | [diff] [blame] | 26 | use memoffset::{offset_of, span_of}; |
| Victor Hsieh | f32bc36 | 2020-12-15 13:56:41 -0800 | [diff] [blame] | 27 | |
| 28 | #[repr(C, packed)] |
| 29 | struct Foo { |
| 30 | a: u32, |
| 31 | b: u32, |
| 32 | c: [u8; 5], |
| 33 | d: u32, |
| 34 | } |
| 35 | |
| 36 | fn main() { |
| 37 | assert_eq!(offset_of!(Foo, b), 4); |
| 38 | assert_eq!(offset_of!(Foo, d), 4+4+5); |
| 39 | |
| 40 | assert_eq!(span_of!(Foo, a), 0..4); |
| 41 | assert_eq!(span_of!(Foo, a .. c), 0..8); |
| 42 | assert_eq!(span_of!(Foo, a ..= c), 0..13); |
| 43 | assert_eq!(span_of!(Foo, ..= d), 0..17); |
| 44 | assert_eq!(span_of!(Foo, b ..), 4..17); |
| 45 | } |
| 46 | ``` |
| 47 | |
| 48 | ## Feature flags ## |
| 49 | |
| 50 | ### Usage in constants ### |
| 51 | `memoffset` has **experimental** support for compile-time `offset_of!` on a nightly compiler. |
| 52 | |
| 53 | In order to use it, you must enable the `unstable_const` crate feature and several compiler features. |
| 54 | |
| 55 | Cargo.toml: |
| 56 | ```toml |
| 57 | [dependencies.memoffset] |
| 58 | version = "0.6" |
| 59 | features = ["unstable_const"] |
| 60 | ``` |
| 61 | |
| 62 | Your crate root: (`lib.rs`/`main.rs`) |
| 63 | ```rust,ignore |
| David LeGare | 7d73837 | 2022-03-02 16:21:27 +0000 | [diff] [blame] | 64 | #![feature(const_ptr_offset_from, const_refs_to_cell)] |
| Victor Hsieh | f32bc36 | 2020-12-15 13:56:41 -0800 | [diff] [blame] | 65 | ``` |