Trait scroll::Cread [] [src]

pub trait Cread<Ctx, I = usize>: Index<I> + Index<RangeFrom<I>> where
    Ctx: Copy
{ fn cread_with<'a, N: FromCtx<Ctx, Self::Output>>(
        &'a self,
        offset: I,
        ctx: Ctx
    ) -> N { ... }
fn cread<'a, N: FromCtx<Ctx, Self::Output>>(&'a self, offset: I) -> N
    where
        Ctx: Default
, { ... } }

Core-read - core, no_std friendly trait for reading basic traits from byte buffers. Cannot fail unless the buffer is too small, in which case an assert fires and the program panics.

If your type implements FromCtx then you can cread::<YourType>(offset).

Example

use scroll::{ctx, Cread, LE};

#[repr(packed)]
struct Bar {
    foo: i32,
    bar: u32,
}

impl ctx::FromCtx<scroll::Endian> for Bar {
    fn from_ctx(bytes: &[u8], ctx: scroll::Endian) -> Self {
        use scroll::Cread;
        Bar { foo: bytes.cread_with(0, ctx), bar: bytes.cread_with(4, ctx) }
    }
}

let bytes = [0xff, 0xff, 0xff, 0xff, 0xef,0xbe,0xad,0xde,];
let bar = bytes.cread_with::<Bar>(0, LE);
assert_eq!(bar.foo, -1);
assert_eq!(bar.bar, 0xdeadbeef);

Provided Methods

Reads a value from Self at offset with ctx. Cannot fail. If the buffer is too small for the value requested, this will panic.

Example

use scroll::{Cread, BE, LE};
use std::i64::MAX;

let bytes = [0x7f,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xef,0xbe,0xad,0xde,];
let foo = bytes.cread_with::<i64>(0, BE);
let bar = bytes.cread_with::<u32>(8, LE);
assert_eq!(foo, MAX);
assert_eq!(bar, 0xdeadbeef);

Reads a value implementing FromCtx from Self at offset, with the target machine's endianness. For the primitive types, this will be the target machine's endianness.

Example

use scroll::Cread;

let bytes = [0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0xef,0xbe,0x00,0x00,];
let foo = bytes.cread::<i64>(0);
let bar = bytes.cread::<u32>(8);
#[cfg(target_endian = "little")]
assert_eq!(foo, 1);
#[cfg(target_endian = "big")]
assert_eq!(foo, 0x100_0000_0000_0000);

#[cfg(target_endian = "little")]
assert_eq!(bar, 0xbeef);
#[cfg(target_endian = "big")]
assert_eq!(bar, 0xefbe0000);

Implementors