1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use super::{BodyAsyncBytesStreamer, Constraints};

use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};

use hyper::body::{Body as HyperBody, Frame, Incoming};

use futures_core::Stream;

use pin_project_lite::pin_project;

use bytes::Bytes;

pin_project! {
	pub struct BodyHttp {
		#[pin]
		inner: BodyAsyncBytesStreamer
	}
}

impl BodyHttp {
	pub(super) fn new(inner: super::Inner, constraints: Constraints) -> Self {
		Self {
			inner: BodyAsyncBytesStreamer::new(inner, constraints),
		}
	}
}

impl HyperBody for BodyHttp {
	type Data = Bytes;
	type Error = io::Error;

	fn poll_frame(
		self: Pin<&mut Self>,
		cx: &mut Context,
	) -> Poll<Option<io::Result<Frame<Bytes>>>> {
		let me = self.project();
		match me.inner.poll_next(cx) {
			Poll::Ready(Some(Ok(b))) => Poll::Ready(Some(Ok(Frame::data(b)))),
			Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(e))),
			Poll::Ready(None) => Poll::Ready(None),
			Poll::Pending => Poll::Pending,
		}
	}
}

pub(super) struct HyperBodyAsAsyncBytesStream {
	inner: Incoming,
}

impl HyperBodyAsAsyncBytesStream {
	pub fn new(inner: Incoming) -> Self {
		Self { inner }
	}
}

impl Stream for HyperBodyAsAsyncBytesStream {
	type Item = io::Result<Bytes>;

	fn poll_next(
		self: Pin<&mut Self>,
		cx: &mut Context,
	) -> Poll<Option<io::Result<Bytes>>> {
		let me = self.get_mut();
		// loop to retry to get data
		loop {
			let r = match Pin::new(&mut me.inner).poll_frame(cx) {
				Poll::Ready(Some(Ok(frame))) => {
					let Ok(data) = frame.into_data() else {
						continue;
					};

					Poll::Ready(Some(Ok(data)))
				}
				Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(
					io::Error::new(io::ErrorKind::Other, e),
				))),
				Poll::Ready(None) => Poll::Ready(None),
				Poll::Pending => Poll::Pending,
			};

			break r;
		}
	}
}