Trait bytecheck::CheckBytes
source · 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§
Object Safety§
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 AtomicBool
Available on target_has_atomic="8"
only.
impl<C> CheckBytes<C> for AtomicBool
Available on
target_has_atomic="8"
only.