Skip to content

Commit 1940cd5

Browse files
committed
Add native-endian methods to BinWrite API
Refs #326.
1 parent 741c3ee commit 1940cd5

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

binrw/src/binwrite/mod.rs

+28
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,19 @@ pub trait BinWrite {
8686
self.write_le_args(writer, Self::Args::args())
8787
}
8888

89+
/// Write `Self` to the writer assuming native-endian byte order.
90+
///
91+
/// # Errors
92+
///
93+
/// If writing fails, an [`Error`](crate::Error) variant will be returned.
94+
#[inline]
95+
fn write_ne<W: Write + Seek>(&self, writer: &mut W) -> BinResult<()>
96+
where
97+
for<'a> Self::Args<'a>: Required,
98+
{
99+
self.write_ne_args(writer, Self::Args::args())
100+
}
101+
89102
/// Write `Self` to the writer using the given arguments.
90103
///
91104
/// # Errors
@@ -129,6 +142,21 @@ pub trait BinWrite {
129142
self.write_options(writer, Endian::Little, args)
130143
}
131144

145+
/// Write `Self` to the writer, assuming native-endian byte order, using the
146+
/// given arguments.
147+
///
148+
/// # Errors
149+
///
150+
/// If reading fails, an [`Error`](crate::Error) variant will be returned.
151+
#[inline]
152+
fn write_ne_args<W: Write + Seek>(
153+
&self,
154+
writer: &mut W,
155+
args: Self::Args<'_>,
156+
) -> BinResult<()> {
157+
self.write_options(writer, Endian::NATIVE, args)
158+
}
159+
132160
/// Write `Self` to the writer using the given [`Endian`] and
133161
/// arguments.
134162
///

binrw/tests/binwrite_impls.rs

+24
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,30 @@ fn non_zero() {
7575
);
7676
}
7777

78+
#[test]
79+
fn native_endian() {
80+
#[derive(BinWrite)]
81+
struct Test(u16);
82+
83+
#[derive(BinWrite)]
84+
#[bw(import(mul: u16))]
85+
struct TestArgs(#[bw(map = |val| mul * *val)] u16);
86+
87+
let mut output = binrw::io::Cursor::new(vec![]);
88+
Test(1).write_ne(&mut output).unwrap();
89+
#[cfg(target_endian = "big")]
90+
assert_eq!(output.into_inner(), b"\0\x01");
91+
#[cfg(target_endian = "little")]
92+
assert_eq!(output.into_inner(), b"\x01\0");
93+
94+
let mut output = binrw::io::Cursor::new(vec![]);
95+
TestArgs(2).write_ne_args(&mut output, (2,)).unwrap();
96+
#[cfg(target_endian = "big")]
97+
assert_eq!(output.into_inner(), b"\0\x04");
98+
#[cfg(target_endian = "little")]
99+
assert_eq!(output.into_inner(), b"\x04\0");
100+
}
101+
78102
#[test]
79103
fn option() {
80104
compare!(Some(1_i32), Endian::Big, b"\0\0\0\x01");

0 commit comments

Comments
 (0)