Skip to content

Commit 98afbb5

Browse files
committed
Add MaybeValid type
`MaybeValid<T>` is a `T` which might not be valid. It is similar to `MaybeUninit<T>`, but it is slightly more strict: any byte in `T` which is guaranteed to be initialized is also guaranteed to be initialized in `MaybeValid<T>` (see the doc comment for a more precise definition). `MaybeValid` is a building block of the `TryFromBytes` design outlined in #5. Makes progress on #5
1 parent d5f7888 commit 98afbb5

File tree

1 file changed

+322
-0
lines changed

1 file changed

+322
-0
lines changed

src/lib.rs

Lines changed: 322 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1824,6 +1824,237 @@ safety_comment! {
18241824
assert_unaligned!(mem::MaybeUninit<()>, MaybeUninit<u8>);
18251825
}
18261826

1827+
/// A value which might or might not constitute a valid instance of `T`.
1828+
///
1829+
/// `MaybeValid<T>` has the same layout (size and alignment) and field offsets
1830+
/// as `T`. Unlike `T`, it may contain any bit pattern, except that
1831+
/// uninitialized bytes may only appear in `MaybeValid<T>` at byte offsets where
1832+
/// they may appear in `T`. This is a dynamic property: if, at a particular byte
1833+
/// offset, a valid enum discriminant is set, the subsequent bytes may only have
1834+
/// uninitialized bytes as specified by the corresponding enum variant.
1835+
///
1836+
/// Formally, given `m: MaybeValid<T>` and a byte offset, `b` in the range `[0,
1837+
/// size_of_val(m))`:
1838+
/// - If, in all valid instances `t: T`, the byte at offset `b` in `t` is
1839+
/// initialized, then the byte at offset `b` within `m` is guaranteed to be
1840+
/// initialized.
1841+
/// - Let `c` be the contents of the byte range `[0, b)` in `m`. Let `TT` be the
1842+
/// subset of valid instances of `T` which contain `c` in the offset range
1843+
/// `[0, b)`. If, for all instances of `t: T` in `TT`, the byte at offset `b`
1844+
/// in `t` is initialized, then the byte at offset `b` in `m` is guaranteed to
1845+
/// be initialized.
1846+
///
1847+
/// Pragmatically, this means that if `m` is guaranteed to contain an enum
1848+
/// type at a particular offset, and the enum discriminant stored in `m`
1849+
/// corresponds to a valid variant of that enum type, then it is guaranteed
1850+
/// that the appropriate bytes of `m` are initialized as defined by that
1851+
/// variant's bit validity (although note that the variant may contain another
1852+
/// enum type, in which case the same rules apply depending on the state of
1853+
/// its discriminant, and so on recursively).
1854+
///
1855+
/// # Safety
1856+
///
1857+
/// Unsafe code may assume that an instance of `MaybeValid` satisfies the
1858+
/// constraints described above. Unsafe code may produce a `MaybeValid` or
1859+
/// modify the bytes of an existing `MaybeValid` so long as these constraints
1860+
/// are upheld. It is unsound to produce a `MaybeValid` which fails to uphold
1861+
/// these constraints.
1862+
#[repr(transparent)]
1863+
pub struct MaybeValid<T: AsMaybeUninit + ?Sized> {
1864+
inner: MaybeUninit<T>,
1865+
}
1866+
1867+
safety_comment! {
1868+
/// SAFETY:
1869+
/// - `AsBytes`: `MaybeValid` requires that, if a byte in `T` is always
1870+
/// initialized, the equivalent byte in `MaybeValid<T>` must be
1871+
/// initialized. `T: AsBytes` implies that all bytes in `T` must always be
1872+
/// initialized, and so all bytes in `MaybeValid<T>` must always be
1873+
/// initialized, and so `MaybeValid<T>` satisfies `AsBytes`. `T: AsBytes`
1874+
/// implies that `[T]: AsBytes`, so this holds is a sufficient bound for
1875+
/// `MaybeValid<[T]>` too.
1876+
/// - `Unaligned`: `MaybeValid<T>` and `MaybeValid<[T]>` have the same
1877+
/// alignment as `T`.
1878+
///
1879+
/// TODO(#5): Implement `FromZeroes` and `FromBytes` for `MaybeValid<T>` and
1880+
/// `MaybeValid<[T]>`.
1881+
unsafe_impl!(T: AsBytes => AsBytes for MaybeValid<T>);
1882+
unsafe_impl!(T: AsBytes => AsBytes for MaybeValid<[T]>);
1883+
unsafe_impl!(T: Unaligned => Unaligned for MaybeValid<T>);
1884+
unsafe_impl!(T: Unaligned => Unaligned for MaybeValid<[T]>);
1885+
}
1886+
1887+
unsafe_impl_known_layout!(T => #[repr([T])] MaybeValid<[T]>);
1888+
1889+
// SAFETY: See safety comment on `MaybeUninit`.
1890+
unsafe impl<T> AsMaybeUninit for MaybeValid<[T]> {
1891+
// SAFETY:
1892+
// - `MaybeUninit` has no bit validity requirements and `[U]` has the same
1893+
// bit validity requirements as `U`, so `[MaybeUninit<T>]` has no bit
1894+
// validity requirements. Thus, it is sound to write uninitialized bytes
1895+
// at every offset.
1896+
// - `MaybeValid<U>` is `repr(transparent)`, and thus has the same layout
1897+
// and field offsets as its contained field of type `U::MaybeUninit`. In
1898+
// this case, `U = [T]`, and so `U::MaybeUninit = [MaybeUninit<T>]`. Thus,
1899+
// `MaybeValid<[T]>` has the same layout and field offsets as
1900+
// `[MaybeUninit<T>]`, which is what we set `MaybeUninit` to here. Thus,
1901+
// they trivially have the same alignment.
1902+
// - By the same token, their raw pointer types are trivially `as` castable
1903+
// and preserve size.
1904+
// - By the same token, `[MaybeUninit<T>]` contains `UnsafeCell`s at the
1905+
// same byte ranges as `MaybeValid<[T]>` does.
1906+
type MaybeUninit = [MaybeUninit<T>];
1907+
1908+
// SAFETY: `as` preserves pointer address and provenance.
1909+
#[allow(clippy::as_conversions)]
1910+
fn raw_from_maybe_uninit(maybe_uninit: *const [MaybeUninit<T>]) -> *const MaybeValid<[T]> {
1911+
maybe_uninit as *const MaybeValid<[T]>
1912+
}
1913+
1914+
// SAFETY: `as` preserves pointer address and provenance.
1915+
#[allow(clippy::as_conversions)]
1916+
fn raw_mut_from_maybe_uninit(maybe_uninit: *mut [MaybeUninit<T>]) -> *mut MaybeValid<[T]> {
1917+
maybe_uninit as *mut MaybeValid<[T]>
1918+
}
1919+
1920+
// SAFETY: `as` preserves pointer address and provenance.
1921+
#[allow(clippy::as_conversions)]
1922+
fn raw_maybe_uninit_from(s: *const MaybeValid<[T]>) -> *const [MaybeUninit<T>] {
1923+
s as *const [MaybeUninit<T>]
1924+
}
1925+
}
1926+
1927+
impl<T> Default for MaybeValid<T> {
1928+
fn default() -> MaybeValid<T> {
1929+
// SAFETY: All of the bytes of `inner` are initialized to 0, and so the
1930+
// safety invariant on `MaybeValid` is upheld.
1931+
MaybeValid { inner: MaybeUninit::zeroed() }
1932+
}
1933+
}
1934+
1935+
impl<T: AsMaybeUninit + ?Sized> MaybeValid<T> {
1936+
/// Converts this `&MaybeValid<T>` to a `&T`.
1937+
///
1938+
/// # Safety
1939+
///
1940+
/// `self` must contain a valid `T`.
1941+
pub unsafe fn assume_valid_ref(&self) -> &T {
1942+
// SAFETY: The caller has promised that `self` contains a valid `T`.
1943+
// Since `Self` is `repr(transparent)`, it has the same layout as
1944+
// `MaybeUninit<T>`, which in turn is guaranteed to have the same layout
1945+
// as `T`. Thus, it is sound to treat `self.inner` as containing a valid
1946+
// `T`.
1947+
unsafe { self.inner.assume_init_ref() }
1948+
}
1949+
1950+
/// Converts this `&mut MaybeValid<T>` to a `&mut T`.
1951+
///
1952+
/// # Safety
1953+
///
1954+
/// `self` must contain a valid `T`.
1955+
pub unsafe fn assume_valid_mut(&mut self) -> &mut T {
1956+
// SAFETY: The caller has promised that `self` contains a valid `T`.
1957+
// Since `Self` is `repr(transparent)`, it has the same layout as
1958+
// `MaybeUninit<T>`, which in turn is guaranteed to have the same layout
1959+
// as `T`. Thus, it is sound to treat `self.inner` as containing a valid
1960+
// `T`.
1961+
unsafe { self.inner.assume_init_mut() }
1962+
}
1963+
1964+
/// Gets a view of this `&T` as a `&MaybeValid<T>`.
1965+
///
1966+
/// There is no mutable equivalent to this function, as producing a `&mut
1967+
/// MaybeValid<T>` from a `&mut T` would allow safe code to write invalid
1968+
/// values which would be accessible through `&mut T`.
1969+
pub fn from_ref(r: &T) -> &MaybeValid<T> {
1970+
let m: *const MaybeUninit<T> = MaybeUninit::from_ref(r);
1971+
#[allow(clippy::as_conversions)]
1972+
let ptr = m as *const MaybeValid<T>;
1973+
// SAFETY: Since `Self` is `repr(transparent)`, it has the same layout
1974+
// as `MaybeUninit<T>`, so the size and alignment here are valid.
1975+
//
1976+
// `MaybeValid<T>`'s bit validity constraints are weaker than those of
1977+
// `T`, so this is guaranteed not to produce an invalid `MaybeValid<T>`.
1978+
// If it were possible to write a different value for `MaybeValid<T>`
1979+
// through the returned reference, it could result in an invalid value
1980+
// being exposed via the `&T`. Luckily, the only way for mutation to
1981+
// happen is if `T` contains an `UnsafeCell` and the caller uses it to
1982+
// perform interior mutation. Importantly, `T` containing an
1983+
// `UnsafeCell` does not permit interior mutation through
1984+
// `MaybeValid<T>`, so it doesn't permit writing uninitialized or
1985+
// otherwise invalid values which would be visible through the original
1986+
// `&T`.
1987+
unsafe { &*ptr }
1988+
}
1989+
}
1990+
1991+
impl<T> MaybeValid<T> {
1992+
/// Converts this `MaybeValid<T>` to a `T`.
1993+
///
1994+
/// # Safety
1995+
///
1996+
/// `self` must contain a valid `T`.
1997+
pub const unsafe fn assume_valid(self) -> T {
1998+
// SAFETY: The caller has promised that `self` contains a valid `T`.
1999+
// Since `Self` is `repr(transparent)`, it has the same layout as
2000+
// `MaybeUninit<T>`, which in turn is guaranteed to have the same layout
2001+
// as `T`. Thus, it is sound to treat `self.inner` as containing a valid
2002+
// `T`.
2003+
unsafe { self.inner.assume_init() }
2004+
}
2005+
}
2006+
2007+
impl<T> MaybeValid<[T]> {
2008+
/// Converts a `MaybeValid<[T]>` to a `[MaybeValid<T>]`.
2009+
///
2010+
/// `MaybeValid<T>` has the same layout as `T`, so these layouts are
2011+
/// equivalent.
2012+
pub const fn as_slice_of_maybe_valids(&self) -> &[MaybeValid<T>] {
2013+
let inner: &[<T as AsMaybeUninit>::MaybeUninit] = &self.inner.inner;
2014+
let inner_ptr: *const [<T as AsMaybeUninit>::MaybeUninit] = inner;
2015+
// Note: this Clippy warning is only emitted on our MSRV (1.61), but not
2016+
// on later versions of Clippy. Thus, we consider it spurious.
2017+
#[allow(clippy::as_conversions)]
2018+
let ret_ptr = inner_ptr as *const [MaybeValid<T>];
2019+
// SAFETY: Since `inner` is a `&[MaybeUninit<T>]`, and `MaybeValid<T>`
2020+
// is a `repr(transparent)` struct around `MaybeUninit<T>`, `inner` has
2021+
// the same layout as `&[MaybeValid<T>]`.
2022+
unsafe { &*ret_ptr }
2023+
}
2024+
}
2025+
2026+
impl<const N: usize, T> MaybeValid<[T; N]> {
2027+
/// Converts a `MaybeValid<[T; N]>` to a `MaybeValid<[T]>`.
2028+
// TODO(#64): Make this `const` once our MSRV is >= 1.64.0 (when
2029+
// `slice_from_raw_parts` was stabilized as `const`).
2030+
pub fn as_slice(&self) -> &MaybeValid<[T]> {
2031+
let base: *const MaybeValid<[T; N]> = self;
2032+
let slice_of_t: *const [T] = ptr::slice_from_raw_parts(base.cast::<T>(), N);
2033+
// Note: this Clippy warning is only emitted on our MSRV (1.61), but not
2034+
// on later versions of Clippy. Thus, we consider it spurious.
2035+
#[allow(clippy::as_conversions)]
2036+
let mv_of_slice = slice_of_t as *const MaybeValid<[T]>;
2037+
// SAFETY: `MaybeValid<T>` is a `repr(transparent)` wrapper around
2038+
// `MaybeUninit<T>`, which in turn has the same layout as `T`. Thus, the
2039+
// trailing slices of `[T]` and of `MaybeValid<[T]>` both have element
2040+
// type `T`. Since the number of elements is preserved during an `as`
2041+
// cast of slice/DST pointers, the resulting `*const MaybeValid<[T]>`
2042+
// has the same number of elements - and thus the same length - as the
2043+
// original `*const [T]`.
2044+
//
2045+
// Thanks to their layouts, `MaybeValid<[T; N]>` and `MaybeValid<[T]>`
2046+
// have the same alignment, so `mv_of_slice` is guaranteed to be
2047+
// aligned.
2048+
unsafe { &*mv_of_slice }
2049+
}
2050+
}
2051+
2052+
impl<T> Debug for MaybeValid<T> {
2053+
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
2054+
f.pad(core::any::type_name::<Self>())
2055+
}
2056+
}
2057+
18272058
/// A type with no alignment requirement.
18282059
///
18292060
/// An `Unalign` wraps a `T`, removing any alignment requirement. `Unalign<T>`
@@ -3782,6 +4013,91 @@ mod tests {
37824013
assert_eq!(unsafe { m.assume_init_ref() }, &Cell::new(2));
37834014
}
37844015

