pub unsafe trait CheckBytes<C: Fallible + ?Sized> {
// Required method
unsafe fn check_bytes(
value: *const Self,
context: &mut C,
) -> Result<(), C::Error>;
}Expand description
A type that can check whether a pointer points to a valid value.
CheckBytes can be derived with CheckBytes or
implemented manually for custom behavior.
§Safety
check_bytes must only return Ok if value points to a valid instance of
Self. Because value must always be properly aligned for Self and point
to enough bytes to represent the type, this implies that value may be
dereferenced safely.
§Example
use core::{error::Error, fmt};
use bytecheck::CheckBytes;
use rancor::{fail, Fallible, Source};
#[repr(C, align(4))]
pub struct NonMaxU32(u32);
unsafe impl<C: Fallible + ?Sized> CheckBytes<C> for NonMaxU32
where
C::Error: Source,
{
unsafe fn check_bytes(
value: *const 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 {}
let value = unsafe { value.read() };
if value.0 == u32::MAX {
fail!(NonMaxCheckError);
}
Ok(())
}
}See Verify for an example which uses less unsafe.
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.
Implementations on Foreign Types§
Source§impl<C> CheckBytes<C> for bool
impl<C> CheckBytes<C> for bool
Source§impl<C> CheckBytes<C> for char
impl<C> CheckBytes<C> for char
Source§impl<C> CheckBytes<C> for str
impl<C> CheckBytes<C> for str
Source§impl<C> CheckBytes<C> for CStr
impl<C> CheckBytes<C> for CStr
Source§impl<C> CheckBytes<C> for NonZeroI8
impl<C> CheckBytes<C> for NonZeroI8
Source§impl<C> CheckBytes<C> for NonZeroI16
impl<C> CheckBytes<C> for NonZeroI16
Source§impl<C> CheckBytes<C> for NonZeroI32
impl<C> CheckBytes<C> for NonZeroI32
Source§impl<C> CheckBytes<C> for NonZeroI64
impl<C> CheckBytes<C> for NonZeroI64
Source§impl<C> CheckBytes<C> for NonZeroI128
impl<C> CheckBytes<C> for NonZeroI128
Source§impl<C> CheckBytes<C> for NonZeroU8
impl<C> CheckBytes<C> for NonZeroU8
Source§impl<C> CheckBytes<C> for NonZeroU16
impl<C> CheckBytes<C> for NonZeroU16
Source§impl<C> CheckBytes<C> for NonZeroU32
impl<C> CheckBytes<C> for NonZeroU32
Source§impl<C> CheckBytes<C> for NonZeroU64
impl<C> CheckBytes<C> for NonZeroU64
Source§impl<C> CheckBytes<C> for NonZeroU128
impl<C> CheckBytes<C> for NonZeroU128
Source§impl<C> CheckBytes<C> for AtomicBool
Available on target_has_atomic=8 only.
impl<C> CheckBytes<C> for AtomicBool
Available on
target_has_atomic=8 only.