Skip to content

Commit

Permalink
Add deku_input example
Browse files Browse the repository at this point in the history
  • Loading branch information
wcampbell0x2a committed Oct 13, 2023
1 parent db94946 commit bb9ff20
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ let ec = EcHdr::from_reader((&mut file, 0)).unwrap();
```

- The more internal (with context) `read(..)` was replaced with `from_reader_with_ctx(..)`.
Now unused variables `deku::input`, `deku::input_bits`, and `deku::rest` were removed. `deku::reader` is the replacement.
With the switch to internal streaming, the variables `deku::input`, `deku::input_bits`, and `deku::rest` are now not possible and were removed.
`deku::reader` is a replacement for some of the functionality.
See [examples/deku_input.rs](examples/deku_input.rs) for a new example of caching all reads.

old:
```rust
Expand Down
43 changes: 43 additions & 0 deletions examples/deku_input.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
//! Example of a close replacement for deku::input
use deku::prelude::*;
use std::io::{self, Cursor, Read};

/// Every read to this struct will be saved into an internal cache. This is to keep the cache
/// around for the crc without reading from the buffer twice
struct ReaderCrc<R: Read> {
reader: R,
pub cache: Vec<u8>,
}

impl<R: Read> ReaderCrc<R> {
pub fn new(reader: R) -> Self {
Self {
reader,
cache: vec![],
}
}
}

impl<R: Read> Read for ReaderCrc<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let n = self.reader.read(buf);
self.cache.extend_from_slice(buf);
n
}
}

#[derive(Debug, DekuRead)]
pub struct DekuStruct {
pub a: u8,
pub b: u8,
}

fn main() {
let data = vec![0x01, 0x02];
let input = Cursor::new(&data);
let mut reader = ReaderCrc::new(input);
let (_, s) = DekuStruct::from_reader((&mut reader, 0)).unwrap();
assert_eq!(reader.cache, data);
assert_eq!(s.a, 1);
assert_eq!(s.b, 2);
}

0 comments on commit bb9ff20

Please sign in to comment.