Skip to content

Commit

Permalink
Add example many for testing
Browse files Browse the repository at this point in the history
  • Loading branch information
wcampbell0x2a committed Aug 4, 2023
1 parent 27f1983 commit 2c51884
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 13 deletions.
30 changes: 30 additions & 0 deletions examples/many.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use deku::{bitvec::BitView, container, ctx::Limit, prelude::*, DekuRead, DekuWrite};
use std::io::Write;

#[derive(Debug, DekuRead, DekuWrite)]
struct Test {
pub a: u64,
pub b: u64,
pub c: u64,
}

fn main() {
let input: Vec<_> = (0..10_0000)
.map(|i| Test {
a: i,
b: i + 1,
c: i + 2,
})
.collect();
let custom: Vec<u8> = input
.iter()
.flat_map(|x| x.to_bytes().unwrap().into_iter())
.collect();
let mut container = Container::new(std::io::Cursor::new(custom.clone()));
let ret = <Vec<Test> as DekuRead<Limit<_, _>>>::from_reader(
&mut container,
Limit::new_count(10_0000),
);

println!("{:?}", ret);
}
26 changes: 13 additions & 13 deletions src/impls/vec.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::io::Read;

#[cfg(feature = "alloc")]
use alloc::vec::Vec;

Expand Down Expand Up @@ -148,19 +150,6 @@ where
}
}

/// Read `T`s until the given limit
/// * `limit` - the limiting factor on the amount of `T`s to read
/// * `inner_ctx` - The context required by `T`. It will be passed to every `T`s when constructing.
/// # Examples
/// ```rust
/// # use deku::ctx::*;
/// # use deku::DekuRead;
/// # use deku::bitvec::BitView;
/// let input = vec![1u8, 2, 3, 4];
/// let (amt_read, v) = Vec::<u32>::read(input.view_bits(), (1.into(), Endian::Little)).unwrap();
/// assert_eq!(amt_read, 32);
/// assert_eq!(vec![0x04030201], v)
/// ```
fn from_reader<R: std::io::Read>(
container: &mut crate::container::Container<R>,
(limit, inner_ctx): (Limit<T, Predicate>, Ctx),
Expand Down Expand Up @@ -222,6 +211,17 @@ impl<'a, T: DekuRead<'a>, Predicate: FnMut(&T) -> bool> DekuRead<'a, Limit<T, Pr
{
Vec::read(input, (limit, ()))
}

/// Read `T`s until the given limit from input for types which don't require context.
fn from_reader<R: Read>(
container: &mut crate::container::Container<R>,
limit: Limit<T, Predicate>,
) -> Result<Self, DekuError>
where
Self: Sized,
{
Vec::from_reader(container, (limit, ()))
}
}

impl<T: DekuWrite<Ctx>, Ctx: Copy> DekuWrite<Ctx> for Vec<T> {
Expand Down

0 comments on commit 2c51884

Please sign in to comment.