Skip to content

Commit

Permalink
Implement FromZeroes for thin raw pointers
Browse files Browse the repository at this point in the history
Makes progress on #170
  • Loading branch information
joshlf committed Aug 29, 2023
1 parent 1ede214 commit 06a411b
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -945,6 +945,35 @@ safety_comment! {
unsafe_impl!(T: ?Sized + Unaligned => Unaligned for ManuallyDrop<T>);
assert_unaligned!(ManuallyDrop<()>, ManuallyDrop<u8>);
}
safety_comment! {
/// SAFETY:
/// The all-zeroes const and mut raw pointers are valid (see e.g.
/// `ptr::null` [1] and `ptr::null_mut` [2]). Unlike non-null pointers, it
/// is always unsound to dereference null pointers, and so it's not a
/// footgun that converting from zeroes may not preserve pointer provenance
/// information.
///
/// Since the encoding of fat pointers is not currently defined by the
/// reference, it would not be sound to implement `FromZeroes` for fat
/// pointer types such `*const T` for `T: ?Sized` or even for more
/// constrained pointer types such as `*const [T]` for `T: Sized`.
///
/// Currently, though it would likely be sound, we choose not to implement
/// `FromBytes` or `AsBytes` for raw pointers because it would be easy for
/// code to mistakenly assume that converting from a raw pointer to a
/// different representation (such as a byte array) and back again via
/// `FromBytes` and `AsBytes` would result in a semantically identical
/// pointer. Thanks to provenance information, that may not actually be
/// true, so this would present a serious footgun. Note that this aspect of
/// Rust's memory model is still up in the air, so it's possible that these
/// conversions will one day be determined to be sound, at which point we
/// could choose to support these impls. See #170 for more information.
///
/// [1] https://doc.rust-lang.org/core/ptr/fn.null.html
/// [2] https://doc.rust-lang.org/core/ptr/fn.null_mut.html
unsafe_impl!(T: Sized => FromZeroes for *const T);
unsafe_impl!(T: Sized => FromZeroes for *mut T);
}
safety_comment! {
/// SAFETY:
/// Per the reference [1]:
Expand Down Expand Up @@ -3983,6 +4012,9 @@ mod tests {
assert_impls!(Unalign<u8>: FromZeroes, FromBytes, AsBytes, Unaligned);
assert_impls!(Unalign<NotZerocopy>: Unaligned, !FromZeroes, !FromBytes, !AsBytes);

assert_impls!(*const NotZerocopy: FromZeroes, !FromBytes, !AsBytes, !Unaligned);
assert_impls!(*mut NotZerocopy: FromZeroes, !FromBytes, !AsBytes, !Unaligned);

assert_impls!([u8]: FromZeroes, FromBytes, AsBytes, Unaligned);
assert_impls!([NotZerocopy]: !FromZeroes, !FromBytes, !AsBytes, !Unaligned);
assert_impls!([u8; 0]: FromZeroes, FromBytes, AsBytes, Unaligned);
Expand Down

0 comments on commit 06a411b

Please sign in to comment.