fusio/impls/
mod.rs

1//! Implementations of the traits in the `fusio` crate.
2
3pub mod buffered;
4pub mod disk;
5pub mod remotes;
6
7use std::{
8    future::Future,
9    io::{self, Cursor},
10};
11
12use crate::{Error, IoBuf, IoBufMut, MaybeSend, Read, Write};
13
14impl Read for &mut Vec<u8> {
15    async fn read_exact_at<B: IoBufMut>(&mut self, mut buf: B, pos: u64) -> (Result<(), Error>, B) {
16        let pos = pos as usize;
17        let len = buf.bytes_init();
18        let end = pos + len;
19        if end > self.len() {
20            return (
21                Err(io::Error::new(io::ErrorKind::UnexpectedEof, "").into()),
22                buf,
23            );
24        }
25        buf.as_slice_mut().copy_from_slice(&self[pos..end]);
26        (Ok(()), buf)
27    }
28
29    async fn read_to_end_at(&mut self, mut buf: Vec<u8>, pos: u64) -> (Result<(), Error>, Vec<u8>) {
30        let pos = pos as usize;
31        buf.extend_from_slice(&self[pos..]);
32        (Ok(()), buf)
33    }
34
35    async fn size(&self) -> Result<u64, Error> {
36        Ok(self.len() as u64)
37    }
38}
39
40impl Write for Cursor<&mut Vec<u8>> {
41    async fn write_all<B: IoBuf>(&mut self, buf: B) -> (Result<(), Error>, B) {
42        (
43            std::io::Write::write_all(self, buf.as_slice()).map_err(Error::Io),
44            buf,
45        )
46    }
47
48    async fn flush(&mut self) -> Result<(), Error> {
49        Ok(())
50    }
51
52    async fn close(&mut self) -> Result<(), Error> {
53        Ok(())
54    }
55}
56
57pub trait SeqRead: MaybeSend {
58    fn read_exact<B: IoBufMut>(
59        &mut self,
60        buf: B,
61    ) -> impl Future<Output = (Result<(), Error>, B)> + MaybeSend;
62}
63
64impl<R: SeqRead> SeqRead for &mut R {
65    fn read_exact<B: IoBufMut>(
66        &mut self,
67        buf: B,
68    ) -> impl Future<Output = (Result<(), Error>, B)> + MaybeSend {
69        R::read_exact(self, buf)
70    }
71}
72
73impl<R: Read> SeqRead for Cursor<R> {
74    async fn read_exact<B: IoBufMut>(&mut self, buf: B) -> (Result<(), Error>, B) {
75        let pos = self.position();
76        let result = self.get_mut().read_exact_at(buf, pos).await;
77        self.set_position(pos + result.1.bytes_init() as u64);
78        result
79    }
80}