Skip to content

Commit

Permalink
Implement BinWrite for PosValue<T>
Browse files Browse the repository at this point in the history
  • Loading branch information
amirbou committed Jun 28, 2024
1 parent c312ad3 commit ad3f80f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
16 changes: 15 additions & 1 deletion 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,
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: std::io::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 ad3f80f

Please sign in to comment.