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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
use bytes::BytesMut;
use std::cmp::min;
use std::io::{self, Read, Write};
pub mod crypto;
pub mod progress;
mod traits;
pub use progress::{ProgressPipe, ProgressReader, ProgressReporter, ProgressWriter};
pub use traits::{Pipe, PipeLen, PipeRead, PipeWrite, ReadLen, WriteLen};
pub mod prelude {
pub use super::{crypto::prelude::*, Pipe, PipeLen, PipeRead, PipeWrite, ReadLen, WriteLen};
}
const DEFAULT_BUF_SIZE: usize = 8 * 1024;
pub struct PipeReader<P>
where
P: Pipe,
{
pipe: P,
inner: Box<dyn Read>,
buf: BytesMut,
}
pub struct PipeWriter<P>
where
P: Pipe,
{
pipe: P,
inner: Box<dyn Write>,
}
impl<P> PipeRead<P> for PipeReader<P>
where
P: Pipe,
{
fn new(pipe: P, inner: Box<dyn Read>) -> Self {
Self {
pipe,
inner,
buf: BytesMut::with_capacity(DEFAULT_BUF_SIZE),
}
}
}
impl<P> PipeWrite<P> for PipeWriter<P>
where
P: Pipe,
{
fn new(pipe: P, inner: Box<dyn Write>) -> Self {
Self { pipe, inner }
}
}
impl<P> Read for PipeReader<P>
where
P: Pipe,
{
fn read(&mut self, mut buf: &mut [u8]) -> io::Result<usize> {
let capacity = min(DEFAULT_BUF_SIZE, buf.len()) - self.buf.len();
if capacity > 0 {
let mut inner_buf = vec![0u8; capacity];
let read = self.inner.read(&mut inner_buf)?;
self.buf.extend_from_slice(&inner_buf[..read]);
if read == 0 {
return Ok(0);
}
}
let (read, out) = self.pipe.pipe(&self.buf);
let _ = self.buf.split_to(read);
let mut total = 0;
if let Some(out) = out {
let write = min(out.len(), buf.len());
total += write;
buf[..write].copy_from_slice(&out[..write]);
assert_eq!(
write,
out.len(),
"failed to write all pipe output bytes to output buffer"
);
if write == buf.len() {
return Ok(total);
}
buf = &mut buf[write..];
}
self.read(buf).map(|n| n + total)
}
}
impl<P> Write for PipeWriter<P>
where
P: Pipe,
{
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let (read, data) = self.pipe.pipe(buf);
if let Some(data) = data {
self.inner.write_all(&data)?;
}
Ok(read)
}
fn flush(&mut self) -> io::Result<()> {
self.inner.flush()
}
}