ioutils/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use std::io::{Read, Write};
4
5/// Merger a reader and a writer into a single stream that implements `Read` and `Write`.
6pub struct Stream<R: Read, W: Write> {
7    reader: R,
8    writer: W,
9}
10
11impl<R: Read, W: Write> Stream<R, W> {
12    pub fn new(reader: R, writer: W) -> Self {
13        Self { reader, writer }
14    }
15
16    /// Split the stream into a reader and a writer borrowing.
17    pub fn split<'a>(&'a mut self) -> (ReadHalf<'a, R>, WriteHalf<'a, W>) {
18        (ReadHalf { inner: &mut self.reader }, WriteHalf { inner: &mut self.writer })
19    }
20
21    /// Split the stream into a reader and a writer taking ownership.
22    pub fn into_split(self) -> (OwnedReadHalf<R>, OwnedWriteHalf<W>) {
23        (OwnedReadHalf { inner: self.reader }, OwnedWriteHalf { inner: self.writer })
24    }
25}
26
27impl<R: Read, W: Write> Read for Stream<R, W> {
28    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
29        self.reader.read(buf)
30    }
31}
32
33impl<R: Read, W: Write> Write for Stream<R, W> {
34    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
35        self.writer.write(buf)
36    }
37
38    fn flush(&mut self) -> std::io::Result<()> {
39        self.writer.flush()
40    }
41}
42
43pub struct ReadHalf<'a, T: Read> {
44    inner: &'a mut T,
45}
46
47impl<'a, T: Read> Read for ReadHalf<'a, T> {
48    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
49        self.inner.read(buf)
50    }
51}
52
53pub struct WriteHalf<'a, T: Write> {
54    inner: &'a mut T,
55}
56
57impl<'a, T: Write> Write for WriteHalf<'a, T> {
58    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
59        self.inner.write(buf)
60    }
61
62    fn flush(&mut self) -> std::io::Result<()> {
63        self.inner.flush()
64    }
65}
66
67pub struct OwnedReadHalf<T: Read> {
68    inner: T,
69}
70
71impl<T: Read> Read for OwnedReadHalf<T> {
72    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
73        self.inner.read(buf)
74    }
75}
76
77pub struct OwnedWriteHalf<T: Write> {
78    inner: T,
79}
80
81impl<T: Write> Write for OwnedWriteHalf<T> {
82    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
83        self.inner.write(buf)
84    }
85
86    fn flush(&mut self) -> std::io::Result<()> {
87        self.inner.flush()
88    }
89}