Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit cc8f131

Browse files
committedFeb 8, 2024
util: add Collected::to_bytes_mut
1 parent 70ba87f commit cc8f131

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed
 

‎http-body-util/src/collected.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use std::{
44
task::{Context, Poll},
55
};
66

7-
use bytes::{Buf, Bytes};
7+
use bytes::{Buf, Bytes, BytesMut};
88
use http::HeaderMap;
99
use http_body::{Body, Frame};
1010

@@ -38,6 +38,11 @@ impl<B: Buf> Collected<B> {
3838
self.bufs.copy_to_bytes(self.bufs.remaining())
3939
}
4040

41+
/// Convert this body into a [`BytesMut`].
42+
pub fn to_bytes_mut(mut self) -> BytesMut {
43+
self.bufs.copy_to_bytes_mut(self.bufs.remaining())
44+
}
45+
4146
pub(crate) fn push_frame(&mut self, frame: Frame<B>) {
4247
let frame = match frame.into_data() {
4348
Ok(data) => {

‎http-body-util/src/util.rs

+10-4
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,14 @@ impl<T: Buf> BufList<T> {
1919
pub(crate) fn pop(&mut self) -> Option<T> {
2020
self.bufs.pop_front()
2121
}
22+
23+
#[inline]
24+
pub(crate) fn copy_to_bytes_mut(&mut self, len: usize) -> BytesMut {
25+
assert!(len <= self.remaining(), "`len` greater than remaining");
26+
let mut bm = BytesMut::with_capacity(len);
27+
bm.put(self.take(len));
28+
bm
29+
}
2230
}
2331

2432
impl<T: Buf> Buf for BufList<T> {
@@ -77,10 +85,8 @@ impl<T: Buf> Buf for BufList<T> {
7785
}
7886
Some(front) if front.remaining() > len => front.copy_to_bytes(len),
7987
_ => {
80-
assert!(len <= self.remaining(), "`len` greater than remaining");
81-
let mut bm = BytesMut::with_capacity(len);
82-
bm.put(self.take(len));
83-
bm.freeze()
88+
let bytes_mut = self.copy_to_bytes_mut(len);
89+
bytes_mut.freeze()
8490
}
8591
}
8692
}

0 commit comments

Comments
 (0)
Please sign in to comment.