pub fn try_view_ref<S: ?Sized + Pun, D: ?Sized + Pun>(
value: &S,
) -> Result<&D, Error>Expand description
view_ref, when only some values of S are a valid D: what could not be proven of the
value itself is checked at run time, as try_pun_ref does.
What is checked is the value that value refers to, not what it points to: a variant that
D does not have, a scalar that D restricts, a pointer that may be null
(Pointer::or_null) read as one that is not. Behind its pointers nothing is checked, so everything
must be proven there, as for view_ref.
With Rel<T> as in the example of view_ref:
#[derive(Pun)]
#[repr(C)]
struct Loose {
byte: u8,
next: Rel<u8>,
}
#[derive(Pun)]
#[repr(C)]
struct Strict {
flag: bool,
next: Rel<u8>,
}
#[repr(C, align(4))]
struct Buffer([u8; 12]);
/// A `Loose` of `byte` at 0, whose pointer, at 4, aims at a byte at 8.
fn buffer(byte: u8) -> Buffer {
let mut bytes = [byte, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0];
bytes[4..8].copy_from_slice(&4i32.to_ne_bytes());
Buffer(bytes)
}
let (a, b) = (buffer(1), buffer(2));
// SAFETY: the bytes at 0 of each are a `Loose`, whose pointer aims at a byte of the buffer.
let one: &Loose = unsafe { &*core::ptr::from_ref(&a).cast::<Loose>() };
let two: &Loose = unsafe { &*core::ptr::from_ref(&b).cast::<Loose>() };
// The `bool` is checked; what the pointer aims at is proven.
assert!(puns::try_view_ref::<Loose, Strict>(one).unwrap().flag);
assert_eq!(puns::try_view_ref::<Loose, Strict>(two).err(), Some(puns::Error::Validity));What a pointer aims at is not checked: a u8 there is never read as a bool.
ⓘ
#[derive(Pun)]
#[repr(C)]
struct Behind {
byte: u8,
next: Rel<bool>,
}
fn check(loose: &Loose) -> Result<&Behind, puns::Error> {
puns::try_view_ref(loose)
}§Errors
As try_pun_ref: Error::Alignment, Error::Size, Error::Validity.