Skip to content

Commit 19d7c3a

Browse files
committed
Removed unnecessary intermediate Vec<Bytes> allocation in HTTP request body preparation
- Removed unnecessary intermediate `Vec<Bytes>` allocation in HTTP request body preparation - Directly consume `SegmentedBytes` iterator into stream using `Arc::unwrap_or_clone()` - Implemented zero-cost `BodyIterator` enum to avoid heap allocation and dynamic dispatch - Reduces memory overhead and eliminates Vec growth reallocations during request preparation
1 parent 1ee21b7 commit 19d7c3a

File tree

1 file changed

+32
-7
lines changed

1 file changed

+32
-7
lines changed

src/s3/client.rs

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,24 @@ pub const MAX_PART_SIZE: u64 = 5_368_709_120; // 5 GiB
115115
/// ensuring the object does not exceed 5 TiB.
116116
pub const MAX_OBJECT_SIZE: u64 = 5_497_558_138_880; // 5 TiB
117117

118+
enum BodyIterator {
119+
Segmented(crate::s3::segmented_bytes::SegmentedBytesIntoIterator),
120+
FromVec(std::vec::IntoIter<Bytes>),
121+
Empty(std::iter::Empty<Bytes>),
122+
}
123+
124+
impl Iterator for BodyIterator {
125+
type Item = Bytes;
126+
127+
fn next(&mut self) -> Option<Self::Item> {
128+
match self {
129+
Self::Segmented(iter) => iter.next(),
130+
Self::FromVec(iter) => iter.next(),
131+
Self::Empty(iter) => iter.next(),
132+
}
133+
}
134+
}
135+
118136
/// Maximum number of parts allowed in a multipart upload.
119137
///
120138
/// Multipart uploads are limited to a total of 10,000 parts. If the object
@@ -521,14 +539,21 @@ impl MinioClient {
521539
}
522540

523541
if (*method == Method::PUT) || (*method == Method::POST) {
524-
//TODO: why-oh-why first collect into a vector and then iterate to a stream?
525-
let bytes_vec: Vec<Bytes> = match body {
526-
Some(v) => v.iter().collect(),
527-
None => Vec::new(),
542+
let iter = match body {
543+
Some(v) => {
544+
// Try to unwrap the Arc if we're the sole owner (zero-cost).
545+
// Otherwise, collect into a Vec to avoid cloning the SegmentedBytes structure.
546+
match Arc::try_unwrap(v) {
547+
Ok(segmented) => BodyIterator::Segmented(segmented.into_iter()),
548+
Err(arc) => {
549+
let vec: Vec<Bytes> = arc.iter().collect();
550+
BodyIterator::FromVec(vec.into_iter())
551+
}
552+
}
553+
}
554+
None => BodyIterator::Empty(std::iter::empty()),
528555
};
529-
let stream = futures_util::stream::iter(
530-
bytes_vec.into_iter().map(|b| -> Result<_, Error> { Ok(b) }),
531-
);
556+
let stream = futures_util::stream::iter(iter.map(|b| -> Result<_, Error> { Ok(b) }));
532557
req = req.body(Body::wrap_stream(stream));
533558
}
534559

0 commit comments

Comments
 (0)