Trait binary_layout::LayoutAs
source · pub trait LayoutAs<U>: Sized {
type ReadError;
type WriteError;
// Required methods
fn try_read(v: U) -> Result<Self, Self::ReadError>;
fn try_write(v: Self) -> Result<U, Self::WriteError>;
}
Expand description
Implementing the LayoutAs trait for a custom type allows that custom type to be used as the type of a layout field. Note that the value of this type is copied each time it is accessed, so this is only recommended for primitive wrappers of primitive types, not for types that are expensive to copy.
§Example
use binary_layout::{prelude::*, LayoutAs};
use core::convert::Infallible;
struct MyIdType(u64);
impl LayoutAs<u64> for MyIdType {
type ReadError = Infallible;
type WriteError = Infallible;
fn try_read(v: u64) -> Result<MyIdType, Infallible> {
Ok(MyIdType(v))
}
fn try_write(v: MyIdType) -> Result<u64, Infallible> {
Ok(v.0)
}
}
binary_layout!(my_layout, BigEndian, {
// ... other fields ...
field: MyIdType as u64,
// ... other fields ...
});
Required Associated Types§
sourcetype ReadError
type ReadError
See FieldCopyAccess::ReadError.
If reading cannot fail, set this to core::convert::Infallible because that will make FieldReadExt::read available for the type. For any other error type, you will have to use FieldCopyAccess::try_read when reading the field.
sourcetype WriteError
type WriteError
See FieldCopyAccess::WriteError.
If writing cannot fail, set this to core::convert::Infallible because that will make FieldWriteExt::write available for the type. For any other error type, you will have to use FieldCopyAccess::try_write when writing the field.
Required Methods§
sourcefn try_read(v: U) -> Result<Self, Self::ReadError>
fn try_read(v: U) -> Result<Self, Self::ReadError>
Implement this to define how the custom type is constructed from the underlying type after it was read from a layouted binary slice.
sourcefn try_write(v: Self) -> Result<U, Self::WriteError>
fn try_write(v: Self) -> Result<U, Self::WriteError>
Implement this to define how the custom type is converted into the underlying type so it can be written into a layouted binary slice.