Trait byte::TryWrite [] [src]

pub trait TryWrite<Ctx = ()> {
    fn try_write(self, bytes: &mut [u8], ctx: Ctx) -> Result<usize>;
}

A data structure that can be serialized. Types implement this trait can be write() into byte slice.

Required Methods

Try to write to bytes using context.

Write the value into bytes; the passed-in bytes is implicitly splitted by offset and should be write at head. If success, try_write() should return the number of bytes it consumed.

Example

use byte::*;

// Demo type showing how to write boolean into bytes.
// This functionality is already provided by this crate.
pub struct Bool(bool);

impl TryWrite for Bool {
    #[inline]
    fn try_write(self, bytes: &mut [u8], _ctx: ()) -> Result<usize> {
        check_len(bytes, 1)?;

        bytes[0] = if self.0 { u8::max_value() } else { 0 };

        Ok(1)
    }
}

Error

If try_write() returns Error::BadOffset, it will be translated into Error::Incomplete. See byte::Error documentation for details.

Implementors