| 1 | // Copyright (c) 2022 Harry [Majored] [[email protected]] |
| 2 | // MIT License (https://github.com/Majored/rs-async-zip/blob/main/LICENSE) |
| 3 | |
| 4 | use std::pin::Pin; |
| 5 | use std::task::{Context, Poll}; |
| 6 | |
| 7 | use futures_lite::io::{AsyncBufRead, AsyncRead}; |
| 8 | use pin_project::pin_project; |
| 9 | |
| 10 | /// A wrapping reader which holds an owned R or a mutable borrow to R. |
| 11 | /// |
| 12 | /// This is used to represent whether the supplied reader can be acted on concurrently or not (with an owned value |
| 13 | /// suggesting that R implements some method of synchronisation & cloning). |
| 14 | #[pin_project(project = OwnedReaderProj)] |
| 15 | pub(crate) enum OwnedReader<'a, R> { |
| 16 | Owned(#[pin] R), |
| 17 | Borrow(#[pin] &'a mut R), |
| 18 | } |
| 19 | |
| 20 | impl<'a, R> OwnedReader<'a, R> |
| 21 | where |
| 22 | R: AsyncBufRead + Unpin, |
| 23 | { |
| 24 | /// Consumes an owned reader and returns the inner value. |
| 25 | pub(crate) fn owned_into_inner(self) -> R { |
| 26 | match self { |
| 27 | OwnedReader::Owned(inner) => inner, |
| 28 | OwnedReader::Borrow(_) => panic!("not OwnedReader::Owned value"), |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | impl<'a, R> AsyncBufRead for OwnedReader<'a, R> |
| 34 | where |
| 35 | R: AsyncBufRead + Unpin, |
| 36 | { |
| 37 | fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<&[u8]>> { |
| 38 | match self.project() { |
| 39 | OwnedReaderProj::Owned(inner) => inner.poll_fill_buf(cx), |
| 40 | OwnedReaderProj::Borrow(inner) => inner.poll_fill_buf(cx), |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | fn consume(self: Pin<&mut Self>, amt: usize) { |
| 45 | match self.project() { |
| 46 | OwnedReaderProj::Owned(inner) => inner.consume(amt), |
| 47 | OwnedReaderProj::Borrow(inner) => inner.consume(amt), |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | impl<'a, R> AsyncRead for OwnedReader<'a, R> |
| 53 | where |
| 54 | R: AsyncBufRead + Unpin, |
| 55 | { |
| 56 | fn poll_read(self: Pin<&mut Self>, c: &mut Context<'_>, b: &mut [u8]) -> Poll<std::io::Result<usize>> { |
| 57 | match self.project() { |
| 58 | OwnedReaderProj::Owned(inner) => inner.poll_read(c, b), |
| 59 | OwnedReaderProj::Borrow(inner) => inner.poll_read(c, b), |
| 60 | } |
| 61 | } |
| 62 | } |