From ff87348e42af6f5c3001628c5cd64a6607622273 Mon Sep 17 00:00:00 2001 From: Joshua Goins Date: Sun, 23 Feb 2025 16:33:25 -0500 Subject: [PATCH] Add writing support for booleans and BoolProperty --- src/bool_property.rs | 50 +++++++++++++++++++++++++++++++++++++------- src/common.rs | 8 +++++++ 2 files changed, 51 insertions(+), 7 deletions(-) diff --git a/src/bool_property.rs b/src/bool_property.rs index 3627563..e6a6682 100644 --- a/src/bool_property.rs +++ b/src/bool_property.rs @@ -1,34 +1,70 @@ -use crate::common::read_bool_from; +use crate::common::{read_bool_from, write_bool_as}; use binrw::binrw; #[binrw] #[derive(Debug)] pub struct BoolProperty { - #[br(pad_before = 8, pad_after = 1)] + #[brw(pad_before = 8, pad_after = 1)] #[br(map = read_bool_from::)] - #[bw(ignore)] + #[bw(map = write_bool_as::)] pub value: bool, } #[cfg(test)] mod tests { use super::*; - use binrw::BinRead; + use binrw::{BinRead, BinWrite}; use std::io::Cursor; #[test] - fn r#false() { + fn read_false() { let data = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; let mut cursor = Cursor::new(data); let decoded = BoolProperty::read_le(&mut cursor).unwrap(); assert!(!decoded.value); } - + #[test] - fn r#true() { + fn write_false() { + let expected_data: [u8; 10] = [ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + ]; + let property = BoolProperty { + value: false + }; + + let mut buffer: Vec = Vec::new(); + { + let mut cursor = Cursor::new(&mut buffer); + property.write_le(&mut cursor).unwrap(); + } + + assert_eq!(expected_data, &buffer[..]); + } + + #[test] + fn read_true() { let data = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00]; let mut cursor = Cursor::new(data); let decoded = BoolProperty::read_le(&mut cursor).unwrap(); assert!(decoded.value); } + + #[test] + fn write_true() { + let expected_data: [u8; 10] = [ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00 + ]; + let property = BoolProperty { + value: true + }; + + let mut buffer: Vec = Vec::new(); + { + let mut cursor = Cursor::new(&mut buffer); + property.write_le(&mut cursor).unwrap(); + } + + assert_eq!(expected_data, &buffer[..]); + } } diff --git a/src/common.rs b/src/common.rs index 86bda9b..3fae8d0 100644 --- a/src/common.rs +++ b/src/common.rs @@ -5,6 +5,14 @@ pub(crate) fn read_bool_from + PartialEq>(x: T) -> bool { x == T::from(1u8) } +pub(crate) fn write_bool_as>(x: &bool) -> T { + if *x { + T::from(1u8) + } else { + T::from(0u8) + } +} + #[binrw::parser(reader, endian)] pub(crate) fn read_string_with_length() -> BinResult { let length = u32::read_le(reader)? as usize;