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§

source

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.

source

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§

source

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.

source

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.

Object Safety§

This trait is not object safe.

Implementations on Foreign Types§

source§

impl LayoutAs<u8> for bool

§

type ReadError = InvalidBoolError

§

type WriteError = Infallible

source§

fn try_read(v: u8) -> Result<Self, Self::ReadError>

source§

fn try_write(v: Self) -> Result<u8, Self::WriteError>

source§

impl LayoutAs<u32> for char

§

type ReadError = InvalidCharError

§

type WriteError = Infallible

source§

fn try_read(v: u32) -> Result<Self, Self::ReadError>

source§

fn try_write(v: Self) -> Result<u32, Self::WriteError>

Implementors§