From 51456e218f0bfb890d8c250d281e87fce42b6a23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=BAc=C3=A1s=20Cr=C3=ADost=C3=B3ir=20Meier?= Date: Mon, 9 May 2022 20:46:58 +0200 Subject: [PATCH] Add impl Encode for [T], where T: Encode Since Encode takes a reference, this allows us to encode &[T] directly using this implementation. The encoding scheme is the same as for Vec. 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. --- src/enc/impls.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/enc/impls.rs b/src/enc/impls.rs index 0f061acd..3d4cfc9f 100644 --- a/src/enc/impls.rs +++ b/src/enc/impls.rs @@ -290,6 +290,19 @@ impl Encode for &'_ [u8] { } } +impl Encode for [T] +where + T: Encode, +{ + fn encode(&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;