Skip to content

Commit

Permalink
encode Int with a single byte when possible
Browse files Browse the repository at this point in the history
  • Loading branch information
noib3 committed Jan 24, 2024
1 parent b5f2f4a commit 17f1c92
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,16 @@ macro_rules! impl_int_encode {
impl Encode for Int<$ty> {
#[inline]
fn encode(&self, buf: &mut Vec<u8>) {
let array = self.0.to_le_bytes();
let int = self.0;

// We can encode the entire integer with a single byte if it
// falls within this range.
if int == 0 || (int > 8 && int <= u8::MAX as $ty) {
buf.push(int as u8);
return;
}

let array = int.to_le_bytes();

let num_trailing_zeros = array
.iter()
Expand Down Expand Up @@ -121,6 +130,11 @@ macro_rules! impl_int_decode {
let (&len, buf) =
buf.split_first().ok_or(IntDecodeError::EmptyBuffer)?;

if len == 0 || len > 8 {
let int = len as $ty;
return Ok((int, buf));
}

if len as usize > buf.len() {
return Err(IntDecodeError::LengthLessThanPrefix {
prefix: len,
Expand Down

0 comments on commit 17f1c92

Please sign in to comment.