vortex_io/
write.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::future::{Future, ready};
5use std::io::{self, Cursor, Write};
6
7use vortex_buffer::ByteBufferMut;
8
9use crate::IoBuf;
10
11pub trait VortexWrite {
12    fn write_all<B: IoBuf>(&mut self, buffer: B) -> impl Future<Output = io::Result<B>>;
13    fn flush(&mut self) -> impl Future<Output = io::Result<()>>;
14    fn shutdown(&mut self) -> impl Future<Output = io::Result<()>>;
15}
16
17impl VortexWrite for Vec<u8> {
18    fn write_all<B: IoBuf>(&mut self, buffer: B) -> impl Future<Output = io::Result<B>> {
19        self.extend_from_slice(buffer.as_slice());
20        ready(Ok(buffer))
21    }
22
23    fn flush(&mut self) -> impl Future<Output = io::Result<()>> {
24        ready(Ok(()))
25    }
26
27    fn shutdown(&mut self) -> impl Future<Output = io::Result<()>> {
28        ready(Ok(()))
29    }
30}
31
32impl VortexWrite for ByteBufferMut {
33    fn write_all<B: IoBuf>(&mut self, buffer: B) -> impl Future<Output = io::Result<B>> {
34        self.extend_from_slice(buffer.as_slice());
35        ready(Ok(buffer))
36    }
37
38    fn flush(&mut self) -> impl Future<Output = io::Result<()>> {
39        ready(Ok(()))
40    }
41
42    fn shutdown(&mut self) -> impl Future<Output = io::Result<()>> {
43        ready(Ok(()))
44    }
45}
46
47impl<T> VortexWrite for Cursor<T>
48where
49    Cursor<T>: Write,
50{
51    fn write_all<B: IoBuf>(&mut self, buffer: B) -> impl Future<Output = io::Result<B>> {
52        ready(Write::write_all(self, buffer.as_slice()).map(|_| buffer))
53    }
54
55    fn flush(&mut self) -> impl Future<Output = io::Result<()>> {
56        ready(Write::flush(self))
57    }
58
59    fn shutdown(&mut self) -> impl Future<Output = io::Result<()>> {
60        ready(Ok(()))
61    }
62}
63
64impl<W: VortexWrite> VortexWrite for futures::io::Cursor<W> {
65    fn write_all<B: IoBuf>(&mut self, buffer: B) -> impl Future<Output = io::Result<B>> {
66        self.set_position(self.position() + buffer.as_slice().len() as u64);
67        VortexWrite::write_all(self.get_mut(), buffer)
68    }
69
70    fn flush(&mut self) -> impl Future<Output = io::Result<()>> {
71        VortexWrite::flush(self.get_mut())
72    }
73
74    fn shutdown(&mut self) -> impl Future<Output = io::Result<()>> {
75        VortexWrite::shutdown(self.get_mut())
76    }
77}
78
79impl<W: VortexWrite> VortexWrite for &mut W {
80    fn write_all<B: IoBuf>(&mut self, buffer: B) -> impl Future<Output = io::Result<B>> {
81        (*self).write_all(buffer)
82    }
83
84    fn flush(&mut self) -> impl Future<Output = io::Result<()>> {
85        (*self).flush()
86    }
87
88    fn shutdown(&mut self) -> impl Future<Output = io::Result<()>> {
89        (*self).shutdown()
90    }
91}