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
use core::future::Future;
use core::pin::Pin;

use futures::future::poll_fn;

#[cfg_attr(docsrs, doc(cfg(feature = "futures")))]
/// Adapter from `futures::io` traits.
pub struct FromFutures<T: ?Sized> {
    inner: T,
}

impl<T> FromFutures<T> {
    /// Create a new adapter.
    pub fn new(inner: T) -> Self {
        Self { inner }
    }

    /// Consume the adapter, returning the inner object.
    pub fn into_inner(self) -> T {
        self.inner
    }
}

impl<T: ?Sized> FromFutures<T> {
    /// Borrow the inner object.
    pub fn inner(&self) -> &T {
        &self.inner
    }

    /// Mutably borrow the inner object.
    pub fn inner_mut(&mut self) -> &mut T {
        &mut self.inner
    }
}

impl<T: ?Sized> crate::Io for FromFutures<T> {
    type Error = std::io::Error;
}

impl<T: futures::io::AsyncRead + Unpin + ?Sized> crate::asynch::Read for FromFutures<T> {
    type ReadFuture<'a> = impl Future<Output = Result<usize, Self::Error>> + 'a
    where
        Self: 'a;

    fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> Self::ReadFuture<'a> {
        poll_fn(|cx| Pin::new(&mut self.inner).poll_read(cx, buf))
    }
}

impl<T: futures::io::AsyncWrite + Unpin + ?Sized> crate::asynch::Write for FromFutures<T> {
    type WriteFuture<'a> = impl Future<Output = Result<usize, Self::Error>> + 'a
    where
        Self: 'a;

    type FlushFuture<'a> = impl Future<Output = Result<(), Self::Error>> + 'a
    where
        Self: 'a;

    fn write<'a>(&'a mut self, buf: &'a [u8]) -> Self::WriteFuture<'a> {
        poll_fn(|cx| Pin::new(&mut self.inner).poll_write(cx, buf))
    }
    fn flush<'a>(&'a mut self) -> Self::FlushFuture<'a> {
        poll_fn(|cx| Pin::new(&mut self.inner).poll_flush(cx))
    }
}

impl<T: futures::io::AsyncSeek + Unpin + ?Sized> crate::asynch::Seek for FromFutures<T> {
    type SeekFuture<'a> = impl Future<Output = Result<u64, Self::Error>> + 'a
    where
        Self: 'a;

    fn seek<'a>(&'a mut self, pos: crate::SeekFrom) -> Self::SeekFuture<'a> {
        poll_fn(move |cx| Pin::new(&mut self.inner).poll_seek(cx, pos.into()))
    }
}

// TODO: ToFutures.
// It's a bit tricky because futures::io is "stateless", while we're "stateful" (we
// return futures that borrow Self and get polled for the duration of the operation.)
// It can probably done by storing the futures in Self, with unsafe Pin hacks because
// we're a self-referential struct