Skip to content
This repository has been archived by the owner on Jul 29, 2024. It is now read-only.

Commit

Permalink
Codec: add codec for [T; N] type.
Browse files Browse the repository at this point in the history
Signed-off-by: xiaoyuxlu <[email protected]>
  • Loading branch information
xiaoyuxlu committed Sep 7, 2023
1 parent 22b0e1f commit 46c35f2
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions codec/src/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,20 @@ impl Codec for u128 {
}
}

impl<T: Codec + Copy, const N: usize> Codec for [T; N] {
fn encode(&self, bytes: &mut Writer) -> Result<usize, EncodeErr> {
let used = bytes.used();
for d in self.as_ref() {
let _ = d.encode(bytes)?;
}
Ok(bytes.used() - used)
}

fn read(reader: &mut Reader) -> Option<Self> {
Some([T::read(reader)?; N])
}
}

#[cfg(test)]
mod tests {
use crate::codec::Codec;
Expand Down Expand Up @@ -399,4 +413,14 @@ mod tests {
};
assert_eq!(reader.sub(4).is_none(), true);
}

#[test]
fn test_case0_array() {
let u8_slice = &mut [0x0u8; 2];
let value = [0x5au8; 2];
let writer = &mut Writer::init(u8_slice);
value.encode(writer).unwrap();
let reader = &mut Reader::init(u8_slice);
assert_eq!(value, <[u8; 2]>::read(reader).unwrap());
}
}

0 comments on commit 46c35f2

Please sign in to comment.