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
use async_trait::async_trait;
use std::{io, sync::Arc};

pub mod buf_reader_at;
pub mod range_reader;
pub mod read_at_wrapper;

/// Provides length and asynchronous random access to a resource
#[async_trait(?Send)]
pub trait ReadAt {
    /// Read bytes from resource, starting at `offset`, into `buf`
    async fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize>;

    /// Reads exactly `buf`, starting at `offset`
    async fn read_at_exact(&self, mut offset: u64, mut buf: &mut [u8]) -> io::Result<()> {
        while !buf.is_empty() {
            match self.read_at(offset, buf).await? {
                0 => break,
                n => {
                    offset += n as u64;
                    buf = &mut buf[n..];
                }
            }
        }
        if !buf.is_empty() {
            Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "failed to fill whole buffer",
            ))
        } else {
            Ok(())
        }
    }

    /// Returns the length of the resource, in bytes
    fn len(&self) -> u64;

    /// Returns true if that resource is empty (has a length of 0)
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

#[async_trait(?Send)]
impl<'a, T> ReadAt for &'a T
where
    T: ReadAt,
{
    async fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize> {
        Ok((*self).read_at(offset, buf).await?)
    }

    fn len(&self) -> u64 {
        (*self).len()
    }
}

#[async_trait(?Send)]
impl<'a, T> ReadAt for Arc<T>
where
    T: ReadAt,
{
    async fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize> {
        Ok(self.as_ref().read_at(offset, buf).await?)
    }

    fn len(&self) -> u64 {
        self.as_ref().len()
    }
}

#[async_trait(?Send)]
impl<'a, T> ReadAt for Box<T>
where
    T: ReadAt,
{
    async fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize> {
        Ok(self.as_ref().read_at(offset, buf).await?)
    }

    fn len(&self) -> u64 {
        self.as_ref().len()
    }
}

/// Type that can be converted into an `AsyncReadAt`.
pub trait AsAsyncReadAt {
    type Out: ReadAt;

    fn as_async_read_at(self: &Arc<Self>) -> Self::Out;
}