microsandbox_utils/
seekable.rs

1//! `microsandbox_utils::seekable` is a module containing seekable utilities for the microsandbox project.
2
3use std::{
4    io::{self, SeekFrom},
5    pin::Pin,
6    task::{Context, Poll},
7};
8use tokio::io::{AsyncRead, AsyncSeek, AsyncWrite, ReadBuf};
9
10//--------------------------------------------------------------------------------------------------
11// Types
12//--------------------------------------------------------------------------------------------------
13
14/// A seekable reader that always reads zero bytes and reports position as 0.
15#[derive(Debug)]
16pub struct EmptySeekableReader;
17
18/// A seekable writer that always writes zero bytes and reports position as 0.
19#[derive(Debug)]
20pub struct EmptySeekableWriter;
21
22//--------------------------------------------------------------------------------------------------
23// Traits
24//--------------------------------------------------------------------------------------------------
25
26/// A trait that extends the `AsyncRead` and `AsyncSeek` traits to allow for seeking.
27pub trait SeekableReader: AsyncRead + AsyncSeek {}
28
29/// A trait that extends the `AsyncWrite` and `AsyncSeek` traits to allow for seeking.
30pub trait SeekableWriter: AsyncWrite + AsyncSeek {}
31
32//--------------------------------------------------------------------------------------------------
33// Trait Implementations
34//--------------------------------------------------------------------------------------------------
35
36impl<T> SeekableReader for T where T: AsyncRead + AsyncSeek {}
37
38impl<T> SeekableWriter for T where T: AsyncWrite + AsyncSeek {}
39
40// Implement AsyncRead by always reading zero bytes
41impl AsyncRead for EmptySeekableReader {
42    fn poll_read(
43        self: Pin<&mut Self>,
44        _cx: &mut Context<'_>,
45        _buf: &mut ReadBuf<'_>,
46    ) -> Poll<io::Result<()>> {
47        Poll::Ready(Ok(()))
48    }
49}
50
51// Implement AsyncSeek by always claiming the new position is 0
52impl AsyncSeek for EmptySeekableReader {
53    fn start_seek(self: Pin<&mut Self>, _position: SeekFrom) -> io::Result<()> {
54        Ok(())
55    }
56
57    fn poll_complete(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<u64>> {
58        Poll::Ready(Ok(0))
59    }
60}