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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
use futures::io::{BufReader, Cursor}; use futures::task::{Context, Poll}; use futures::{AsyncBufRead as BufRead, AsyncRead as Read, Stream}; use std::io::Error; use std::pin::Pin; pub struct Body { counter: usize, segments: Vec<Segment>, } pub type Segment = Box<dyn BufRead + Sync + Send + Unpin + 'static>; impl Body { pub fn new() -> Self { Self { counter: 0, segments: Vec::new(), } } pub fn write_buf( &mut self, buf_reader: impl BufRead + Sync + Send + Unpin + 'static, ) -> &mut Self { self.segments.push(Box::new(buf_reader)); self } pub fn write(&mut self, reader: impl Read + Sync + Send + Unpin + 'static) -> &mut Self { self.write_buf(BufReader::new(reader)) } pub fn write_bytes(&mut self, bytes: impl Into<Vec<u8>>) -> &mut Self { self.write_buf(Cursor::new(bytes.into())) } pub fn write_str(&mut self, data: impl ToString) -> &mut Self { self.write_bytes(data.to_string()) } pub fn stream(self) -> BodyStream<Self> { BodyStream::new(self) } pub fn poll_segment(&mut self, cx: &mut Context<'_>) -> Poll<Result<&[u8], Error>> { Pin::new(self.segments[self.counter].as_mut()).poll_fill_buf(cx) } } impl Default for Body { fn default() -> Self { Self::new() } } impl BufRead for Body { fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<&[u8], Error>> { let mut_ref = self.get_mut(); loop { if mut_ref.counter >= mut_ref.segments.len() { break Poll::Ready(Ok(b"".as_ref())); } let buf = futures::ready!(mut_ref.poll_segment(cx))?; let buf_ptr = buf as *const [u8]; if !buf.is_empty() { break Poll::Ready(Ok(unsafe { &*buf_ptr })); } mut_ref.counter += 1; } } fn consume(self: Pin<&mut Self>, amt: usize) { let self_mut = self.get_mut(); if self_mut.counter < self_mut.segments.len() { Pin::new(self_mut.segments[self_mut.counter].as_mut()).consume(amt) } } } impl Read for Body { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<Result<usize, Error>> { let data: &[u8] = futures::ready!(self.as_mut().poll_fill_buf(cx))?; let nums = std::cmp::min(data.len(), buf.len()); buf[0..nums].copy_from_slice(&data[0..nums]); self.consume(nums); Poll::Ready(Ok(nums)) } } pub struct BodyStream<R: BufRead> { body: R, } impl<R: BufRead> BodyStream<R> { pub fn new(body: R) -> Self { Self { body } } } impl<R: BufRead + Unpin> Stream for BodyStream<R> { type Item = Result<Vec<u8>, std::io::Error>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let buf: &[u8] = futures::ready!(Pin::new(&mut self.body).poll_fill_buf(cx))?; let buf_len = buf.len(); if buf_len == 0 { Poll::Ready(None) } else { let data = buf.to_vec(); Pin::new(&mut self.body).consume(buf_len); Poll::Ready(Some(Ok(data))) } } } impl<R: BufRead + Unpin + Send + Sync + 'static> From<BodyStream<R>> for hyper::Body { fn from(stream: BodyStream<R>) -> Self { hyper::Body::wrap_stream(stream) } } #[cfg(test)] mod tests { use super::Body; use async_std::fs::File; use futures::AsyncReadExt; #[tokio::test] async fn body_empty() -> std::io::Result<()> { let mut body = Body::new(); let mut data = String::new(); body.read_to_string(&mut data).await?; assert_eq!("", data); Ok(()) } #[tokio::test] async fn body_single() -> std::io::Result<()> { let mut body = Body::new(); let mut data = String::new(); body.write_buf(b"Hello, World".as_ref()) .read_to_string(&mut data) .await?; println!("{}", &data); assert_eq!("Hello, World", data); Ok(()) } #[tokio::test] async fn body_multiple() -> std::io::Result<()> { let mut body = Body::new(); let mut data = String::new(); body.write_buf(b"He".as_ref()) .write_buf(b"llo, ".as_ref()) .write_buf(b"World".as_ref()) .read_to_string(&mut data) .await?; assert_eq!("Hello, World", data); Ok(()) } #[tokio::test] async fn body_composed() -> std::io::Result<()> { let mut body = Body::new(); let mut data = String::new(); body.write_buf(b"He".as_ref()) .write_buf(b"llo, ".as_ref()) .write(File::open("../assets/author.txt").await?) .write_buf(b".".as_ref()) .read_to_string(&mut data) .await?; assert_eq!("Hello, Hexilee.", data); Ok(()) } #[tokio::test] async fn response_write_str() -> std::io::Result<()> { let mut body = Body::new(); let mut data = String::new(); body.write_str("Hello, World") .read_to_string(&mut data) .await?; assert_eq!("Hello, World", data); Ok(()) } }