pub unsafe trait Verify<C: Fallible + ?Sized> {
// Required method
fn verify(&self, context: &mut C) -> Result<(), C::Error>;
}
Expand description
A type that can check whether its invariants are upheld.
When using the derive, adding #[bytecheck(verify)]
allows implementing Verify
for the derived type. Verify::verify
will
be called after the type is checked and all fields are known to be valid.
§Safety
verify
must only returnOk
if all of the invariants of this type are upheld byself
.verify
may not assume that its type invariants are upheld by the givenself
(the invariants of each field are guaranteed to be upheld).
§Example
use core::{error::Error, fmt};
use bytecheck::{CheckBytes, Verify};
use rancor::{fail, Fallible, Source};
#[derive(CheckBytes)]
#[bytecheck(verify)]
#[repr(C, align(4))]
pub struct NonMaxU32(u32);
unsafe impl<C: Fallible + ?Sized> Verify<C> for NonMaxU32
where
C::Error: Source,
{
fn verify(&self, context: &mut C) -> Result<(), C::Error> {
#[derive(Debug)]
struct NonMaxCheckError;
impl fmt::Display for NonMaxCheckError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "non-max u32 was set to u32::MAX")
}
}
impl Error for NonMaxCheckError {}
if self.0 == u32::MAX {
fail!(NonMaxCheckError);
}
Ok(())
}
}