README.md
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 * `span_of!` for obtaining the range that a field, or fields, span.
10
11`memoffset` works under `no_std` environments.
12
13## Usage ##
14Add the following dependency to your `Cargo.toml`:
15
16```toml
17[dependencies]
18memoffset = "0.5"
19```
20
21These versions will compile fine with rustc versions greater or equal to 1.19.
22
23Add the following lines at the top of your `main.rs` or `lib.rs` files.
24
25```rust,ignore
26#[macro_use]
27extern crate memoffset;
28```
29
30## Examples ##
31```rust
32#[macro_use]
33extern crate memoffset;
34
35#[repr(C, packed)]
36struct Foo {
37 a: u32,
38 b: u32,
39 c: [u8; 5],
40 d: u32,
41}
42
43fn main() {
44 assert_eq!(offset_of!(Foo, b), 4);
45 assert_eq!(offset_of!(Foo, d), 4+4+5);
46
47 assert_eq!(span_of!(Foo, a), 0..4);
48 assert_eq!(span_of!(Foo, a .. c), 0..8);
49 assert_eq!(span_of!(Foo, a ..= c), 0..13);
50 assert_eq!(span_of!(Foo, ..= d), 0..17);
51 assert_eq!(span_of!(Foo, b ..), 4..17);
52}
53```
54
55## Feature flags ##
56
57### Usage in constants ###
58`memoffset` has **experimental** support for compile-time `offset_of!` on a nightly compiler.
59
60In order to use it, you must enable the `unstable_const` crate feature and several compiler features.
61
62Cargo.toml:
63```toml
64[dependencies.memoffset]
65version = "0.5"
66features = ["unstable_const"]
67```
68
69Your crate root: (`lib.rs`/`main.rs`)
70```rust,ignore
71#![feature(ptr_offset_from, const_ptr_offset_from, const_transmute, const_raw_ptr_deref)]
72```
73
74and then:
75
76```rust,ignore
77struct Foo {
78 a: u32,
79 b: u32,
80}
81
82let foo = [0; offset_of!(Foo, b)]
83```
84
85### Raw references ###
86Recent nightlies support [a way to create raw pointers](https://github.com/rust-lang/rust/issues/73394) that avoids creating intermediate safe references.
87`memoffset` can make use of that feature to avoid what is technically Undefined Behavior.
88Use the `unstable_raw` feature to enable this.
89