4016+
#[test]
4017+
fn test_maybe_valid() {
4018+
let m = MaybeValid::<usize>::default();
4019+
// SAFETY: all bit patterns are valid `usize`s, and `m` is initialized.
4020+
let u = unsafe { m.assume_valid() };
4021+
// This ensures that Miri can see whether `u` (and thus `m`) has been
4022+
// properly initialized.
4023+
assert_eq!(u, u);
4024+
4025+
fn bytes_to_maybe_valid(bytes: &mut [u8]) -> &mut MaybeValid<[u8]> {
4026+
// SAFETY: `MaybeValid<[u8]>` has the same layout as `[u8]`, and
4027+
// `bytes` is initialized.
4028+
unsafe {
4029+
#[allow(clippy::as_conversions)]
4030+
let m = &mut *(bytes as *mut [u8] as *mut MaybeValid<[u8]>);
4031+
m
4032+
}
4033+
}
4034+
4035+
let mut bytes = [0u8, 1, 2];
4036+
let m = bytes_to_maybe_valid(&mut bytes[..]);
4037+
4038+
// SAFETY: `m` was created from a valid `[u8]`.
4039+
let r = unsafe { m.assume_valid_ref() };
4040+
assert_eq!(r.len(), 3);
4041+
assert_eq!(r, [0, 1, 2]);
4042+
4043+
// SAFETY: `m` was created from a valid `[u8]`.
4044+
let r = unsafe { m.assume_valid_mut() };
4045+
assert_eq!(r.len(), 3);
4046+
assert_eq!(r, [0, 1, 2]);
4047+
4048+
r[0] = 1;
4049+
assert_eq!(bytes, [1, 1, 2]);
4050+
4051+
let mut bytes = [0u8, 1, 2];
4052+
let m = bytes_to_maybe_valid(&mut bytes[..]);
4053+
let slc = m.as_slice_of_maybe_valids();
4054+
assert_eq!(slc.len(), 3);
4055+
for i in 0u8..3 {
4056+
// SAFETY: `m` was created from a valid `[u8]`.
4057+
let u = unsafe { slc[usize::from(i)].assume_valid_ref() };
4058+
assert_eq!(u, &i);
4059+
}
4060+
}
4061+
4062+
#[test]
4063+
fn test_maybe_valid_as_slice() {
4064+
let mut m = MaybeValid::<[u8; 3]>::default();
4065+
// SAFETY: all bit patterns are valid `[u8; 3]`s, and `m` is
4066+
// initialized.
4067+
unsafe { *m.assume_valid_mut() = [0, 1, 2] };
4068+
4069+
let slc = m.as_slice().as_slice_of_maybe_valids();
4070+
assert_eq!(slc.len(), 3);
4071+
4072+
for i in 0u8..3 {
4073+
// SAFETY: `m` was initialized as a valid `[u8; 3]`.
4074+
let u = unsafe { slc[usize::from(i)].assume_valid_ref() };
4075+
assert_eq!(u, &i);
4076+
}
4077+
}
4078+
4079+
#[test]
4080+
fn test_maybe_valid_from_ref() {
4081+
use core::cell::Cell;
4082+
4083+
let u = 1usize;
4084+
let m = MaybeValid::from_ref(&u);
4085+
// SAFETY: `m` was constructed from a valid `&usize`.
4086+
assert_eq!(unsafe { m.assume_valid_ref() }, &1usize);
4087+
4088+
// Test that interior mutability doesn't affect correctness or
4089+
// soundness.
4090+
4091+
let c = Cell::new(1usize);
4092+
let m = MaybeValid::from_ref(&c);
4093+
// SAFETY: `m` was constructed from a valid `&usize`.
4094+
assert_eq!(unsafe { m.assume_valid_ref() }, &Cell::new(1));
4095+
4096+
c.set(2);
4097+
// SAFETY: `m` was constructed from a valid `&usize`.
4098+
assert_eq!(unsafe { m.assume_valid_ref() }, &Cell::new(2));
4099+
}
4100+
37854101
#[test]
37864102
fn test_unalign() {
37874103
// Test methods that don't depend on alignment.
@@ -4717,6 +5033,12 @@ mod tests {
47175033
assert_impls!(MaybeUninit<NotZerocopy>: !FromZeroes, !FromBytes, !AsBytes, !Unaligned);
47185034
assert_impls!(MaybeUninit<MaybeUninit<NotZerocopy>>: !FromZeroes, !FromBytes, !AsBytes, !Unaligned);
47195035

5036+
assert_impls!(MaybeValid<u8>: Unaligned, AsBytes, !FromZeroes, !FromBytes);
5037+
assert_impls!(MaybeValid<MaybeValid<u8>>: Unaligned, AsBytes, !FromZeroes, !FromBytes);
5038+
assert_impls!(MaybeValid<[u8]>: Unaligned, AsBytes, !FromZeroes, !FromBytes);
5039+
assert_impls!(MaybeValid<NotZerocopy>: !FromZeroes, !FromBytes, !AsBytes, !Unaligned);
5040+
assert_impls!(MaybeValid<MaybeValid<NotZerocopy>>: !FromZeroes, !FromBytes, !AsBytes, !Unaligned);
5041+
47205042
assert_impls!(Wrapping<u8>: FromZeroes, FromBytes, AsBytes, Unaligned);
47215043
assert_impls!(Wrapping<NotZerocopy>: !FromZeroes, !FromBytes, !AsBytes, !Unaligned);
47225044

0 commit comments

Comments
 (0)