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
159
160
161
162
use std;
use std::io::{Read, Seek};
pub trait Pos {
fn pos(&mut self) -> usize;
fn size(&mut self) -> usize;
}
impl<T> Pos for T
where
T: Seek,
{
fn pos(&mut self) -> usize {
self.seek(std::io::SeekFrom::Current(0))
.expect("Could not check position") as usize
}
fn size(&mut self) -> usize {
let old = self
.seek(std::io::SeekFrom::Current(0))
.expect("Could not check position");
let size = self
.seek(std::io::SeekFrom::End(0))
.expect("Could not look for end of stream");
self.seek(std::io::SeekFrom::Start(old))
.expect("Could not rewind");
size as usize
}
}
pub struct PosRead<T>
where
T: Read,
{
inner: T,
pos: usize,
}
impl<T> PosRead<T>
where
T: Read,
{
pub fn new(inner: T) -> Self {
PosRead { inner, pos: 0 }
}
pub fn pos(&mut self) -> usize {
self.pos
}
}
impl<T> Read for PosRead<T>
where
T: Read,
{
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let bytes_read = self.inner.read(buf)?;
self.pos += bytes_read;
Ok(bytes_read)
}
}
pub trait ReadConst {
fn read_const(&mut self, bytes: &[u8]) -> Result<(), std::io::Error>;
}
impl<T> ReadConst for T
where
T: std::io::Read,
{
fn read_const(&mut self, data: &[u8]) -> Result<(), std::io::Error> {
let mut buf = Vec::with_capacity(data.len());
unsafe {
buf.set_len(data.len());
}
let bytes = self.read(&mut buf)?;
if bytes != data.len() || &buf as &[u8] != data {
debug!(target: "read_const", "Invalid data {:?}, expected {:?}",
String::from_utf8(buf.to_vec()),
String::from_utf8(data.to_vec())
);
let details = String::from_utf8(data.to_vec())
.unwrap_or_else(|_| "<invalid read_const string>".to_string());
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
details,
));
}
Ok(())
}
}
pub struct PoisonLock<S> {
state: S,
poisoned: bool,
}
impl<S> PoisonLock<S> {
pub fn new(state: S) -> Self {
PoisonLock {
state,
poisoned: false,
}
}
pub fn try<T, E, F>(&mut self, f: F) -> Result<T, E>
where
F: FnOnce(&mut S) -> Result<T, E>,
{
assert!(!self.poisoned, "State is poisoned");
f(&mut self.state).map_err(|err| {
self.poisoned = true;
err
})
}
pub fn poison(&mut self) {
self.poisoned = true;
}
pub fn is_poisoned(&self) -> bool {
self.poisoned
}
}