You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opendal.apache.org by xu...@apache.org on 2024/04/10 08:53:37 UTC

(opendal) 01/01: feat(core): Implement FromIterator for Buffer

This is an automated email from the ASF dual-hosted git repository.

xuanwo pushed a commit to branch accept-into-interator
in repository https://gitbox.apache.org/repos/asf/opendal.git

commit 222b6ab66d147d356deeabc289e75553396b3721
Author: Xuanwo <gi...@xuanwo.io>
AuthorDate: Wed Apr 10 16:53:14 2024 +0800

    feat(core): Implement FromIterator for Buffer
    
    Signed-off-by: Xuanwo <gi...@xuanwo.io>
---
 core/src/types/buffer.rs | 28 +++++++++++++++++++++++++---
 1 file changed, 25 insertions(+), 3 deletions(-)

diff --git a/core/src/types/buffer.rs b/core/src/types/buffer.rs
index 803eb7414b..72d025d537 100644
--- a/core/src/types/buffer.rs
+++ b/core/src/types/buffer.rs
@@ -94,6 +94,7 @@ impl Buffer {
     }
 }
 
+
 impl From<Vec<u8>> for Buffer {
     fn from(bs: Vec<u8>) -> Self {
         Self(Inner::Contiguous(bs.into()))
@@ -106,9 +107,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,
@@ -120,7 +127,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,
@@ -132,7 +139,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,
@@ -142,6 +149,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 {