-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathv2.rs
More file actions
88 lines (76 loc) · 2.27 KB
/
v2.rs
File metadata and controls
88 lines (76 loc) · 2.27 KB
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
use crate::DisplayError;
#[derive(Clone, Debug)]
pub enum WriteMode {
Data,
Command,
}
pub trait WriteInterface<DataFormat> {
fn write(&mut self, mode: WriteMode, buf: &[DataFormat]) -> Result<(), DisplayError> {
self.write_iter(mode, &mut buf.into_iter())
}
fn write_iter(
&mut self,
mode: WriteMode,
iter: &mut dyn Iterator<Item = &DataFormat>,
) -> Result<(), DisplayError> {
self.write_stream(mode, &mut || iter.next())
}
fn write_stream<'a>(
&mut self,
mode: WriteMode,
func: &mut dyn FnMut() -> Option<&'a DataFormat>,
) -> Result<(), DisplayError>;
}
pub trait ReadInterface<DataFormat> {
fn read(&mut self, buf: &mut [DataFormat]) -> Result<(), DisplayError> {
let mut n = 0;
self.read_stream(&mut |b| {
if n == buf.len() {
return false;
}
buf[n] = b;
n += 1;
true
})
}
fn read_stream(&mut self, f: &mut dyn FnMut(DataFormat) -> bool) -> Result<(), DisplayError>;
}
pub trait ReadWriteInterface<T>: ReadInterface<T> + WriteInterface<T> {}
impl<DataFormat, T> ReadWriteInterface<DataFormat> for T where
T: ReadInterface<DataFormat> + WriteInterface<DataFormat>
{
}
pub struct ReadIterator<'a, DataFormat> {
reader: &'a mut dyn ReadInterface<DataFormat>,
}
impl<'a, DataFormat> ReadIterator<'a, DataFormat> {
fn new(reader: &'a mut dyn ReadInterface<DataFormat>) -> ReadIterator<'a, DataFormat> {
ReadIterator { reader: reader }
}
}
impl<'a, DataFormat> Iterator for ReadIterator<'a, DataFormat>
where
DataFormat: Default,
{
type Item = Result<DataFormat, DisplayError>;
fn next(&mut self) -> Option<Self::Item> {
let mut next: DataFormat = Default::default();
match self.reader.read_stream(&mut |b| {
next = b;
false
}) {
Ok(_) => Some(Ok(next)),
Err(e) => Some(Err(e)),
}
}
}
impl<'a, DataFormat> IntoIterator for &'a mut dyn ReadInterface<DataFormat>
where
DataFormat: Default,
{
type Item = Result<DataFormat, DisplayError>;
type IntoIter = ReadIterator<'a, DataFormat>;
fn into_iter(self) -> Self::IntoIter {
ReadIterator::new(self)
}
}