diff --git a/binrw/src/pos_value.rs b/binrw/src/pos_value.rs index 299c64ed..619489c7 100644 --- a/binrw/src/pos_value.rs +++ b/binrw/src/pos_value.rs @@ -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 /// @@ -46,6 +47,19 @@ impl BinRead for PosValue { } } +impl BinWrite for PosValue { + type Args<'a> = T::Args<'a>; + + fn write_options( + &self, + writer: &mut W, + endian: Endian, + args: Self::Args<'_>, + ) -> BinResult<()> { + self.val.write_options(writer, endian, args) + } +} + impl core::ops::Deref for PosValue { type Target = T; diff --git a/binrw/tests/pos_value.rs b/binrw/tests/pos_value.rs index 9125b478..e8caa6d6 100644 --- a/binrw/tests/pos_value.rs +++ b/binrw/tests/pos_value.rs @@ -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, } - let mut val = Cursor::new(b"\xFF\xFE\xFD").read_be::().unwrap(); + let mut val: MyType = Cursor::new(b"\xFF\xFE\xFD").read_be::().unwrap(); assert_eq!(val.a, 0xFFFE); assert_eq!(val.b.pos, 2); assert_eq!(*val.b, 0xFD); @@ -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"); }