]> git.proxmox.com Git - rustc.git/blame - vendor/memoffset/README.md
New upstream version 1.67.1+dfsg1
[rustc.git] / vendor / memoffset / README.md
CommitLineData
2c00a5a8
XL
1# memoffset #
2
a2a8927a 3[![](https://img.shields.io/crates/v/memoffset.svg)](https://crates.io/crates/memoffset)
2c00a5a8
XL
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.
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 ##
15Add the following dependency to your `Cargo.toml`:
16
17```toml
18[dependencies]
487cf647 19memoffset = "0.7"
2c00a5a8
XL
20```
21
f035d41b 22These versions will compile fine with rustc versions greater or equal to 1.19.
416331ca 23
2c00a5a8
XL
24## Examples ##
25```rust
a2a8927a 26use memoffset::{offset_of, span_of};
f035d41b 27
2c00a5a8
XL
28#[repr(C, packed)]
29struct Foo {
f035d41b
XL
30 a: u32,
31 b: u32,
32 c: [u8; 5],
33 d: u32,
2c00a5a8
XL
34}
35
f035d41b
XL
36fn main() {
37 assert_eq!(offset_of!(Foo, b), 4);
38 assert_eq!(offset_of!(Foo, d), 4+4+5);
2c00a5a8 39
f035d41b
XL
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}
2c00a5a8 46```
f035d41b
XL
47
48## Feature flags ##
49
50### Usage in constants ###
51`memoffset` has **experimental** support for compile-time `offset_of!` on a nightly compiler.
52
53In order to use it, you must enable the `unstable_const` crate feature and several compiler features.
54
55Cargo.toml:
56```toml
57[dependencies.memoffset]
487cf647 58version = "0.7"
f035d41b
XL
59features = ["unstable_const"]
60```
61
62Your crate root: (`lib.rs`/`main.rs`)
63```rust,ignore
a2a8927a 64#![feature(const_ptr_offset_from, const_refs_to_cell)]
f035d41b 65```