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
use std::future::{self, Future};
use std::io::{Cursor, Empty, Result, SeekFrom};
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};

use completion_core::CompletionFuture;

/// A cursor which can be moved within a stream of bytes.
///
/// This is an asynchronous version of [`std::io::Seek`].
///
/// You should not implement this trait manually, instead implement [`AsyncSeekWith`].
pub trait AsyncSeek: for<'a> AsyncSeekWith<'a> {}
impl<T: for<'a> AsyncSeekWith<'a> + ?Sized> AsyncSeek for T {}

/// A cursor which can be moved within a stream of bytes with a specific lifetime.
pub trait AsyncSeekWith<'a> {
    /// Future that seeks to an offset a stream. If successful, resolves to the new position from
    /// the start of the stream.
    type SeekFuture: CompletionFuture<Output = Result<u64>>;

    /// Seek to an offset in bytes in a stream.
    fn seek(&'a mut self, pos: SeekFrom) -> Self::SeekFuture;
}

impl<'a, S: AsyncSeekWith<'a> + ?Sized> AsyncSeekWith<'a> for &mut S {
    type SeekFuture = S::SeekFuture;

    #[inline]
    fn seek(&'a mut self, pos: SeekFrom) -> Self::SeekFuture {
        (**self).seek(pos)
    }
}

impl<'a, S: AsyncSeekWith<'a> + ?Sized> AsyncSeekWith<'a> for Box<S> {
    type SeekFuture = S::SeekFuture;

    #[inline]
    fn seek(&'a mut self, pos: SeekFrom) -> Self::SeekFuture {
        (**self).seek(pos)
    }
}

impl<'a> AsyncSeekWith<'a> for Empty {
    type SeekFuture = future::Ready<Result<u64>>;

    fn seek(&'a mut self, _pos: SeekFrom) -> Self::SeekFuture {
        future::ready(Ok(0))
    }
}

impl<'a, T: AsRef<[u8]>> AsyncSeekWith<'a> for Cursor<T> {
    type SeekFuture = SeekCursor<'a, T>;

    #[inline]
    fn seek(&'a mut self, pos: SeekFrom) -> Self::SeekFuture {
        SeekCursor {
            cursor: self,
            pos,
            _lifetime: PhantomData,
        }
    }
}

/// Future for [`seek`](AsyncSeekWith::seek) on a [`Cursor`].
#[derive(Debug)]
pub struct SeekCursor<'a, T> {
    // This is conceptually an &'a mut Cursor<T>. However, that would add the implicit bound T: 'a
    // which is incompatible with AsyncReadWith.
    cursor: *mut Cursor<T>,
    pos: SeekFrom,
    _lifetime: PhantomData<&'a ()>,
}
// SeekFrom is always Send+Sync, and we hold a mutable reference to Cursor.
unsafe impl<T: Send> Send for SeekCursor<'_, T> {}
unsafe impl<T: Sync> Sync for SeekCursor<'_, T> {}

impl<T: AsRef<[u8]>> Future for SeekCursor<'_, T> {
    type Output = Result<u64>;

    fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = &mut *self;
        Poll::Ready(std::io::Seek::seek(unsafe { &mut *this.cursor }, this.pos))
    }
}
impl<T: AsRef<[u8]>> CompletionFuture for SeekCursor<'_, T> {
    type Output = Result<u64>;

    unsafe fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        Future::poll(self, cx)
    }
    unsafe fn poll_cancel(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
        Poll::Ready(())
    }
}

#[cfg(test)]
#[allow(dead_code, clippy::extra_unused_lifetimes)]
fn test_impls_traits<'a>() {
    fn assert_impls<R: AsyncSeek>() {}

    assert_impls::<Cursor<&'a [u8]>>();
    assert_impls::<Cursor<Vec<u8>>>();
    assert_impls::<&'a mut Cursor<&'a [u8]>>();
    assert_impls::<&'a mut Cursor<Vec<u8>>>();
    assert_impls::<Box<Cursor<&'a [u8]>>>();
    assert_impls::<Box<Cursor<Vec<u8>>>>();
}