Skip to content

Commit

Permalink
Implement BinWrite for PosValue<T>
Browse files Browse the repository at this point in the history
Fixes #270. Closes #273.

Signed-off-by: Colin Snover <[email protected]>
  • Loading branch information
amirbou authored and csnover committed Nov 27, 2024
1 parent 453e2c5 commit cd53cdf
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
18 changes: 16 additions & 2 deletions binrw/src/pos_value.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use crate::{
io::{Read, Seek},
BinRead, BinResult, Endian,
io::{Read, Seek, Write},
BinRead, BinResult, BinWrite, Endian,
};
use core::fmt;

/// A wrapper that stores a value’s position alongside the value.
/// Serializing a `PosValue` will ignore the `pos` field.
///
/// # Examples
///
Expand Down Expand Up @@ -46,6 +47,19 @@ impl<T: BinRead> BinRead for PosValue<T> {
}
}

impl<T: BinWrite> BinWrite for PosValue<T> {
type Args<'a> = T::Args<'a>;

fn write_options<W: Write + Seek>(
&self,
writer: &mut W,
endian: Endian,
args: Self::Args<'_>,
) -> BinResult<()> {
self.val.write_options(writer, endian, args)
}
}

impl<T> core::ops::Deref for PosValue<T> {
type Target = T;

Expand Down
11 changes: 8 additions & 3 deletions binrw/tests/pos_value.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
extern crate alloc;

use alloc::format;
use binrw::{io::Cursor, BinRead, BinReaderExt, PosValue};
use binrw::{io::Cursor, BinRead, BinReaderExt, BinWrite, PosValue};

#[test]
fn pos_value() {
#[derive(BinRead)]
#[derive(BinRead, BinWrite)]
struct MyType {
a: u16,
b: PosValue<u8>,
}

let mut val = Cursor::new(b"\xFF\xFE\xFD").read_be::<MyType>().unwrap();
let mut val: MyType = Cursor::new(b"\xFF\xFE\xFD").read_be::<MyType>().unwrap();
assert_eq!(val.a, 0xFFFE);
assert_eq!(val.b.pos, 2);
assert_eq!(*val.b, 0xFD);
Expand All @@ -23,4 +23,9 @@ fn pos_value() {
let clone = val.b.clone();
assert_eq!(*clone, *val.b);
assert_eq!(clone.pos, val.b.pos);

let mut output = Vec::new();
val.write_be(&mut Cursor::new(&mut output)).unwrap();

assert_eq!(output, b"\xFF\xFE\x01");
}

0 comments on commit cd53cdf

Please sign in to comment.