Skip to content

Commit d8e86d9

Browse files
committed
util: add Collected::to_bytes_mut
1 parent 70ba87f commit d8e86d9

File tree

2 files changed

+28
-5
lines changed

2 files changed

+28
-5
lines changed

http-body-util/src/collected.rs

Lines changed: 18 additions & 1 deletion
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) => {
@@ -125,6 +130,18 @@ mod tests {
125130
assert_eq!(&buf.copy_to_bytes(buf.remaining())[..], b"helloworld!");
126131
}
127132

133+
#[tokio::test]
134+
async fn segmented_body_mut() {
135+
let bufs = [&b"hello"[..], &b"world"[..], &b"!"[..]];
136+
let body = StreamBody::new(stream::iter(bufs.map(Frame::data).map(Ok::<_, Infallible>)));
137+
138+
let buffered = body.collect().await.unwrap();
139+
140+
let mut buf = buffered.to_bytes_mut();
141+
142+
assert_eq!(&buf.copy_to_bytes(buf.remaining())[..], b"helloworld!");
143+
}
144+
128145
#[tokio::test]
129146
async fn delayed_segments() {
130147
let one = stream::once(async { Ok::<_, Infallible>(Frame::data(&b"hello "[..])) });

http-body-util/src/util.rs

Lines changed: 10 additions & 4 deletions
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)