1 // Copyright (c) 2017 Gilad Naaman
3 // Permission is hereby granted, free of charge, to any person obtaining a copy
4 // of this software and associated documentation files (the "Software"), to deal
5 // in the Software without restriction, including without limitation the rights
6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 // copies of the Software, and to permit persons to whom the Software is
8 // furnished to do so, subject to the following conditions:
10 // The above copyright notice and this permission notice shall be included in all
11 // copies or substantial portions of the Software.
13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 /// Macro to create a local `base_ptr` raw pointer of the given type, avoiding UB as
22 /// much as is possible currently.
26 macro_rules! _memoffset__let_base_ptr {
27 ($name:ident, $type:ty) => {
28 // No UB here, and the pointer does not dangle, either.
29 // But we have to make sure that `uninit` lives long enough,
30 // so it has to be in the same scope as `$name`. That's why
31 // `let_base_ptr` declares a variable (several, actually)
32 // instead of returning one.
33 let uninit = $crate::__priv::mem::MaybeUninit::<$type>::uninit();
34 let $name: *const $type = uninit.as_ptr();
37 #[cfg(not(maybe_uninit))]
40 macro_rules! _memoffset__let_base_ptr {
41 ($name:ident, $type:ty) => {
42 // No UB right here, but we will later dereference this pointer to
43 // offset into a field, and that is UB because the pointer is dangling.
44 let $name = $crate::__priv::mem::align_of::<$type>() as *const $type;
48 /// Macro to compute the distance between two pointers.
49 #[cfg(any(feature = "unstable_const", stable_const))]
52 macro_rules! _memoffset_offset_from_unsafe {
53 ($field:expr, $base:expr) => {{
54 let field = $field; // evaluate $field outside the `unsafe` block
55 let base = $base; // evaluate $base outside the `unsafe` block
56 // Compute offset, with unstable `offset_from` for const-compatibility.
57 // (Requires the pointers to not dangle, but we already need that for `raw_field!` anyway.)
58 unsafe { (field as *const u8).offset_from(base as *const u8) as usize }
61 #[cfg(not(any(feature = "unstable_const", stable_const)))]
64 macro_rules! _memoffset_offset_from_unsafe {
65 ($field:expr, $base:expr) => {
67 ($field as usize) - ($base as usize)
70 #[cfg(not(feature = "unstable_offset_of"))]
71 #[macro_export(local_inner_macros)]
73 macro_rules! _memoffset__offset_of_impl {
74 ($parent:path, $field:tt) => {{
75 // Get a base pointer (non-dangling if rustc supports `MaybeUninit`).
76 _memoffset__let_base_ptr!(base_ptr, $parent);
78 let field_ptr = raw_field!(base_ptr, $parent, $field);
80 _memoffset_offset_from_unsafe!(field_ptr, base_ptr)
83 #[cfg(feature = "unstable_offset_of")]
86 #[allow_internal_unstable(offset_of)]
87 macro_rules! _memoffset__offset_of_impl {
88 ($parent:path, $field:tt) => {{
89 $crate::__priv::mem::offset_of!($parent, $field)
93 /// Calculates the offset of the specified field from the start of the named struct.
97 /// use memoffset::offset_of;
99 /// #[repr(C, packed)]
107 /// assert_eq!(offset_of!(Foo, a), 0);
108 /// assert_eq!(offset_of!(Foo, b), 4);
113 /// Rust's ABI is unstable, and [type layout can be changed with each
114 /// compilation](https://doc.rust-lang.org/reference/type-layout.html).
116 /// Using `offset_of!` with a `repr(Rust)` struct will return the correct offset of the
117 /// specified `field` for a particular compilation, but the exact value may change
118 /// based on the compiler version, concrete struct type, time of day, or rustc's mood.
120 /// As a result, the value should not be retained and used between different compilations.
121 #[macro_export(local_inner_macros)]
122 macro_rules! offset_of {
123 ($parent:path, $field:tt) => {
124 _memoffset__offset_of_impl!($parent, $field)
128 /// Calculates the offset of the specified field from the start of the tuple.
132 /// use memoffset::offset_of_tuple;
135 /// assert!(offset_of_tuple!((u8, u32), 1) >= 0, "Tuples do not have a defined layout");
139 #[macro_export(local_inner_macros)]
140 macro_rules! offset_of_tuple {
141 ($parent:ty, $field:tt) => {{
142 // Get a base pointer (non-dangling if rustc supports `MaybeUninit`).
143 _memoffset__let_base_ptr!(base_ptr, $parent);
144 // Get field pointer.
145 let field_ptr = raw_field_tuple!(base_ptr, $parent, $field);
147 _memoffset_offset_from_unsafe!(field_ptr, base_ptr)
151 #[cfg(not(feature = "unstable_offset_of"))]
152 #[macro_export(local_inner_macros)]
154 macro_rules! _memoffset__offset_of_union_impl {
155 ($parent:path, $field:tt) => {{
156 // Get a base pointer (non-dangling if rustc supports `MaybeUninit`).
157 _memoffset__let_base_ptr!(base_ptr, $parent);
158 // Get field pointer.
159 let field_ptr = raw_field_union!(base_ptr, $parent, $field);
161 _memoffset_offset_from_unsafe!(field_ptr, base_ptr)
165 #[cfg(feature = "unstable_offset_of")]
166 #[macro_export(local_inner_macros)]
168 #[allow_internal_unstable(offset_of)]
169 macro_rules! _memoffset__offset_of_union_impl {
170 ($parent:path, $field:tt) => {{
171 $crate::__priv::mem::offset_of!($parent, $field)
175 /// Calculates the offset of the specified union member from the start of the union.
179 /// use memoffset::offset_of_union;
181 /// #[repr(C, packed)]
188 /// assert!(offset_of_union!(Foo, foo64) == 0);
193 /// Due to macro_rules limitations, this macro will accept structs with a single field as well as unions.
194 /// This is not a stable guarantee, and future versions of this crate might fail
195 /// on any use of this macro with a struct, without a semver bump.
196 #[macro_export(local_inner_macros)]
197 macro_rules! offset_of_union {
198 ($parent:path, $field:tt) => {{
199 _memoffset__offset_of_union_impl!($parent, $field)
214 assert_eq!(offset_of!(Foo, a), 0);
215 assert_eq!(offset_of!(Foo, b), 4);
216 assert_eq!(offset_of!(Foo, c), 8);
220 #[cfg_attr(miri, ignore)] // this creates unaligned references
221 fn offset_simple_packed() {
229 assert_eq!(offset_of!(Foo, a), 0);
230 assert_eq!(offset_of!(Foo, b), 4);
231 assert_eq!(offset_of!(Foo, c), 6);
237 struct Tup(i32, i32);
239 assert_eq!(offset_of!(Tup, 0), 0);
240 assert_eq!(offset_of!(Tup, 1), 4);
245 // Since we're specifying repr(C), all fields are supposed to be at offset 0
253 assert_eq!(offset_of_union!(Foo, a), 0);
254 assert_eq!(offset_of_union!(Foo, b), 0);
255 assert_eq!(offset_of_union!(Foo, c), 0);
267 assert_eq!(offset_of!(sub::Foo, x), 0);
271 fn inside_generic_method() {
272 struct Pair<T, U>(T, U);
274 fn foo<T, U>(_: Pair<T, U>) -> usize {
275 offset_of!(Pair<T, U>, 1)
278 assert_eq!(foo(Pair(0, 0)), 4);
283 fn test_tuple_offset() {
284 let f = (0i32, 0.0f32, 0u8);
285 let f_ptr = &f as *const _;
286 let f1_ptr = &f.1 as *const _;
289 f1_ptr as usize - f_ptr as usize,
290 offset_of_tuple!((i32, f32, u8), 1)
295 fn test_raw_field() {
308 let f_ptr = &f as *const _;
309 assert_eq!(f_ptr as usize + 0, raw_field!(f_ptr, Foo, a) as usize);
310 assert_eq!(f_ptr as usize + 4, raw_field!(f_ptr, Foo, b) as usize);
311 assert_eq!(f_ptr as usize + 8, raw_field!(f_ptr, Foo, c) as usize);
316 fn test_raw_field_tuple() {
317 let t = (0u32, 0u8, false);
318 let t_ptr = &t as *const _;
319 let t_addr = t_ptr as usize;
322 &t.0 as *const _ as usize - t_addr,
323 raw_field_tuple!(t_ptr, (u32, u8, bool), 0) as usize - t_addr
326 &t.1 as *const _ as usize - t_addr,
327 raw_field_tuple!(t_ptr, (u32, u8, bool), 1) as usize - t_addr
330 &t.2 as *const _ as usize - t_addr,
331 raw_field_tuple!(t_ptr, (u32, u8, bool), 2) as usize - t_addr
336 fn test_raw_field_union() {
344 let f = Foo { a: 0 };
345 let f_ptr = &f as *const _;
346 assert_eq!(f_ptr as usize + 0, raw_field_union!(f_ptr, Foo, a) as usize);
347 assert_eq!(f_ptr as usize + 0, raw_field_union!(f_ptr, Foo, b) as usize);
348 assert_eq!(f_ptr as usize + 0, raw_field_union!(f_ptr, Foo, c) as usize);
352 feature = "unstable_const",
353 feature = "unstable_offset_of",
365 assert_eq!([0; offset_of!(Foo, b)].len(), 4);
368 #[cfg(feature = "unstable_const")]
370 fn const_offset_interior_mutable() {
374 b: core::cell::Cell<u32>,
377 assert_eq!([0; offset_of!(Foo, b)].len(), 4);
381 feature = "unstable_const",
382 feature = "unstable_offset_of",
386 fn const_fn_offset() {
387 const fn test_fn() -> usize {
398 assert_eq!([0; test_fn()].len(), 4);