]>
Commit | Line | Data |
---|---|---|
2c00a5a8 XL |
1 | # memoffset # |
2 | ||
3 | [![](http://meritbadge.herokuapp.com/memoffset)](https://crates.io/crates/memoffset) | |
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. | |
5869c6ff | 9 | * `offset_of_tuple!` for obtaining the offset of a member of a tuple. (Requires Rust 1.20+) |
2c00a5a8 XL |
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] | |
5869c6ff | 19 | memoffset = "0.6" |
2c00a5a8 XL |
20 | ``` |
21 | ||
f035d41b | 22 | These versions will compile fine with rustc versions greater or equal to 1.19. |
416331ca | 23 | |
2c00a5a8 XL |
24 | Add the following lines at the top of your `main.rs` or `lib.rs` files. |
25 | ||
f035d41b | 26 | ```rust,ignore |
2c00a5a8 XL |
27 | #[macro_use] |
28 | extern crate memoffset; | |
29 | ``` | |
30 | ||
31 | ## Examples ## | |
32 | ```rust | |
f035d41b XL |
33 | #[macro_use] |
34 | extern crate memoffset; | |
35 | ||
2c00a5a8 XL |
36 | #[repr(C, packed)] |
37 | struct Foo { | |
f035d41b XL |
38 | a: u32, |
39 | b: u32, | |
40 | c: [u8; 5], | |
41 | d: u32, | |
2c00a5a8 XL |
42 | } |
43 | ||
f035d41b XL |
44 | fn main() { |
45 | assert_eq!(offset_of!(Foo, b), 4); | |
46 | assert_eq!(offset_of!(Foo, d), 4+4+5); | |
2c00a5a8 | 47 | |
f035d41b XL |
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 | } | |
2c00a5a8 | 54 | ``` |
f035d41b XL |
55 | |
56 | ## Feature flags ## | |
57 | ||
58 | ### Usage in constants ### | |
59 | `memoffset` has **experimental** support for compile-time `offset_of!` on a nightly compiler. | |
60 | ||
61 | In order to use it, you must enable the `unstable_const` crate feature and several compiler features. | |
62 | ||
63 | Cargo.toml: | |
64 | ```toml | |
65 | [dependencies.memoffset] | |
5869c6ff | 66 | version = "0.6" |
f035d41b XL |
67 | features = ["unstable_const"] |
68 | ``` | |
69 | ||
70 | Your crate root: (`lib.rs`/`main.rs`) | |
71 | ```rust,ignore | |
5869c6ff | 72 | #![feature(ptr_offset_from, const_ptr_offset_from, const_maybe_uninit_as_ptr, const_raw_ptr_deref)] |
f035d41b XL |
73 | ``` |
74 | ||
5869c6ff | 75 | If you intend to use `offset_of!` inside a `const fn`, also add the `const_fn` compiler feature. |