Skip to content

Commit

Permalink
Add a fixed signed writer to endianness trait
Browse files Browse the repository at this point in the history
This eliminates another runtime check in favor
of something that can be evaluated at compile-time.
  • Loading branch information
tuffy committed Jun 14, 2024
1 parent be2db77 commit bdeedfd
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
36 changes: 36 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,12 @@ pub trait Endianness: Sized {
W: BitWrite,
S: SignedNumeric;

/// Writes signed value to writer in this endianness
fn write_signed_fixed<W, const B: u32, S>(w: &mut W, value: S) -> io::Result<()>
where
W: BitWrite,
S: SignedNumeric;

/// Reads convertable numeric value from reader in this endianness
fn read_primitive<R, V>(r: &mut R) -> io::Result<V>
where
Expand Down Expand Up @@ -518,6 +524,21 @@ impl Endianness for BigEndian {
}
}

fn write_signed_fixed<W, const B: u32, S>(w: &mut W, value: S) -> io::Result<()>
where
W: BitWrite,
S: SignedNumeric,
{
if B == S::BITS_SIZE {
w.write_bytes(value.to_be_bytes().as_ref())
} else if value.is_negative() {
w.write_bit(true)
.and_then(|()| w.write(B - 1, value.as_unsigned(B)))
} else {
w.write_bit(false).and_then(|()| w.write(B - 1, value))
}
}

#[inline]
fn read_primitive<R, V>(r: &mut R) -> io::Result<V>
where
Expand Down Expand Up @@ -685,6 +706,21 @@ impl Endianness for LittleEndian {
}
}

fn write_signed_fixed<W, const B: u32, S>(w: &mut W, value: S) -> io::Result<()>
where
W: BitWrite,
S: SignedNumeric,
{
if B == S::BITS_SIZE {
w.write_bytes(value.to_le_bytes().as_ref())
} else if value.is_negative() {
w.write(B - 1, value.as_unsigned(B))
.and_then(|()| w.write_bit(true))
} else {
w.write(B - 1, value).and_then(|()| w.write_bit(false))
}
}

#[inline]
fn read_primitive<R, V>(r: &mut R) -> io::Result<V>
where
Expand Down
4 changes: 2 additions & 2 deletions src/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -775,7 +775,7 @@ impl<W: io::Write, E: Endianness> BitWrite for BitWriter<W, E> {
const {
assert!(BITS <= S::BITS_SIZE, "excessive bits for type written");
}
E::write_signed(self, BITS, value)
E::write_signed_fixed::<_, BITS, S>(self, value)
}

#[inline]
Expand Down Expand Up @@ -956,7 +956,7 @@ where
const {
assert!(BITS <= S::BITS_SIZE, "excessive bits for type written");
}
E::write_signed(self, BITS, value)
E::write_signed_fixed::<_, BITS, S>(self, value)
}

#[inline]
Expand Down

0 comments on commit bdeedfd

Please sign in to comment.