Skip to content

Commit

Permalink
Add impl Encode for [T], where T: Encode
Browse files Browse the repository at this point in the history
Since Encode takes a reference, this allows us to encode &[T] directly
using this implementation. The encoding scheme is the same as for
Vec<T>.

This also makes the implementation for &[u8] superfluous, since we get
an implementation for [u8] by virtue of u8 implementing encode. This
also gives us free implementations for &[u16], &[u32], etc. which is
quite useful. Nonetheless, we keep the implementation for &[u8] around,
because the implementation can directly write a large number of bytes,
which can be more efficient than the generic implementation.
  • Loading branch information
cronokirby committed May 24, 2022
1 parent 6ec69a3 commit 51456e2
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/enc/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,19 @@ impl Encode for &'_ [u8] {
}
}

impl<T> Encode for [T]
where
T: Encode,
{
fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
super::encode_slice_len(encoder, self.len())?;
for item in self {
item.encode(encoder)?;
}
Ok(())
}
}

const TAG_CONT: u8 = 0b1000_0000;
const TAG_TWO_B: u8 = 0b1100_0000;
const TAG_THREE_B: u8 = 0b1110_0000;
Expand Down

0 comments on commit 51456e2

Please sign in to comment.