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

Commit

Permalink
Codec: introduce alloc feature for vec encode/read
Browse files Browse the repository at this point in the history
This feature is disabled by default.

Signed-off-by: xiaoyuxlu <[email protected]>
  • Loading branch information
xiaoyuxlu committed Sep 7, 2023
1 parent 46c35f2 commit bade3ea
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
4 changes: 4 additions & 0 deletions codec/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,7 @@ edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

[features]
default = []
alloc = []
31 changes: 31 additions & 0 deletions codec/src/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
//
// SPDX-License-Identifier: Apache-2.0

#[cfg(feature = "alloc")]
extern crate alloc;

use core::{fmt::Debug, mem};

/// Read from a byte slice.
Expand Down Expand Up @@ -134,6 +137,34 @@ pub trait Codec: Debug + Sized {
let mut rd = Reader::init(bytes);
Self::read(&mut rd)
}

#[cfg(feature = "alloc")]
/// Read count T's and returns Vec<T>
/// count: the number of T wants to read.
fn read_vec<T: Codec>(reader: &mut Reader, count: usize) -> Option<alloc::vec::Vec<T>> {
let mut data = alloc::vec::Vec::new();
for _ in 0..count {
let t = T::read(reader)?;
data.push(t)
}
Some(data)
}
}

#[cfg(feature = "alloc")]
impl<T: Codec + Copy> Codec for alloc::vec::Vec<T> {
fn encode(&self, bytes: &mut Writer) -> Result<usize, EncodeErr> {
let used = bytes.used();
for t in self.iter() {
let _ = t.encode(bytes)?;
}
Ok(bytes.used() - used)
}

fn read(_reader: &mut Reader) -> Option<Self> {
// Not support can't known the length
panic!("Should not call this API for reading vec. Use read_vec instead.")
}
}

// Encoding functions.
Expand Down

0 comments on commit bade3ea

Please sign in to comment.