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
87
88
89
90
91
92
93
94
95
use super::{Constraints, BodyAsyncBytesStreamer};

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

use hyper::body::HttpBody;
use http::header::{HeaderMap, HeaderValue};

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 HttpBody for BodyHttp {
	type Data = Bytes;
	type Error = io::Error;

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

	fn poll_trailers(
		self: Pin<&mut Self>,
		_cx: &mut Context
	) -> Poll<io::Result<Option<HeaderMap<HeaderValue>>>> {
		Poll::Ready(Ok(None))
	}
}


pub(super) struct HyperBodyAsAsyncBytesStream {
	inner: hyper::Body
}

impl HyperBodyAsAsyncBytesStream {
	pub fn new(inner: hyper::Body) -> 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_data(cx) {
				Poll::Ready(Some(Ok(data))) => {
					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
		}
	}
}