Skip to content

Commit

Permalink
feat(core): Implement FromIterator for Buffer (#4459)
Browse files Browse the repository at this point in the history
* feat(core): Implement FromIterator for Buffer

Signed-off-by: Xuanwo <[email protected]>

* Format code

Signed-off-by: Xuanwo <[email protected]>

---------

Signed-off-by: Xuanwo <[email protected]>
  • Loading branch information
Xuanwo authored Apr 10, 2024
1 parent 42a42f3 commit 0891924
Showing 1 changed file with 24 additions and 3 deletions.
27 changes: 24 additions & 3 deletions core/src/types/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,15 @@ impl From<Bytes> for Buffer {
}
}

impl FromIterator<u8> for Buffer {
fn from_iter<T: IntoIterator<Item = u8>>(iter: T) -> Self {
Self(Inner::Contiguous(Bytes::from_iter(iter)))
}
}

impl From<VecDeque<Bytes>> for Buffer {
fn from(bs: VecDeque<Bytes>) -> Self {
let size = bs.iter().map(|b| b.len()).sum();
let size = bs.iter().map(Bytes::len).sum();
Self(Inner::NonContiguous {
parts: Vec::from(bs).into(),
size,
Expand All @@ -120,7 +126,7 @@ impl From<VecDeque<Bytes>> for Buffer {

impl From<Vec<Bytes>> for Buffer {
fn from(bs: Vec<Bytes>) -> Self {
let size = bs.iter().map(|b| b.len()).sum();
let size = bs.iter().map(Bytes::len).sum();
Self(Inner::NonContiguous {
parts: bs.into(),
size,
Expand All @@ -132,7 +138,7 @@ impl From<Vec<Bytes>> for Buffer {

impl From<Arc<[Bytes]>> for Buffer {
fn from(bs: Arc<[Bytes]>) -> Self {
let size = bs.iter().map(|b| b.len()).sum();
let size = bs.iter().map(Bytes::len).sum();
Self(Inner::NonContiguous {
parts: bs,
size,
Expand All @@ -142,6 +148,21 @@ impl From<Arc<[Bytes]>> for Buffer {
}
}

impl FromIterator<Bytes> for Buffer {
fn from_iter<T: IntoIterator<Item = Bytes>>(iter: T) -> Self {
let mut size = 0;
let bs = iter.into_iter().inspect(|v| size += v.len());
// Use `Arc::from_iter` here to make sure we can benefit from `TrustedLen` if provided.
let parts = Arc::from_iter(bs);
Self(Inner::NonContiguous {
parts,
size,
idx: 0,
offset: 0,
})
}
}

impl Buf for Buffer {
#[inline]
fn remaining(&self) -> usize {
Expand Down

0 comments on commit 0891924

Please sign in to comment.