1 | // Copyright 2022 The Fuchsia Authors |
2 | // |
3 | // Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 |
4 | // <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT |
5 | // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. |
6 | // This file may not be copied, modified, or distributed except according to |
7 | // those terms. |
8 | |
9 | //! Utilities used by macros and by `zerocopy-derive`. |
10 | //! |
11 | //! These are defined here `zerocopy` rather than in code generated by macros or |
12 | //! by `zerocopy-derive` so that they can be compiled once rather than |
13 | //! recompiled for every invocation (e.g., if they were defined in generated |
14 | //! code, then deriving `AsBytes` and `FromBytes` on three different types would |
15 | //! result in the code in question being emitted and compiled six different |
16 | //! times). |
17 | |
18 | #![allow (missing_debug_implementations)] |
19 | |
20 | use core::{marker::PhantomData, mem::ManuallyDrop}; |
21 | |
22 | // TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this |
23 | // `cfg` when `size_of_val_raw` is stabilized. |
24 | #[cfg (__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS)] |
25 | use core::ptr::{self, NonNull}; |
26 | |
27 | /// A compile-time check that should be one particular value. |
28 | pub trait ShouldBe<const VALUE: bool> {} |
29 | |
30 | /// A struct for checking whether `T` contains padding. |
31 | pub struct HasPadding<T: ?Sized, const VALUE: bool>(PhantomData<T>); |
32 | |
33 | impl<T: ?Sized, const VALUE: bool> ShouldBe<VALUE> for HasPadding<T, VALUE> {} |
34 | |
35 | /// A type whose size is equal to `align_of::<T>()`. |
36 | #[repr (C)] |
37 | pub struct AlignOf<T> { |
38 | // This field ensures that: |
39 | // - The size is always at least 1 (the minimum possible alignment). |
40 | // - If the alignment is greater than 1, Rust has to round up to the next |
41 | // multiple of it in order to make sure that `Align`'s size is a multiple |
42 | // of that alignment. Without this field, its size could be 0, which is a |
43 | // valid multiple of any alignment. |
44 | _u: u8, |
45 | _a: [T; 0], |
46 | } |
47 | |
48 | impl<T> AlignOf<T> { |
49 | #[inline (never)] // Make `missing_inline_in_public_items` happy. |
50 | pub fn into_t(self) -> T { |
51 | unreachable!() |
52 | } |
53 | } |
54 | |
55 | /// A type whose size is equal to `max(align_of::<T>(), align_of::<U>())`. |
56 | #[repr (C)] |
57 | pub union MaxAlignsOf<T, U> { |
58 | _t: ManuallyDrop<AlignOf<T>>, |
59 | _u: ManuallyDrop<AlignOf<U>>, |
60 | } |
61 | |
62 | impl<T, U> MaxAlignsOf<T, U> { |
63 | #[inline (never)] // Make `missing_inline_in_public_items` happy. |
64 | pub fn new(_t: T, _u: U) -> MaxAlignsOf<T, U> { |
65 | unreachable!() |
66 | } |
67 | } |
68 | |
69 | const _64K: usize = 1 << 16; |
70 | |
71 | // TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this |
72 | // `cfg` when `size_of_val_raw` is stabilized. |
73 | #[cfg (__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS)] |
74 | #[repr (C, align(65536))] |
75 | struct Aligned64kAllocation([u8; _64K]); |
76 | |
77 | /// A pointer to an aligned allocation of size 2^16. |
78 | /// |
79 | /// # Safety |
80 | /// |
81 | /// `ALIGNED_64K_ALLOCATION` is guaranteed to point to the entirety of an |
82 | /// allocation with size and alignment 2^16, and to have valid provenance. |
83 | // TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this |
84 | // `cfg` when `size_of_val_raw` is stabilized. |
85 | #[cfg (__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS)] |
86 | pub const ALIGNED_64K_ALLOCATION: NonNull<[u8]> = { |
87 | const REF: &Aligned64kAllocation = &Aligned64kAllocation([0; _64K]); |
88 | let ptr: *const Aligned64kAllocation = REF; |
89 | let ptr: *const [u8] = ptr::slice_from_raw_parts(ptr.cast(), _64K); |
90 | // SAFETY: |
91 | // - `ptr` is derived from a Rust reference, which is guaranteed to be |
92 | // non-null. |
93 | // - `ptr` is derived from an `&Aligned64kAllocation`, which has size and |
94 | // alignment `_64K` as promised. Its length is initialized to `_64K`, |
95 | // which means that it refers to the entire allocation. |
96 | // - `ptr` is derived from a Rust reference, which is guaranteed to have |
97 | // valid provenance. |
98 | // |
99 | // TODO(#429): Once `NonNull::new_unchecked` docs document that it preserves |
100 | // provenance, cite those docs. |
101 | // TODO: Replace this `as` with `ptr.cast_mut()` once our MSRV >= 1.65 |
102 | #[allow (clippy::as_conversions)] |
103 | unsafe { |
104 | NonNull::new_unchecked(ptr as *mut _) |
105 | } |
106 | }; |
107 | |
108 | /// Computes the offset of the base of the field `$trailing_field_name` within |
109 | /// the type `$ty`. |
110 | /// |
111 | /// `trailing_field_offset!` produces code which is valid in a `const` context. |
112 | // TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this |
113 | // `cfg` when `size_of_val_raw` is stabilized. |
114 | #[cfg (__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS)] |
115 | #[doc (hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`. |
116 | #[macro_export ] |
117 | macro_rules! trailing_field_offset { |
118 | ($ty:ty, $trailing_field_name:tt) => {{ |
119 | let min_size = { |
120 | let zero_elems: *const [()] = |
121 | $crate::macro_util::core_reexport::ptr::slice_from_raw_parts( |
122 | $crate::macro_util::core_reexport::ptr::NonNull::<()>::dangling() |
123 | .as_ptr() |
124 | .cast_const(), |
125 | 0, |
126 | ); |
127 | // SAFETY: |
128 | // - If `$ty` is `Sized`, `size_of_val_raw` is always safe to call. |
129 | // - Otherwise: |
130 | // - If `$ty` is not a slice DST, this pointer conversion will |
131 | // fail due to "mismatched vtable kinds", and compilation will |
132 | // fail. |
133 | // - If `$ty` is a slice DST, the safety requirement is that "the |
134 | // length of the slice tail must be an initialized integer, and |
135 | // the size of the entire value (dynamic tail length + |
136 | // statically sized prefix) must fit in isize." The length is |
137 | // initialized to 0 above, and Rust guarantees that no type's |
138 | // minimum size may overflow `isize`. [1] |
139 | // |
140 | // [1] TODO(#429), |
141 | // TODO(https://github.com/rust-lang/unsafe-code-guidelines/issues/465#issuecomment-1782206516): |
142 | // Citation for this? |
143 | unsafe { |
144 | #[allow(clippy::as_conversions)] |
145 | $crate::macro_util::core_reexport::mem::size_of_val_raw(zero_elems as *const $ty) |
146 | } |
147 | }; |
148 | |
149 | assert!(min_size <= _64K); |
150 | |
151 | #[allow(clippy::as_conversions)] |
152 | let ptr = ALIGNED_64K_ALLOCATION.as_ptr() as *const $ty; |
153 | |
154 | // SAFETY: |
155 | // - Thanks to the preceding `assert!`, we know that the value with zero |
156 | // elements fits in `_64K` bytes, and thus in the allocation addressed |
157 | // by `ALIGNED_64K_ALLOCATION`. The offset of the trailing field is |
158 | // guaranteed to be no larger than this size, so this field projection |
159 | // is guaranteed to remain in-bounds of its allocation. |
160 | // - Because the minimum size is no larger than `_64K` bytes, and |
161 | // because an object's size must always be a multiple of its alignment |
162 | // [1], we know that `$ty`'s alignment is no larger than `_64K`. The |
163 | // allocation addressed by `ALIGNED_64K_ALLOCATION` is guaranteed to |
164 | // be aligned to `_64K`, so `ptr` is guaranteed to satisfy `$ty`'s |
165 | // alignment. |
166 | // |
167 | // Note that, as of [2], this requirement is technically unnecessary |
168 | // for Rust versions >= 1.75.0, but no harm in guaranteeing it anyway |
169 | // until we bump our MSRV. |
170 | // |
171 | // [1] Per https://doc.rust-lang.org/reference/type-layout.html: |
172 | // |
173 | // The size of a value is always a multiple of its alignment. |
174 | // |
175 | // [2] https://github.com/rust-lang/reference/pull/1387 |
176 | let field = unsafe { |
177 | $crate::macro_util::core_reexport::ptr::addr_of!((*ptr).$trailing_field_name) |
178 | }; |
179 | // SAFETY: |
180 | // - Both `ptr` and `field` are derived from the same allocated object. |
181 | // - By the preceding safety comment, `field` is in bounds of that |
182 | // allocated object. |
183 | // - The distance, in bytes, between `ptr` and `field` is required to be |
184 | // a multiple of the size of `u8`, which is trivially true because |
185 | // `u8`'s size is 1. |
186 | // - The distance, in bytes, cannot overflow `isize`. This is guaranteed |
187 | // because no allocated object can have a size larger than can fit in |
188 | // `isize`. [1] |
189 | // - The distance being in-bounds cannot rely on wrapping around the |
190 | // address space. This is guaranteed because the same is guaranteed of |
191 | // allocated objects. [1] |
192 | // |
193 | // [1] TODO(#429), TODO(https://github.com/rust-lang/rust/pull/116675): |
194 | // Once these are guaranteed in the Reference, cite it. |
195 | let offset = unsafe { field.cast::<u8>().offset_from(ptr.cast::<u8>()) }; |
196 | // Guaranteed not to be lossy: `field` comes after `ptr`, so the offset |
197 | // from `ptr` to `field` is guaranteed to be positive. |
198 | assert!(offset >= 0); |
199 | Some( |
200 | #[allow(clippy::as_conversions)] |
201 | { |
202 | offset as usize |
203 | }, |
204 | ) |
205 | }}; |
206 | } |
207 | |
208 | /// Computes alignment of `$ty: ?Sized`. |
209 | /// |
210 | /// `align_of!` produces code which is valid in a `const` context. |
211 | // TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this |
212 | // `cfg` when `size_of_val_raw` is stabilized. |
213 | #[cfg (__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS)] |
214 | #[doc (hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`. |
215 | #[macro_export ] |
216 | macro_rules! align_of { |
217 | ($ty:ty) => {{ |
218 | // SAFETY: `OffsetOfTrailingIsAlignment` is `repr(C)`, and its layout is |
219 | // guaranteed [1] to begin with the single-byte layout for `_byte`, |
220 | // followed by the padding needed to align `_trailing`, then the layout |
221 | // for `_trailing`, and finally any trailing padding bytes needed to |
222 | // correctly-align the entire struct. |
223 | // |
224 | // This macro computes the alignment of `$ty` by counting the number of |
225 | // bytes preceeding `_trailing`. For instance, if the alignment of `$ty` |
226 | // is `1`, then no padding is required align `_trailing` and it will be |
227 | // located immediately after `_byte` at offset 1. If the alignment of |
228 | // `$ty` is 2, then a single padding byte is required before |
229 | // `_trailing`, and `_trailing` will be located at offset 2. |
230 | |
231 | // This correspondence between offset and alignment holds for all valid |
232 | // Rust alignments, and we confirm this exhaustively (or, at least up to |
233 | // the maximum alignment supported by `trailing_field_offset!`) in |
234 | // `test_align_of_dst`. |
235 | // |
236 | // [1]: https://doc.rust-lang.org/nomicon/other-reprs.html#reprc |
237 | |
238 | #[repr(C)] |
239 | struct OffsetOfTrailingIsAlignment { |
240 | _byte: u8, |
241 | _trailing: $ty, |
242 | } |
243 | |
244 | trailing_field_offset!(OffsetOfTrailingIsAlignment, _trailing) |
245 | }}; |
246 | } |
247 | |
248 | /// Does the struct type `$t` have padding? |
249 | /// |
250 | /// `$ts` is the list of the type of every field in `$t`. `$t` must be a |
251 | /// struct type, or else `struct_has_padding!`'s result may be meaningless. |
252 | /// |
253 | /// Note that `struct_has_padding!`'s results are independent of `repr` since |
254 | /// they only consider the size of the type and the sizes of the fields. |
255 | /// Whatever the repr, the size of the type already takes into account any |
256 | /// padding that the compiler has decided to add. Structs with well-defined |
257 | /// representations (such as `repr(C)`) can use this macro to check for padding. |
258 | /// Note that while this may yield some consistent value for some `repr(Rust)` |
259 | /// structs, it is not guaranteed across platforms or compilations. |
260 | #[doc (hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`. |
261 | #[macro_export ] |
262 | macro_rules! struct_has_padding { |
263 | ($t:ty, $($ts:ty),*) => { |
264 | core::mem::size_of::<$t>() > 0 $(+ core::mem::size_of::<$ts>())* |
265 | }; |
266 | } |
267 | |
268 | /// Does the union type `$t` have padding? |
269 | /// |
270 | /// `$ts` is the list of the type of every field in `$t`. `$t` must be a |
271 | /// union type, or else `union_has_padding!`'s result may be meaningless. |
272 | /// |
273 | /// Note that `union_has_padding!`'s results are independent of `repr` since |
274 | /// they only consider the size of the type and the sizes of the fields. |
275 | /// Whatever the repr, the size of the type already takes into account any |
276 | /// padding that the compiler has decided to add. Unions with well-defined |
277 | /// representations (such as `repr(C)`) can use this macro to check for padding. |
278 | /// Note that while this may yield some consistent value for some `repr(Rust)` |
279 | /// unions, it is not guaranteed across platforms or compilations. |
280 | #[doc (hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`. |
281 | #[macro_export ] |
282 | macro_rules! union_has_padding { |
283 | ($t:ty, $($ts:ty),*) => { |
284 | false $(|| core::mem::size_of::<$t>() != core::mem::size_of::<$ts>())* |
285 | }; |
286 | } |
287 | |
288 | /// Does `t` have alignment greater than or equal to `u`? If not, this macro |
289 | /// produces a compile error. It must be invoked in a dead codepath. This is |
290 | /// used in `transmute_ref!` and `transmute_mut!`. |
291 | #[doc (hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`. |
292 | #[macro_export ] |
293 | macro_rules! assert_align_gt_eq { |
294 | ($t:ident, $u: ident) => {{ |
295 | // The comments here should be read in the context of this macro's |
296 | // invocations in `transmute_ref!` and `transmute_mut!`. |
297 | #[allow(clippy::missing_transmute_annotations)] |
298 | if false { |
299 | // The type wildcard in this bound is inferred to be `T` because |
300 | // `align_of.into_t()` is assigned to `t` (which has type `T`). |
301 | let align_of: $crate::macro_util::AlignOf<_> = unreachable!(); |
302 | $t = align_of.into_t(); |
303 | // `max_aligns` is inferred to have type `MaxAlignsOf<T, U>` because |
304 | // of the inferred types of `t` and `u`. |
305 | let mut max_aligns = $crate::macro_util::MaxAlignsOf::new($t, $u); |
306 | |
307 | // This transmute will only compile successfully if |
308 | // `align_of::<T>() == max(align_of::<T>(), align_of::<U>())` - in |
309 | // other words, if `align_of::<T>() >= align_of::<U>()`. |
310 | // |
311 | // SAFETY: This code is never run. |
312 | max_aligns = unsafe { $crate::macro_util::core_reexport::mem::transmute(align_of) }; |
313 | } else { |
314 | loop {} |
315 | } |
316 | }}; |
317 | } |
318 | |
319 | /// Do `t` and `u` have the same size? If not, this macro produces a compile |
320 | /// error. It must be invoked in a dead codepath. This is used in |
321 | /// `transmute_ref!` and `transmute_mut!`. |
322 | #[doc (hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`. |
323 | #[macro_export ] |
324 | macro_rules! assert_size_eq { |
325 | ($t:ident, $u: ident) => {{ |
326 | // The comments here should be read in the context of this macro's |
327 | // invocations in `transmute_ref!` and `transmute_mut!`. |
328 | if false { |
329 | // SAFETY: This code is never run. |
330 | $u = unsafe { |
331 | // Clippy: It's okay to transmute a type to itself. |
332 | #[allow(clippy::useless_transmute, clippy::missing_transmute_annotations)] |
333 | $crate::macro_util::core_reexport::mem::transmute($t) |
334 | }; |
335 | } else { |
336 | loop {} |
337 | } |
338 | }}; |
339 | } |
340 | |
341 | /// Transmutes a reference of one type to a reference of another type. |
342 | /// |
343 | /// # Safety |
344 | /// |
345 | /// The caller must guarantee that: |
346 | /// - `Src: AsBytes` |
347 | /// - `Dst: FromBytes` |
348 | /// - `size_of::<Src>() == size_of::<Dst>()` |
349 | /// - `align_of::<Src>() >= align_of::<Dst>()` |
350 | #[inline (always)] |
351 | pub const unsafe fn transmute_ref<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( |
352 | src: &'src Src, |
353 | ) -> &'dst Dst { |
354 | let src: *const Src = src; |
355 | let dst: *const Dst = src.cast::<Dst>(); |
356 | // SAFETY: |
357 | // - We know that it is sound to view the target type of the input reference |
358 | // (`Src`) as the target type of the output reference (`Dst`) because the |
359 | // caller has guaranteed that `Src: AsBytes`, `Dst: FromBytes`, and |
360 | // `size_of::<Src>() == size_of::<Dst>()`. |
361 | // - We know that there are no `UnsafeCell`s, and thus we don't have to |
362 | // worry about `UnsafeCell` overlap, because `Src: AsBytes` and `Dst: |
363 | // FromBytes` both forbid `UnsafeCell`s. |
364 | // - The caller has guaranteed that alignment is not increased. |
365 | // - We know that the returned lifetime will not outlive the input lifetime |
366 | // thanks to the lifetime bounds on this function. |
367 | unsafe { &*dst } |
368 | } |
369 | |
370 | /// Transmutes a mutable reference of one type to a mutable reference of another |
371 | /// type. |
372 | /// |
373 | /// # Safety |
374 | /// |
375 | /// The caller must guarantee that: |
376 | /// - `Src: FromBytes + AsBytes` |
377 | /// - `Dst: FromBytes + AsBytes` |
378 | /// - `size_of::<Src>() == size_of::<Dst>()` |
379 | /// - `align_of::<Src>() >= align_of::<Dst>()` |
380 | #[inline (always)] |
381 | pub unsafe fn transmute_mut<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( |
382 | src: &'src mut Src, |
383 | ) -> &'dst mut Dst { |
384 | let src: *mut Src = src; |
385 | let dst: *mut Dst = src.cast::<Dst>(); |
386 | // SAFETY: |
387 | // - We know that it is sound to view the target type of the input reference |
388 | // (`Src`) as the target type of the output reference (`Dst`) and |
389 | // vice-versa because the caller has guaranteed that `Src: FromBytes + |
390 | // AsBytes`, `Dst: FromBytes + AsBytes`, and `size_of::<Src>() == |
391 | // size_of::<Dst>()`. |
392 | // - We know that there are no `UnsafeCell`s, and thus we don't have to |
393 | // worry about `UnsafeCell` overlap, because `Src: FromBytes + AsBytes` |
394 | // and `Dst: FromBytes + AsBytes` forbid `UnsafeCell`s. |
395 | // - The caller has guaranteed that alignment is not increased. |
396 | // - We know that the returned lifetime will not outlive the input lifetime |
397 | // thanks to the lifetime bounds on this function. |
398 | unsafe { &mut *dst } |
399 | } |
400 | |
401 | // NOTE: We can't change this to a `pub use core as core_reexport` until [1] is |
402 | // fixed or we update to a semver-breaking version (as of this writing, 0.8.0) |
403 | // on the `main` branch. |
404 | // |
405 | // [1] https://github.com/obi1kenobi/cargo-semver-checks/issues/573 |
406 | pub mod core_reexport { |
407 | pub use core::*; |
408 | |
409 | pub mod mem { |
410 | pub use core::mem::*; |
411 | } |
412 | } |
413 | |
414 | #[cfg (test)] |
415 | mod tests { |
416 | use core::mem; |
417 | |
418 | use super::*; |
419 | use crate::util::testutil::*; |
420 | |
421 | #[test ] |
422 | fn test_align_of() { |
423 | macro_rules! test { |
424 | ($ty:ty) => { |
425 | assert_eq!(mem::size_of::<AlignOf<$ty>>(), mem::align_of::<$ty>()); |
426 | }; |
427 | } |
428 | |
429 | test !(()); |
430 | test !(u8); |
431 | test !(AU64); |
432 | test !([AU64; 2]); |
433 | } |
434 | |
435 | #[test ] |
436 | fn test_max_aligns_of() { |
437 | macro_rules! test { |
438 | ($t:ty, $u:ty) => { |
439 | assert_eq!( |
440 | mem::size_of::<MaxAlignsOf<$t, $u>>(), |
441 | core::cmp::max(mem::align_of::<$t>(), mem::align_of::<$u>()) |
442 | ); |
443 | }; |
444 | } |
445 | |
446 | test !(u8, u8); |
447 | test !(u8, AU64); |
448 | test !(AU64, u8); |
449 | } |
450 | |
451 | #[test ] |
452 | fn test_typed_align_check() { |
453 | // Test that the type-based alignment check used in |
454 | // `assert_align_gt_eq!` behaves as expected. |
455 | |
456 | macro_rules! assert_t_align_gteq_u_align { |
457 | ($t:ty, $u:ty, $gteq:expr) => { |
458 | assert_eq!( |
459 | mem::size_of::<MaxAlignsOf<$t, $u>>() == mem::size_of::<AlignOf<$t>>(), |
460 | $gteq |
461 | ); |
462 | }; |
463 | } |
464 | |
465 | assert_t_align_gteq_u_align!(u8, u8, true); |
466 | assert_t_align_gteq_u_align!(AU64, AU64, true); |
467 | assert_t_align_gteq_u_align!(AU64, u8, true); |
468 | assert_t_align_gteq_u_align!(u8, AU64, false); |
469 | } |
470 | |
471 | // TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove |
472 | // this `cfg` when `size_of_val_raw` is stabilized. |
473 | #[allow (clippy::decimal_literal_representation)] |
474 | #[cfg (__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS)] |
475 | #[test ] |
476 | fn test_trailing_field_offset() { |
477 | assert_eq!(mem::align_of::<Aligned64kAllocation>(), _64K); |
478 | |
479 | macro_rules! test { |
480 | (#[$cfg:meta] ($($ts:ty),* ; $trailing_field_ty:ty) => $expect:expr) => {{ |
481 | #[$cfg] |
482 | #[allow(dead_code)] // fields are never read |
483 | struct Test($($ts,)* $trailing_field_ty); |
484 | assert_eq!(test!(@offset $($ts),* ; $trailing_field_ty), $expect); |
485 | }}; |
486 | (#[$cfg:meta] $(#[$cfgs:meta])* ($($ts:ty),* ; $trailing_field_ty:ty) => $expect:expr) => { |
487 | test!(#[$cfg] ($($ts),* ; $trailing_field_ty) => $expect); |
488 | test!($(#[$cfgs])* ($($ts),* ; $trailing_field_ty) => $expect); |
489 | }; |
490 | (@offset ; $_trailing:ty) => { trailing_field_offset!(Test, 0) }; |
491 | (@offset $_t:ty ; $_trailing:ty) => { trailing_field_offset!(Test, 1) }; |
492 | } |
493 | |
494 | test !(#[repr(C)] #[repr(transparent)] #[repr(packed)](; u8) => Some(0)); |
495 | test !(#[repr(C)] #[repr(transparent)] #[repr(packed)](; [u8]) => Some(0)); |
496 | test !(#[repr(C)] #[repr(C, packed)] (u8; u8) => Some(1)); |
497 | test !(#[repr(C)] (; AU64) => Some(0)); |
498 | test !(#[repr(C)] (; [AU64]) => Some(0)); |
499 | test !(#[repr(C)] (u8; AU64) => Some(8)); |
500 | test !(#[repr(C)] (u8; [AU64]) => Some(8)); |
501 | test !(#[repr(C)] (; Nested<u8, AU64>) => Some(0)); |
502 | test !(#[repr(C)] (; Nested<u8, [AU64]>) => Some(0)); |
503 | test !(#[repr(C)] (u8; Nested<u8, AU64>) => Some(8)); |
504 | test !(#[repr(C)] (u8; Nested<u8, [AU64]>) => Some(8)); |
505 | |
506 | // Test that `packed(N)` limits the offset of the trailing field. |
507 | test !(#[repr(C, packed( 1))] (u8; elain::Align< 2>) => Some( 1)); |
508 | test !(#[repr(C, packed( 2))] (u8; elain::Align< 4>) => Some( 2)); |
509 | test !(#[repr(C, packed( 4))] (u8; elain::Align< 8>) => Some( 4)); |
510 | test !(#[repr(C, packed( 8))] (u8; elain::Align< 16>) => Some( 8)); |
511 | test !(#[repr(C, packed( 16))] (u8; elain::Align< 32>) => Some( 16)); |
512 | test !(#[repr(C, packed( 32))] (u8; elain::Align< 64>) => Some( 32)); |
513 | test !(#[repr(C, packed( 64))] (u8; elain::Align< 128>) => Some( 64)); |
514 | test !(#[repr(C, packed( 128))] (u8; elain::Align< 256>) => Some( 128)); |
515 | test !(#[repr(C, packed( 256))] (u8; elain::Align< 512>) => Some( 256)); |
516 | test !(#[repr(C, packed( 512))] (u8; elain::Align< 1024>) => Some( 512)); |
517 | test !(#[repr(C, packed( 1024))] (u8; elain::Align< 2048>) => Some( 1024)); |
518 | test !(#[repr(C, packed( 2048))] (u8; elain::Align< 4096>) => Some( 2048)); |
519 | test !(#[repr(C, packed( 4096))] (u8; elain::Align< 8192>) => Some( 4096)); |
520 | test !(#[repr(C, packed( 8192))] (u8; elain::Align< 16384>) => Some( 8192)); |
521 | test !(#[repr(C, packed( 16384))] (u8; elain::Align< 32768>) => Some( 16384)); |
522 | test !(#[repr(C, packed( 32768))] (u8; elain::Align< 65536>) => Some( 32768)); |
523 | test !(#[repr(C, packed( 65536))] (u8; elain::Align< 131072>) => Some( 65536)); |
524 | /* Alignments above 65536 are not yet supported. |
525 | test!(#[repr(C, packed( 131072))] (u8; elain::Align< 262144>) => Some( 131072)); |
526 | test!(#[repr(C, packed( 262144))] (u8; elain::Align< 524288>) => Some( 262144)); |
527 | test!(#[repr(C, packed( 524288))] (u8; elain::Align< 1048576>) => Some( 524288)); |
528 | test!(#[repr(C, packed( 1048576))] (u8; elain::Align< 2097152>) => Some( 1048576)); |
529 | test!(#[repr(C, packed( 2097152))] (u8; elain::Align< 4194304>) => Some( 2097152)); |
530 | test!(#[repr(C, packed( 4194304))] (u8; elain::Align< 8388608>) => Some( 4194304)); |
531 | test!(#[repr(C, packed( 8388608))] (u8; elain::Align< 16777216>) => Some( 8388608)); |
532 | test!(#[repr(C, packed( 16777216))] (u8; elain::Align< 33554432>) => Some( 16777216)); |
533 | test!(#[repr(C, packed( 33554432))] (u8; elain::Align< 67108864>) => Some( 33554432)); |
534 | test!(#[repr(C, packed( 67108864))] (u8; elain::Align< 33554432>) => Some( 67108864)); |
535 | test!(#[repr(C, packed( 33554432))] (u8; elain::Align<134217728>) => Some( 33554432)); |
536 | test!(#[repr(C, packed(134217728))] (u8; elain::Align<268435456>) => Some(134217728)); |
537 | test!(#[repr(C, packed(268435456))] (u8; elain::Align<268435456>) => Some(268435456)); |
538 | */ |
539 | |
540 | // Test that `align(N)` does not limit the offset of the trailing field. |
541 | test !(#[repr(C, align( 1))] (u8; elain::Align< 2>) => Some( 2)); |
542 | test !(#[repr(C, align( 2))] (u8; elain::Align< 4>) => Some( 4)); |
543 | test !(#[repr(C, align( 4))] (u8; elain::Align< 8>) => Some( 8)); |
544 | test !(#[repr(C, align( 8))] (u8; elain::Align< 16>) => Some( 16)); |
545 | test !(#[repr(C, align( 16))] (u8; elain::Align< 32>) => Some( 32)); |
546 | test !(#[repr(C, align( 32))] (u8; elain::Align< 64>) => Some( 64)); |
547 | test !(#[repr(C, align( 64))] (u8; elain::Align< 128>) => Some( 128)); |
548 | test !(#[repr(C, align( 128))] (u8; elain::Align< 256>) => Some( 256)); |
549 | test !(#[repr(C, align( 256))] (u8; elain::Align< 512>) => Some( 512)); |
550 | test !(#[repr(C, align( 512))] (u8; elain::Align< 1024>) => Some( 1024)); |
551 | test !(#[repr(C, align( 1024))] (u8; elain::Align< 2048>) => Some( 2048)); |
552 | test !(#[repr(C, align( 2048))] (u8; elain::Align< 4096>) => Some( 4096)); |
553 | test !(#[repr(C, align( 4096))] (u8; elain::Align< 8192>) => Some( 8192)); |
554 | test !(#[repr(C, align( 8192))] (u8; elain::Align< 16384>) => Some( 16384)); |
555 | test !(#[repr(C, align( 16384))] (u8; elain::Align< 32768>) => Some( 32768)); |
556 | test !(#[repr(C, align( 32768))] (u8; elain::Align< 65536>) => Some( 65536)); |
557 | /* Alignments above 65536 are not yet supported. |
558 | test!(#[repr(C, align( 65536))] (u8; elain::Align< 131072>) => Some( 131072)); |
559 | test!(#[repr(C, align( 131072))] (u8; elain::Align< 262144>) => Some( 262144)); |
560 | test!(#[repr(C, align( 262144))] (u8; elain::Align< 524288>) => Some( 524288)); |
561 | test!(#[repr(C, align( 524288))] (u8; elain::Align< 1048576>) => Some( 1048576)); |
562 | test!(#[repr(C, align( 1048576))] (u8; elain::Align< 2097152>) => Some( 2097152)); |
563 | test!(#[repr(C, align( 2097152))] (u8; elain::Align< 4194304>) => Some( 4194304)); |
564 | test!(#[repr(C, align( 4194304))] (u8; elain::Align< 8388608>) => Some( 8388608)); |
565 | test!(#[repr(C, align( 8388608))] (u8; elain::Align< 16777216>) => Some( 16777216)); |
566 | test!(#[repr(C, align( 16777216))] (u8; elain::Align< 33554432>) => Some( 33554432)); |
567 | test!(#[repr(C, align( 33554432))] (u8; elain::Align< 67108864>) => Some( 67108864)); |
568 | test!(#[repr(C, align( 67108864))] (u8; elain::Align< 33554432>) => Some( 33554432)); |
569 | test!(#[repr(C, align( 33554432))] (u8; elain::Align<134217728>) => Some(134217728)); |
570 | test!(#[repr(C, align(134217728))] (u8; elain::Align<268435456>) => Some(268435456)); |
571 | */ |
572 | } |
573 | |
574 | // TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove |
575 | // this `cfg` when `size_of_val_raw` is stabilized. |
576 | #[allow (clippy::decimal_literal_representation)] |
577 | #[cfg (__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS)] |
578 | #[test ] |
579 | fn test_align_of_dst() { |
580 | // Test that `align_of!` correctly computes the alignment of DSTs. |
581 | assert_eq!(align_of!([elain::Align<1>]), Some(1)); |
582 | assert_eq!(align_of!([elain::Align<2>]), Some(2)); |
583 | assert_eq!(align_of!([elain::Align<4>]), Some(4)); |
584 | assert_eq!(align_of!([elain::Align<8>]), Some(8)); |
585 | assert_eq!(align_of!([elain::Align<16>]), Some(16)); |
586 | assert_eq!(align_of!([elain::Align<32>]), Some(32)); |
587 | assert_eq!(align_of!([elain::Align<64>]), Some(64)); |
588 | assert_eq!(align_of!([elain::Align<128>]), Some(128)); |
589 | assert_eq!(align_of!([elain::Align<256>]), Some(256)); |
590 | assert_eq!(align_of!([elain::Align<512>]), Some(512)); |
591 | assert_eq!(align_of!([elain::Align<1024>]), Some(1024)); |
592 | assert_eq!(align_of!([elain::Align<2048>]), Some(2048)); |
593 | assert_eq!(align_of!([elain::Align<4096>]), Some(4096)); |
594 | assert_eq!(align_of!([elain::Align<8192>]), Some(8192)); |
595 | assert_eq!(align_of!([elain::Align<16384>]), Some(16384)); |
596 | assert_eq!(align_of!([elain::Align<32768>]), Some(32768)); |
597 | assert_eq!(align_of!([elain::Align<65536>]), Some(65536)); |
598 | /* Alignments above 65536 are not yet supported. |
599 | assert_eq!(align_of!([elain::Align<131072>]), Some(131072)); |
600 | assert_eq!(align_of!([elain::Align<262144>]), Some(262144)); |
601 | assert_eq!(align_of!([elain::Align<524288>]), Some(524288)); |
602 | assert_eq!(align_of!([elain::Align<1048576>]), Some(1048576)); |
603 | assert_eq!(align_of!([elain::Align<2097152>]), Some(2097152)); |
604 | assert_eq!(align_of!([elain::Align<4194304>]), Some(4194304)); |
605 | assert_eq!(align_of!([elain::Align<8388608>]), Some(8388608)); |
606 | assert_eq!(align_of!([elain::Align<16777216>]), Some(16777216)); |
607 | assert_eq!(align_of!([elain::Align<33554432>]), Some(33554432)); |
608 | assert_eq!(align_of!([elain::Align<67108864>]), Some(67108864)); |
609 | assert_eq!(align_of!([elain::Align<33554432>]), Some(33554432)); |
610 | assert_eq!(align_of!([elain::Align<134217728>]), Some(134217728)); |
611 | assert_eq!(align_of!([elain::Align<268435456>]), Some(268435456)); |
612 | */ |
613 | } |
614 | |
615 | #[test ] |
616 | fn test_struct_has_padding() { |
617 | // Test that, for each provided repr, `struct_has_padding!` reports the |
618 | // expected value. |
619 | macro_rules! test { |
620 | (#[$cfg:meta] ($($ts:ty),*) => $expect:expr) => {{ |
621 | #[$cfg] |
622 | #[allow(dead_code)] // fields are never read |
623 | struct Test($($ts),*); |
624 | assert_eq!(struct_has_padding!(Test, $($ts),*), $expect); |
625 | }}; |
626 | (#[$cfg:meta] $(#[$cfgs:meta])* ($($ts:ty),*) => $expect:expr) => { |
627 | test!(#[$cfg] ($($ts),*) => $expect); |
628 | test!($(#[$cfgs])* ($($ts),*) => $expect); |
629 | }; |
630 | } |
631 | |
632 | test !(#[repr(C)] #[repr(transparent)] #[repr(packed)] () => false); |
633 | test !(#[repr(C)] #[repr(transparent)] #[repr(packed)] (u8) => false); |
634 | test !(#[repr(C)] #[repr(transparent)] #[repr(packed)] (u8, ()) => false); |
635 | test !(#[repr(C)] #[repr(packed)] (u8, u8) => false); |
636 | |
637 | test !(#[repr(C)] (u8, AU64) => true); |
638 | // Rust won't let you put `#[repr(packed)]` on a type which contains a |
639 | // `#[repr(align(n > 1))]` type (`AU64`), so we have to use `u64` here. |
640 | // It's not ideal, but it definitely has align > 1 on /some/ of our CI |
641 | // targets, and this isn't a particularly complex macro we're testing |
642 | // anyway. |
643 | test !(#[repr(packed)] (u8, u64) => false); |
644 | } |
645 | |
646 | #[test ] |
647 | fn test_union_has_padding() { |
648 | // Test that, for each provided repr, `union_has_padding!` reports the |
649 | // expected value. |
650 | macro_rules! test { |
651 | (#[$cfg:meta] {$($fs:ident: $ts:ty),*} => $expect:expr) => {{ |
652 | #[$cfg] |
653 | #[allow(unused)] // fields are never read |
654 | union Test{ $($fs: $ts),* } |
655 | assert_eq!(union_has_padding!(Test, $($ts),*), $expect); |
656 | }}; |
657 | (#[$cfg:meta] $(#[$cfgs:meta])* {$($fs:ident: $ts:ty),*} => $expect:expr) => { |
658 | test!(#[$cfg] {$($fs: $ts),*} => $expect); |
659 | test!($(#[$cfgs])* {$($fs: $ts),*} => $expect); |
660 | }; |
661 | } |
662 | |
663 | test !(#[repr(C)] #[repr(packed)] {a: u8} => false); |
664 | test !(#[repr(C)] #[repr(packed)] {a: u8, b: u8} => false); |
665 | |
666 | // Rust won't let you put `#[repr(packed)]` on a type which contains a |
667 | // `#[repr(align(n > 1))]` type (`AU64`), so we have to use `u64` here. |
668 | // It's not ideal, but it definitely has align > 1 on /some/ of our CI |
669 | // targets, and this isn't a particularly complex macro we're testing |
670 | // anyway. |
671 | test !(#[repr(C)] #[repr(packed)] {a: u8, b: u64} => true); |
672 | } |
673 | } |
674 | |