|
1 | 1 | use wasi::http::types::{IncomingBody as WasiIncomingBody, IncomingResponse};
|
2 |
| -use wasi::io::streams::{InputStream, StreamError}; |
3 | 2 |
|
4 | 3 | use super::{fields::header_map_from_wasi, Body, Error, HeaderMap, Result, StatusCode};
|
5 |
| -use crate::io::AsyncRead; |
6 |
| -use crate::runtime::Reactor; |
7 |
| - |
8 |
| -/// Stream 2kb chunks at a time |
9 |
| -const CHUNK_SIZE: u64 = 2048; |
| 4 | +use crate::io::{AsyncInputStream, AsyncRead}; |
10 | 5 |
|
11 | 6 | /// An HTTP response
|
12 | 7 | #[derive(Debug)]
|
@@ -57,9 +52,7 @@ impl Response<IncomingBody> {
|
57 | 52 |
|
58 | 53 | let body = IncomingBody {
|
59 | 54 | kind,
|
60 |
| - buf_offset: 0, |
61 |
| - buf: None, |
62 |
| - body_stream, |
| 55 | + body_stream: AsyncInputStream::new(body_stream), |
63 | 56 | _incoming_body: incoming_body,
|
64 | 57 | };
|
65 | 58 |
|
@@ -96,54 +89,15 @@ impl<B: Body> Response<B> {
|
96 | 89 | #[derive(Debug)]
|
97 | 90 | pub struct IncomingBody {
|
98 | 91 | kind: BodyKind,
|
99 |
| - buf: Option<Vec<u8>>, |
100 |
| - // How many bytes have we already read from the buf? |
101 |
| - buf_offset: usize, |
102 |
| - |
103 | 92 | // IMPORTANT: the order of these fields here matters. `body_stream` must
|
104 | 93 | // be dropped before `_incoming_body`.
|
105 |
| - body_stream: InputStream, |
| 94 | + body_stream: AsyncInputStream, |
106 | 95 | _incoming_body: WasiIncomingBody,
|
107 | 96 | }
|
108 | 97 |
|
109 | 98 | impl AsyncRead for IncomingBody {
|
110 | 99 | async fn read(&mut self, out_buf: &mut [u8]) -> crate::io::Result<usize> {
|
111 |
| - let buf = match &mut self.buf { |
112 |
| - Some(ref mut buf) => buf, |
113 |
| - None => { |
114 |
| - // Wait for an event to be ready |
115 |
| - let pollable = self.body_stream.subscribe(); |
116 |
| - Reactor::current().wait_for(pollable).await; |
117 |
| - |
118 |
| - // Read the bytes from the body stream |
119 |
| - let buf = match self.body_stream.read(CHUNK_SIZE) { |
120 |
| - Ok(buf) => buf, |
121 |
| - Err(StreamError::Closed) => return Ok(0), |
122 |
| - Err(StreamError::LastOperationFailed(err)) => { |
123 |
| - return Err(std::io::Error::other(format!( |
124 |
| - "last operation failed: {}", |
125 |
| - err.to_debug_string() |
126 |
| - ))) |
127 |
| - } |
128 |
| - }; |
129 |
| - self.buf.insert(buf) |
130 |
| - } |
131 |
| - }; |
132 |
| - |
133 |
| - // copy bytes |
134 |
| - let len = (buf.len() - self.buf_offset).min(out_buf.len()); |
135 |
| - let max = self.buf_offset + len; |
136 |
| - let slice = &buf[self.buf_offset..max]; |
137 |
| - out_buf[0..len].copy_from_slice(slice); |
138 |
| - self.buf_offset += len; |
139 |
| - |
140 |
| - // reset the local slice if necessary |
141 |
| - if self.buf_offset == buf.len() { |
142 |
| - self.buf = None; |
143 |
| - self.buf_offset = 0; |
144 |
| - } |
145 |
| - |
146 |
| - Ok(len) |
| 100 | + self.body_stream.read(out_buf).await |
147 | 101 | }
|
148 | 102 | }
|
149 | 103 |
|
|
0 commit comments