pub trait BytesExt<Ctx> {
// Required methods
fn read_with<'a, T>(&'a self, offset: &mut usize, ctx: Ctx) -> Result<T>
where T: TryRead<'a, Ctx>;
fn read_iter<'a, 'i, T>(
&'a self,
offset: &'i mut usize,
ctx: Ctx
) -> Iter<'a, 'i, T, Ctx> ⓘ
where T: TryRead<'a, Ctx>,
Ctx: Clone;
fn write_with<T>(
&mut self,
offset: &mut usize,
t: T,
ctx: Ctx
) -> Result<()>
where T: TryWrite<Ctx>;
// Provided methods
fn read<'a, T>(&'a self, offset: &mut usize) -> Result<T>
where T: TryRead<'a, Ctx>,
Ctx: Default { ... }
fn write<T>(&mut self, offset: &mut usize, t: T) -> Result<()>
where T: TryWrite<Ctx>,
Ctx: Default { ... }
}
Expand description
Extension methods for byte slices.
§Offset
The offset is the first parameter of each method.
It tells the starting position, and will be increased by the number which will be increased by size the operation consumed.
Required Methods§
sourcefn read_with<'a, T>(&'a self, offset: &mut usize, ctx: Ctx) -> Result<T>where
T: TryRead<'a, Ctx>,
fn read_with<'a, T>(&'a self, offset: &mut usize, ctx: Ctx) -> Result<T>where
T: TryRead<'a, Ctx>,
Reads a value from a byte slice specifying the context.
§Example
use byte::*;
use byte::ctx::*;
let bytes: &[u8] = b"hello, world!";
let str: &str = bytes.read_with(&mut 0, Str::Delimiter(b"!"[0])).unwrap();
assert_eq!(str, "hello, world");
sourcefn read_iter<'a, 'i, T>(
&'a self,
offset: &'i mut usize,
ctx: Ctx
) -> Iter<'a, 'i, T, Ctx> ⓘ
fn read_iter<'a, 'i, T>( &'a self, offset: &'i mut usize, ctx: Ctx ) -> Iter<'a, 'i, T, Ctx> ⓘ
Reads multiple values of the same type using an iterator.
§Example
use byte::*;
use byte::ctx::*;
let bytes: &[u8] = b"hello\0world\0dead\0beef\0more";
let mut offset = 0;
{
let mut iter = bytes.read_iter(&mut offset, Str::Delimiter(NULL));
assert_eq!(iter.next(), Some("hello"));
assert_eq!(iter.next(), Some("world"));
assert_eq!(iter.next(), Some("dead"));
assert_eq!(iter.next(), Some("beef"));
assert_eq!(iter.next(), None);
}
assert_eq!(offset, 22);
sourcefn write_with<T>(&mut self, offset: &mut usize, t: T, ctx: Ctx) -> Result<()>where
T: TryWrite<Ctx>,
fn write_with<T>(&mut self, offset: &mut usize, t: T, ctx: Ctx) -> Result<()>where
T: TryWrite<Ctx>,
Writes a value into a byte slice specifiying the context.
§Example
use byte::*;
use byte::ctx::*;
let mut bytes_be = [0u8; 2];
let mut bytes_le = [0u8; 2];
bytes_be.write_with::<u16>(&mut 0, 0xff, BE).unwrap();
bytes_le.write_with::<u16>(&mut 0, 0xff, LE).unwrap();
assert_eq!(bytes_be, [0, 0xff]);
assert_eq!(bytes_le, [0xff, 0]);
Provided Methods§
sourcefn read<'a, T>(&'a self, offset: &mut usize) -> Result<T>
fn read<'a, T>(&'a self, offset: &mut usize) -> Result<T>
Reads a value from a byte slice using the default context.
§Example
use byte::*;
let bytes: &[u8] = &[0, 1];
let bool1: bool = bytes.read(&mut 0).unwrap();
let bool2: bool = bytes.read(&mut 1).unwrap();
assert_eq!(bool1, false);
assert_eq!(bool2, true);
Object Safety§
This trait is not object safe.