xref: /linux/rust/zerocopy/src/pointer/mod.rs (revision b079329b8691768962aa514b8f8c9077ca352459)
1*499dc02cSMiguel Ojeda // SPDX-License-Identifier: (BSD-2-Clause OR Apache-2.0) OR MIT
2*499dc02cSMiguel Ojeda 
3c3739801SMiguel Ojeda // Copyright 2023 The Fuchsia Authors
4c3739801SMiguel Ojeda //
5c3739801SMiguel Ojeda // Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
6c3739801SMiguel Ojeda // <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
7c3739801SMiguel Ojeda // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
8c3739801SMiguel Ojeda // This file may not be copied, modified, or distributed except according to
9c3739801SMiguel Ojeda // those terms.
10c3739801SMiguel Ojeda 
11c3739801SMiguel Ojeda //! Abstractions over raw pointers.
12c3739801SMiguel Ojeda 
13c3739801SMiguel Ojeda #![allow(missing_docs)]
14c3739801SMiguel Ojeda 
15c3739801SMiguel Ojeda mod inner;
16c3739801SMiguel Ojeda pub mod invariant;
17c3739801SMiguel Ojeda mod ptr;
18c3739801SMiguel Ojeda pub mod transmute;
19c3739801SMiguel Ojeda 
20c3739801SMiguel Ojeda pub use inner::PtrInner;
21c3739801SMiguel Ojeda pub use invariant::{BecauseExclusive, BecauseImmutable, Read};
22c3739801SMiguel Ojeda pub use ptr::{Ptr, TryWithError};
23c3739801SMiguel Ojeda pub use transmute::*;
24c3739801SMiguel Ojeda 
25c3739801SMiguel Ojeda use crate::wrappers::ReadOnly;
26c3739801SMiguel Ojeda 
27c3739801SMiguel Ojeda /// A shorthand for a maybe-valid, maybe-aligned reference. Used as the argument
28c3739801SMiguel Ojeda /// to [`TryFromBytes::is_bit_valid`].
29c3739801SMiguel Ojeda ///
30c3739801SMiguel Ojeda /// [`TryFromBytes::is_bit_valid`]: crate::TryFromBytes::is_bit_valid
31c3739801SMiguel Ojeda pub type Maybe<'a, T, Alignment = invariant::Unaligned> =
32c3739801SMiguel Ojeda     Ptr<'a, ReadOnly<T>, (invariant::Shared, Alignment, invariant::Initialized)>;
33c3739801SMiguel Ojeda 
34c3739801SMiguel Ojeda /// Checks if the referent is zeroed.
35c3739801SMiguel Ojeda pub(crate) fn is_zeroed<T, I>(ptr: Ptr<'_, T, I>) -> bool
36c3739801SMiguel Ojeda where
37c3739801SMiguel Ojeda     T: crate::Immutable + crate::KnownLayout,
38c3739801SMiguel Ojeda     I: invariant::Invariants<Validity = invariant::Initialized>,
39c3739801SMiguel Ojeda     I::Aliasing: invariant::Reference,
40c3739801SMiguel Ojeda {
41c3739801SMiguel Ojeda     ptr.as_bytes().as_ref().iter().all(
42c3739801SMiguel Ojeda         #[inline(always)]
43c3739801SMiguel Ojeda         |&byte| byte == 0,
44c3739801SMiguel Ojeda     )
45c3739801SMiguel Ojeda }
46c3739801SMiguel Ojeda 
47c3739801SMiguel Ojeda pub mod cast {
48c3739801SMiguel Ojeda     use core::{marker::PhantomData, mem};
49c3739801SMiguel Ojeda 
50c3739801SMiguel Ojeda     use crate::{
51c3739801SMiguel Ojeda         layout::{SizeInfo, TrailingSliceLayout},
52c3739801SMiguel Ojeda         HasField, KnownLayout, PtrInner,
53c3739801SMiguel Ojeda     };
54c3739801SMiguel Ojeda 
55c3739801SMiguel Ojeda     /// A pointer cast or projection.
56c3739801SMiguel Ojeda     ///
57c3739801SMiguel Ojeda     /// # Safety
58c3739801SMiguel Ojeda     ///
59c3739801SMiguel Ojeda     /// The implementation of `project` must satisfy its safety post-condition.
60c3739801SMiguel Ojeda     pub unsafe trait Project<Src: ?Sized, Dst: ?Sized> {
61c3739801SMiguel Ojeda         /// Projects a pointer from `Src` to `Dst`.
62c3739801SMiguel Ojeda         ///
63c3739801SMiguel Ojeda         /// Users should generally not call `project` directly, and instead
64c3739801SMiguel Ojeda         /// should use high-level APIs like [`PtrInner::project`] or
65c3739801SMiguel Ojeda         /// [`Ptr::project`].
66c3739801SMiguel Ojeda         ///
67c3739801SMiguel Ojeda         /// [`Ptr::project`]: crate::pointer::Ptr::project
68c3739801SMiguel Ojeda         ///
69c3739801SMiguel Ojeda         /// # Safety
70c3739801SMiguel Ojeda         ///
71c3739801SMiguel Ojeda         /// The returned pointer refers to a non-strict subset of the bytes of
72c3739801SMiguel Ojeda         /// `src`'s referent, and has the same provenance as `src`.
73c3739801SMiguel Ojeda         fn project(src: PtrInner<'_, Src>) -> *mut Dst;
74c3739801SMiguel Ojeda     }
75c3739801SMiguel Ojeda 
76c3739801SMiguel Ojeda     /// A [`Project`] which preserves the address of the referent – a pointer
77c3739801SMiguel Ojeda     /// cast.
78c3739801SMiguel Ojeda     ///
79c3739801SMiguel Ojeda     /// # Safety
80c3739801SMiguel Ojeda     ///
81c3739801SMiguel Ojeda     /// A `Cast` projection must preserve the address of the referent. It may
82c3739801SMiguel Ojeda     /// shrink the set of referent bytes, and it may change the referent's type.
83c3739801SMiguel Ojeda     pub unsafe trait Cast<Src: ?Sized, Dst: ?Sized>: Project<Src, Dst> {}
84c3739801SMiguel Ojeda 
85c3739801SMiguel Ojeda     /// A [`Cast`] which does not shrink the set of referent bytes.
86c3739801SMiguel Ojeda     ///
87c3739801SMiguel Ojeda     /// # Safety
88c3739801SMiguel Ojeda     ///
89c3739801SMiguel Ojeda     /// A `CastExact` projection must preserve the set of referent bytes.
90c3739801SMiguel Ojeda     pub unsafe trait CastExact<Src: ?Sized, Dst: ?Sized>: Cast<Src, Dst> {}
91c3739801SMiguel Ojeda 
92c3739801SMiguel Ojeda     /// A no-op pointer cast.
93c3739801SMiguel Ojeda     #[derive(Default, Copy, Clone)]
94c3739801SMiguel Ojeda     #[allow(missing_debug_implementations)]
95c3739801SMiguel Ojeda     pub struct IdCast;
96c3739801SMiguel Ojeda 
97c3739801SMiguel Ojeda     // SAFETY: `project` returns its argument unchanged, and so it is a
98c3739801SMiguel Ojeda     // provenance-preserving projection which preserves the set of referent
99c3739801SMiguel Ojeda     // bytes.
100c3739801SMiguel Ojeda     unsafe impl<T: ?Sized> Project<T, T> for IdCast {
101c3739801SMiguel Ojeda         #[inline(always)]
102c3739801SMiguel Ojeda         fn project(src: PtrInner<'_, T>) -> *mut T {
103c3739801SMiguel Ojeda             src.as_ptr()
104c3739801SMiguel Ojeda         }
105c3739801SMiguel Ojeda     }
106c3739801SMiguel Ojeda 
107c3739801SMiguel Ojeda     // SAFETY: The `Project::project` impl preserves referent address.
108c3739801SMiguel Ojeda     unsafe impl<T: ?Sized> Cast<T, T> for IdCast {}
109c3739801SMiguel Ojeda 
110c3739801SMiguel Ojeda     // SAFETY: The `Project::project` impl preserves referent size.
111c3739801SMiguel Ojeda     unsafe impl<T: ?Sized> CastExact<T, T> for IdCast {}
112c3739801SMiguel Ojeda 
113c3739801SMiguel Ojeda     /// A pointer cast which preserves or shrinks the set of referent bytes of
114c3739801SMiguel Ojeda     /// a statically-sized referent.
115c3739801SMiguel Ojeda     ///
116c3739801SMiguel Ojeda     /// # Safety
117c3739801SMiguel Ojeda     ///
118c3739801SMiguel Ojeda     /// The implementation of [`Project`] uses a compile-time assertion to
119c3739801SMiguel Ojeda     /// guarantee that `Dst` is no larger than `Src`. Thus, `CastSized` has a
120c3739801SMiguel Ojeda     /// sound implementation of [`Project`] for all `Src` and `Dst` – the caller
121c3739801SMiguel Ojeda     /// may pass any `Src` and `Dst` without being responsible for soundness.
122c3739801SMiguel Ojeda     #[allow(missing_debug_implementations, missing_copy_implementations)]
123c3739801SMiguel Ojeda     pub enum CastSized {}
124c3739801SMiguel Ojeda 
125c3739801SMiguel Ojeda     // SAFETY: By the `static_assert!`, `Dst` is no larger than `Src`,
126c3739801SMiguel Ojeda     // and so all casts preserve or shrink the set of referent bytes. All
127c3739801SMiguel Ojeda     // operations preserve provenance.
128c3739801SMiguel Ojeda     unsafe impl<Src, Dst> Project<Src, Dst> for CastSized {
129c3739801SMiguel Ojeda         #[inline(always)]
130c3739801SMiguel Ojeda         fn project(src: PtrInner<'_, Src>) -> *mut Dst {
131c3739801SMiguel Ojeda             static_assert!(Src, Dst => mem::size_of::<Src>() >= mem::size_of::<Dst>());
132c3739801SMiguel Ojeda             src.as_ptr().cast::<Dst>()
133c3739801SMiguel Ojeda         }
134c3739801SMiguel Ojeda     }
135c3739801SMiguel Ojeda 
136c3739801SMiguel Ojeda     // SAFETY: The `Project::project` impl preserves referent address.
137c3739801SMiguel Ojeda     unsafe impl<Src, Dst> Cast<Src, Dst> for CastSized {}
138c3739801SMiguel Ojeda 
139c3739801SMiguel Ojeda     /// A pointer cast which preserves the set of referent bytes of a
140c3739801SMiguel Ojeda     /// statically-sized referent.
141c3739801SMiguel Ojeda     ///
142c3739801SMiguel Ojeda     /// # Safety
143c3739801SMiguel Ojeda     ///
144c3739801SMiguel Ojeda     /// The implementation of [`Project`] uses a compile-time assertion to
145c3739801SMiguel Ojeda     /// guarantee that `Dst` has the same size as `Src`. Thus, `CastSizedExact`
146c3739801SMiguel Ojeda     /// has a sound implementation of [`Project`] for all `Src` and `Dst` – the
147c3739801SMiguel Ojeda     /// caller may pass any `Src` and `Dst` without being responsible for
148c3739801SMiguel Ojeda     /// soundness.
149c3739801SMiguel Ojeda     #[allow(missing_debug_implementations, missing_copy_implementations)]
150c3739801SMiguel Ojeda     pub enum CastSizedExact {}
151c3739801SMiguel Ojeda 
152c3739801SMiguel Ojeda     // SAFETY: By the `static_assert!`, `Dst` has the same size as `Src`,
153c3739801SMiguel Ojeda     // and so all casts preserve the set of referent bytes. All operations
154c3739801SMiguel Ojeda     // preserve provenance.
155c3739801SMiguel Ojeda     unsafe impl<Src, Dst> Project<Src, Dst> for CastSizedExact {
156c3739801SMiguel Ojeda         #[inline(always)]
157c3739801SMiguel Ojeda         fn project(src: PtrInner<'_, Src>) -> *mut Dst {
158c3739801SMiguel Ojeda             static_assert!(Src, Dst => mem::size_of::<Src>() == mem::size_of::<Dst>());
159c3739801SMiguel Ojeda             src.as_ptr().cast::<Dst>()
160c3739801SMiguel Ojeda         }
161c3739801SMiguel Ojeda     }
162c3739801SMiguel Ojeda 
163c3739801SMiguel Ojeda     // SAFETY: The `Project::project_raw` impl preserves referent address.
164c3739801SMiguel Ojeda     unsafe impl<Src, Dst> Cast<Src, Dst> for CastSizedExact {}
165c3739801SMiguel Ojeda 
166c3739801SMiguel Ojeda     // SAFETY: By the `static_assert!`, `Project::project_raw` impl preserves
167c3739801SMiguel Ojeda     // referent size.
168c3739801SMiguel Ojeda     unsafe impl<Src, Dst> CastExact<Src, Dst> for CastSizedExact {}
169c3739801SMiguel Ojeda 
170c3739801SMiguel Ojeda     /// A pointer cast which preserves or shrinks the set of referent bytes of
171c3739801SMiguel Ojeda     /// a dynamically-sized referent.
172c3739801SMiguel Ojeda     ///
173c3739801SMiguel Ojeda     /// # Safety
174c3739801SMiguel Ojeda     ///
175c3739801SMiguel Ojeda     /// The implementation of [`Project`] uses a compile-time assertion to
176c3739801SMiguel Ojeda     /// guarantee that the cast preserves the set of referent bytes. Thus,
177c3739801SMiguel Ojeda     /// `CastUnsized` has a sound implementation of [`Project`] for all `Src`
178c3739801SMiguel Ojeda     /// and `Dst` – the caller may pass any `Src` and `Dst` without being
179c3739801SMiguel Ojeda     /// responsible for soundness.
180c3739801SMiguel Ojeda     #[allow(missing_debug_implementations, missing_copy_implementations)]
181c3739801SMiguel Ojeda     pub enum CastUnsized {}
182c3739801SMiguel Ojeda 
183c3739801SMiguel Ojeda     // SAFETY: By the `static_assert!`, `Src` and `Dst` are either:
184c3739801SMiguel Ojeda     // - Both sized and equal in size
185c3739801SMiguel Ojeda     // - Both slice DSTs with the same trailing slice offset and element size
186c3739801SMiguel Ojeda     //   and with align_of::<Src>() == align_of::<Dst>(). These ensure that any
187c3739801SMiguel Ojeda     //   given pointer metadata encodes the same size for both `Src` and `Dst`
188c3739801SMiguel Ojeda     //   (note that the alignment is required as it affects the amount of
189c3739801SMiguel Ojeda     //   trailing padding). Thus, `project` preserves the set of referent bytes.
190c3739801SMiguel Ojeda     unsafe impl<Src, Dst> Project<Src, Dst> for CastUnsized
191c3739801SMiguel Ojeda     where
192c3739801SMiguel Ojeda         Src: ?Sized + KnownLayout,
193c3739801SMiguel Ojeda         Dst: ?Sized + KnownLayout<PointerMetadata = Src::PointerMetadata>,
194c3739801SMiguel Ojeda     {
195c3739801SMiguel Ojeda         #[inline(always)]
196c3739801SMiguel Ojeda         fn project(src: PtrInner<'_, Src>) -> *mut Dst {
197c3739801SMiguel Ojeda             // FIXME: Do we want this to support shrinking casts as well? If so,
198c3739801SMiguel Ojeda             // we'll need to remove the `CastExact` impl.
199c3739801SMiguel Ojeda             static_assert!(Src: ?Sized + KnownLayout, Dst: ?Sized + KnownLayout => {
200c3739801SMiguel Ojeda                 let src = <Src as KnownLayout>::LAYOUT;
201c3739801SMiguel Ojeda                 let dst = <Dst as KnownLayout>::LAYOUT;
202c3739801SMiguel Ojeda                 match (src.size_info, dst.size_info) {
203c3739801SMiguel Ojeda                     (SizeInfo::Sized { size: src_size }, SizeInfo::Sized { size: dst_size }) => src_size == dst_size,
204c3739801SMiguel Ojeda                     (
205c3739801SMiguel Ojeda                         SizeInfo::SliceDst(TrailingSliceLayout { offset: src_offset, elem_size: src_elem_size }),
206c3739801SMiguel Ojeda                         SizeInfo::SliceDst(TrailingSliceLayout { offset: dst_offset, elem_size: dst_elem_size })
207c3739801SMiguel Ojeda                     ) => src.align.get() == dst.align.get() && src_offset == dst_offset && src_elem_size == dst_elem_size,
208c3739801SMiguel Ojeda                     _ => false,
209c3739801SMiguel Ojeda                 }
210c3739801SMiguel Ojeda             });
211c3739801SMiguel Ojeda 
212c3739801SMiguel Ojeda             let metadata = Src::pointer_to_metadata(src.as_ptr());
213c3739801SMiguel Ojeda             Dst::raw_from_ptr_len(src.as_non_null().cast::<u8>(), metadata).as_ptr()
214c3739801SMiguel Ojeda         }
215c3739801SMiguel Ojeda     }
216c3739801SMiguel Ojeda 
217c3739801SMiguel Ojeda     // SAFETY: The `Project::project` impl preserves referent address.
218c3739801SMiguel Ojeda     unsafe impl<Src, Dst> Cast<Src, Dst> for CastUnsized
219c3739801SMiguel Ojeda     where
220c3739801SMiguel Ojeda         Src: ?Sized + KnownLayout,
221c3739801SMiguel Ojeda         Dst: ?Sized + KnownLayout<PointerMetadata = Src::PointerMetadata>,
222c3739801SMiguel Ojeda     {
223c3739801SMiguel Ojeda     }
224c3739801SMiguel Ojeda 
225c3739801SMiguel Ojeda     // SAFETY: By the `static_assert!` in `Project::project`, `Src` and `Dst`
226c3739801SMiguel Ojeda     // are either:
227c3739801SMiguel Ojeda     // - Both sized and equal in size
228c3739801SMiguel Ojeda     // - Both slice DSTs with the same alignment, trailing slice offset, and
229c3739801SMiguel Ojeda     //   element size. These ensure that any given pointer metadata encodes the
230c3739801SMiguel Ojeda     //   same size for both `Src` and `Dst` (note that the alignment is required
231c3739801SMiguel Ojeda     //   as it affects the amount of trailing padding).
232c3739801SMiguel Ojeda     unsafe impl<Src, Dst> CastExact<Src, Dst> for CastUnsized
233c3739801SMiguel Ojeda     where
234c3739801SMiguel Ojeda         Src: ?Sized + KnownLayout,
235c3739801SMiguel Ojeda         Dst: ?Sized + KnownLayout<PointerMetadata = Src::PointerMetadata>,
236c3739801SMiguel Ojeda     {
237c3739801SMiguel Ojeda     }
238c3739801SMiguel Ojeda 
239c3739801SMiguel Ojeda     /// A field projection
240c3739801SMiguel Ojeda     ///
241c3739801SMiguel Ojeda     /// A `Projection` is a [`Project`] which implements projection by
242c3739801SMiguel Ojeda     /// delegating to an implementation of [`HasField::project`].
243c3739801SMiguel Ojeda     #[allow(missing_debug_implementations, missing_copy_implementations)]
244c3739801SMiguel Ojeda     pub struct Projection<F: ?Sized, const VARIANT_ID: i128, const FIELD_ID: i128> {
245c3739801SMiguel Ojeda         _never: core::convert::Infallible,
246c3739801SMiguel Ojeda         _phantom: PhantomData<F>,
247c3739801SMiguel Ojeda     }
248c3739801SMiguel Ojeda 
249c3739801SMiguel Ojeda     // SAFETY: `HasField::project` has the same safety post-conditions as
250c3739801SMiguel Ojeda     // `Project::project`.
251c3739801SMiguel Ojeda     unsafe impl<T: ?Sized, F, const VARIANT_ID: i128, const FIELD_ID: i128> Project<T, T::Type>
252c3739801SMiguel Ojeda         for Projection<F, VARIANT_ID, FIELD_ID>
253c3739801SMiguel Ojeda     where
254c3739801SMiguel Ojeda         T: HasField<F, VARIANT_ID, FIELD_ID>,
255c3739801SMiguel Ojeda     {
256c3739801SMiguel Ojeda         #[inline(always)]
257c3739801SMiguel Ojeda         fn project(src: PtrInner<'_, T>) -> *mut T::Type {
258c3739801SMiguel Ojeda             T::project(src)
259c3739801SMiguel Ojeda         }
260c3739801SMiguel Ojeda     }
261c3739801SMiguel Ojeda 
262c3739801SMiguel Ojeda     // SAFETY: All `repr(C)` union fields exist at offset 0 within the union [1],
263c3739801SMiguel Ojeda     // and so any union projection is actually a cast (ie, preserves address).
264c3739801SMiguel Ojeda     //
265c3739801SMiguel Ojeda     // [1] Per
266c3739801SMiguel Ojeda     //     https://doc.rust-lang.org/1.92.0/reference/type-layout.html#reprc-unions,
267c3739801SMiguel Ojeda     //     it's not *technically* guaranteed that non-maximally-sized fields
268c3739801SMiguel Ojeda     //     are at offset 0, but it's clear that this is the intention of `repr(C)`
269c3739801SMiguel Ojeda     //     unions. It says:
270c3739801SMiguel Ojeda     //
271c3739801SMiguel Ojeda     //     > A union declared with `#[repr(C)]` will have the same size and
272c3739801SMiguel Ojeda     //     > alignment as an equivalent C union declaration in the C language for
273c3739801SMiguel Ojeda     //     > the target platform.
274c3739801SMiguel Ojeda     //
275c3739801SMiguel Ojeda     //     Note that this only mentions size and alignment, not layout. However,
276c3739801SMiguel Ojeda     //     C unions *do* guarantee that all fields start at offset 0. [2]
277c3739801SMiguel Ojeda     //
278c3739801SMiguel Ojeda     //     This is also reinforced by
279c3739801SMiguel Ojeda     //     https://doc.rust-lang.org/1.92.0/reference/items/unions.html#r-items.union.fields.offset:
280c3739801SMiguel Ojeda     //
281c3739801SMiguel Ojeda     //     > Fields might have a non-zero offset (except when the C
282c3739801SMiguel Ojeda     //     > representation is used); in that case the bits starting at the
283c3739801SMiguel Ojeda     //     > offset of the fields are read
284c3739801SMiguel Ojeda     //
285c3739801SMiguel Ojeda     // [2] Per https://port70.net/~nsz/c/c11/n1570.html#6.7.2.1p16:
286c3739801SMiguel Ojeda     //
287c3739801SMiguel Ojeda     //     > The size of a union is sufficient to contain the largest of its
288c3739801SMiguel Ojeda     //     > members. The value of at most one of the members can be stored in a
289c3739801SMiguel Ojeda     //     > union object at any time. A pointer to a union object, suitably
290c3739801SMiguel Ojeda     //     > converted, points to each of its members (or if a member is a
291c3739801SMiguel Ojeda     //     > bit-field, then to the unit in which it resides), and vice versa.
292c3739801SMiguel Ojeda     //
293c3739801SMiguel Ojeda     // FIXME(https://github.com/rust-lang/unsafe-code-guidelines/issues/595):
294c3739801SMiguel Ojeda     // Cite the documentation once it's updated.
295c3739801SMiguel Ojeda     unsafe impl<T: ?Sized, F, const FIELD_ID: i128> Cast<T, T::Type>
296c3739801SMiguel Ojeda         for Projection<F, { crate::REPR_C_UNION_VARIANT_ID }, FIELD_ID>
297c3739801SMiguel Ojeda     where
298c3739801SMiguel Ojeda         T: HasField<F, { crate::REPR_C_UNION_VARIANT_ID }, FIELD_ID>,
299c3739801SMiguel Ojeda     {
300c3739801SMiguel Ojeda     }
301c3739801SMiguel Ojeda 
302c3739801SMiguel Ojeda     /// A transitive sequence of projections.
303c3739801SMiguel Ojeda     ///
304c3739801SMiguel Ojeda     /// Given `TU: Project` and `UV: Project`, `TransitiveProject<_, TU, UV>` is
305c3739801SMiguel Ojeda     /// a [`Project`] which projects by applying `TU` followed by `UV`.
306c3739801SMiguel Ojeda     ///
307c3739801SMiguel Ojeda     /// If `TU: Cast` and `UV: Cast`, then `TransitiveProject<_, TU, UV>: Cast`.
308c3739801SMiguel Ojeda     #[allow(missing_debug_implementations)]
309c3739801SMiguel Ojeda     pub struct TransitiveProject<U: ?Sized, TU, UV> {
310c3739801SMiguel Ojeda         _never: core::convert::Infallible,
311c3739801SMiguel Ojeda         _projections: PhantomData<(TU, UV)>,
312c3739801SMiguel Ojeda         // On our MSRV (1.56), the debuginfo for a tuple containing both an
313c3739801SMiguel Ojeda         // uninhabited type and a DST causes an ICE. We split `U` from `TU` and
314c3739801SMiguel Ojeda         // `UV` to avoid this situation.
315c3739801SMiguel Ojeda         _u: PhantomData<U>,
316c3739801SMiguel Ojeda     }
317c3739801SMiguel Ojeda 
318c3739801SMiguel Ojeda     // SAFETY: Since `TU::project` and `UV::project` are each
319c3739801SMiguel Ojeda     // provenance-preserving operations which preserve or shrink the set of
320c3739801SMiguel Ojeda     // referent bytes, so is their composition.
321c3739801SMiguel Ojeda     unsafe impl<T, U, V, TU, UV> Project<T, V> for TransitiveProject<U, TU, UV>
322c3739801SMiguel Ojeda     where
323c3739801SMiguel Ojeda         T: ?Sized,
324c3739801SMiguel Ojeda         U: ?Sized,
325c3739801SMiguel Ojeda         V: ?Sized,
326c3739801SMiguel Ojeda         TU: Project<T, U>,
327c3739801SMiguel Ojeda         UV: Project<U, V>,
328c3739801SMiguel Ojeda     {
329c3739801SMiguel Ojeda         #[inline(always)]
330c3739801SMiguel Ojeda         fn project(t: PtrInner<'_, T>) -> *mut V {
331c3739801SMiguel Ojeda             t.project::<_, TU>().project::<_, UV>().as_ptr()
332c3739801SMiguel Ojeda         }
333c3739801SMiguel Ojeda     }
334c3739801SMiguel Ojeda 
335c3739801SMiguel Ojeda     // SAFETY: Since the `Project::project` impl delegates to `TU::project` and
336c3739801SMiguel Ojeda     // `UV::project`, and since `TU` and `UV` are `Cast`, the `Project::project`
337c3739801SMiguel Ojeda     // impl preserves the address of the referent.
338c3739801SMiguel Ojeda     unsafe impl<T, U, V, TU, UV> Cast<T, V> for TransitiveProject<U, TU, UV>
339c3739801SMiguel Ojeda     where
340c3739801SMiguel Ojeda         T: ?Sized,
341c3739801SMiguel Ojeda         U: ?Sized,
342c3739801SMiguel Ojeda         V: ?Sized,
343c3739801SMiguel Ojeda         TU: Cast<T, U>,
344c3739801SMiguel Ojeda         UV: Cast<U, V>,
345c3739801SMiguel Ojeda     {
346c3739801SMiguel Ojeda     }
347c3739801SMiguel Ojeda 
348c3739801SMiguel Ojeda     // SAFETY: Since the `Project::project` impl delegates to `TU::project` and
349c3739801SMiguel Ojeda     // `UV::project`, and since `TU` and `UV` are `CastExact`, the `Project::project`
350c3739801SMiguel Ojeda     // impl preserves the set of referent bytes.
351c3739801SMiguel Ojeda     unsafe impl<T, U, V, TU, UV> CastExact<T, V> for TransitiveProject<U, TU, UV>
352c3739801SMiguel Ojeda     where
353c3739801SMiguel Ojeda         T: ?Sized,
354c3739801SMiguel Ojeda         U: ?Sized,
355c3739801SMiguel Ojeda         V: ?Sized,
356c3739801SMiguel Ojeda         TU: CastExact<T, U>,
357c3739801SMiguel Ojeda         UV: CastExact<U, V>,
358c3739801SMiguel Ojeda     {
359c3739801SMiguel Ojeda     }
360c3739801SMiguel Ojeda 
361c3739801SMiguel Ojeda     /// A cast from `T` to `[u8]`.
362c3739801SMiguel Ojeda     #[allow(missing_copy_implementations, missing_debug_implementations)]
363c3739801SMiguel Ojeda     pub struct AsBytesCast;
364c3739801SMiguel Ojeda 
365c3739801SMiguel Ojeda     // SAFETY: `project` constructs a pointer with the same address as `src`
366c3739801SMiguel Ojeda     // and with a referent of the same size as `*src`. It does this using
367c3739801SMiguel Ojeda     // provenance-preserving operations.
368c3739801SMiguel Ojeda     //
369c3739801SMiguel Ojeda     // FIXME(https://github.com/rust-lang/unsafe-code-guidelines/issues/594):
370c3739801SMiguel Ojeda     // Technically, this proof assumes that `*src` is contiguous (the same is
371c3739801SMiguel Ojeda     // true of other proofs in this codebase). Is this guaranteed anywhere?
372c3739801SMiguel Ojeda     unsafe impl<T: ?Sized + KnownLayout> Project<T, [u8]> for AsBytesCast {
373c3739801SMiguel Ojeda         #[inline(always)]
374c3739801SMiguel Ojeda         fn project(src: PtrInner<'_, T>) -> *mut [u8] {
375c3739801SMiguel Ojeda             let bytes = match T::size_of_val_raw(src.as_non_null()) {
376c3739801SMiguel Ojeda                 Some(bytes) => bytes,
377c3739801SMiguel Ojeda                 // SAFETY: `KnownLayout::size_of_val_raw` promises to always
378c3739801SMiguel Ojeda                 // return `Some` so long as the resulting size fits in a
379c3739801SMiguel Ojeda                 // `usize`. By invariant on `PtrInner`, `src` refers to a range
380c3739801SMiguel Ojeda                 // of bytes whose size fits in an `isize`, which implies that it
381c3739801SMiguel Ojeda                 // also fits in a `usize`.
382c3739801SMiguel Ojeda                 None => unsafe { core::hint::unreachable_unchecked() },
383c3739801SMiguel Ojeda             };
384c3739801SMiguel Ojeda 
385c3739801SMiguel Ojeda             core::ptr::slice_from_raw_parts_mut(src.as_ptr().cast::<u8>(), bytes)
386c3739801SMiguel Ojeda         }
387c3739801SMiguel Ojeda     }
388c3739801SMiguel Ojeda 
389c3739801SMiguel Ojeda     // SAFETY: The `Project::project` impl preserves referent address.
390c3739801SMiguel Ojeda     unsafe impl<T: ?Sized + KnownLayout> Cast<T, [u8]> for AsBytesCast {}
391c3739801SMiguel Ojeda 
392c3739801SMiguel Ojeda     // SAFETY: The `Project::project` impl preserves the set of referent bytes.
393c3739801SMiguel Ojeda     unsafe impl<T: ?Sized + KnownLayout> CastExact<T, [u8]> for AsBytesCast {}
394c3739801SMiguel Ojeda 
395c3739801SMiguel Ojeda     /// A cast from any type to `()`.
396c3739801SMiguel Ojeda     #[allow(missing_copy_implementations, missing_debug_implementations)]
397c3739801SMiguel Ojeda     pub struct CastToUnit;
398c3739801SMiguel Ojeda 
399c3739801SMiguel Ojeda     // SAFETY: The `project` implementation projects to a subset of its
400c3739801SMiguel Ojeda     // argument's referent using provenance-preserving operations.
401c3739801SMiguel Ojeda     unsafe impl<T: ?Sized> Project<T, ()> for CastToUnit {
402c3739801SMiguel Ojeda         #[inline(always)]
403c3739801SMiguel Ojeda         fn project(src: PtrInner<'_, T>) -> *mut () {
404c3739801SMiguel Ojeda             src.as_ptr().cast::<()>()
405c3739801SMiguel Ojeda         }
406c3739801SMiguel Ojeda     }
407c3739801SMiguel Ojeda 
408c3739801SMiguel Ojeda     // SAFETY: The `project` implementation preserves referent address.
409c3739801SMiguel Ojeda     unsafe impl<T: ?Sized> Cast<T, ()> for CastToUnit {}
410c3739801SMiguel Ojeda }
411