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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
use super::*;
use crate::element::*;
use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};
use serde_bytes::ByteBuf;
use std::default::Default;
#[inline]
fn is_false(v: &bool) -> bool {
!v
}
#[inline]
fn bytes_empty(v: &ByteBuf) -> bool {
v.is_empty()
}
#[inline]
fn u32_is_zero(v: &u32) -> bool {
*v == 0
}
#[inline]
fn u32_is_max(v: &u32) -> bool {
*v == u32::MAX
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct BinValidator {
#[serde(skip_serializing_if = "String::is_empty")]
pub comment: String,
#[serde(skip_serializing_if = "bytes_empty")]
pub bits_clr: ByteBuf,
#[serde(skip_serializing_if = "bytes_empty")]
pub bits_set: ByteBuf,
#[serde(skip_serializing_if = "bytes_empty")]
pub max: ByteBuf,
#[serde(skip_serializing_if = "bytes_empty")]
pub min: ByteBuf,
#[serde(skip_serializing_if = "is_false")]
pub ex_max: bool,
#[serde(skip_serializing_if = "is_false")]
pub ex_min: bool,
#[serde(skip_serializing_if = "u32_is_max")]
pub max_len: u32,
#[serde(skip_serializing_if = "u32_is_zero")]
pub min_len: u32,
#[serde(rename = "in", skip_serializing_if = "Vec::is_empty")]
pub in_list: Vec<ByteBuf>,
#[serde(rename = "nin", skip_serializing_if = "Vec::is_empty")]
pub nin_list: Vec<ByteBuf>,
#[serde(skip_serializing_if = "is_false")]
pub query: bool,
#[serde(skip_serializing_if = "is_false")]
pub bit: bool,
#[serde(skip_serializing_if = "is_false")]
pub ord: bool,
#[serde(skip_serializing_if = "is_false")]
pub size: bool,
}
impl Default for BinValidator {
fn default() -> Self {
Self {
comment: String::new(),
bits_clr: ByteBuf::new(),
bits_set: ByteBuf::new(),
ex_max: false,
ex_min: false,
max: ByteBuf::new(),
min: ByteBuf::new(),
max_len: u32::MAX,
min_len: u32::MIN,
in_list: Vec::new(),
nin_list: Vec::new(),
query: false,
bit: false,
ord: false,
size: false,
}
}
}
impl BinValidator {
pub fn new() -> Self {
Self::default()
}
pub fn comment(mut self, comment: impl Into<String>) -> Self {
self.comment = comment.into();
self
}
pub fn bits_set(mut self, bits_set: impl Into<Vec<u8>>) -> Self {
self.bits_set = ByteBuf::from(bits_set);
self
}
pub fn bits_clr(mut self, bits_clr: impl Into<Vec<u8>>) -> Self {
self.bits_clr = ByteBuf::from(bits_clr);
self
}
pub fn max(mut self, max: impl Into<Vec<u8>>) -> Self {
self.max = ByteBuf::from(max);
self
}
pub fn min(mut self, min: impl Into<Vec<u8>>) -> Self {
self.min = ByteBuf::from(min);
self
}
pub fn ex_max(mut self, ex_max: bool) -> Self {
self.ex_max = ex_max;
self
}
pub fn ex_min(mut self, ex_min: bool) -> Self {
self.ex_min = ex_min;
self
}
pub fn max_len(mut self, max_len: u32) -> Self {
self.max_len = max_len;
self
}
pub fn min_len(mut self, min_len: u32) -> Self {
self.min_len = min_len;
self
}
pub fn in_add(mut self, add: impl Into<Vec<u8>>) -> Self {
self.in_list.push(ByteBuf::from(add));
self
}
pub fn nin_add(mut self, add: impl Into<Vec<u8>>) -> Self {
self.nin_list.push(ByteBuf::from(add));
self
}
pub fn query(mut self, query: bool) -> Self {
self.query = query;
self
}
pub fn bit(mut self, bit: bool) -> Self {
self.bit = bit;
self
}
pub fn ord(mut self, ord: bool) -> Self {
self.ord = ord;
self
}
pub fn size(mut self, size: bool) -> Self {
self.size = size;
self
}
pub fn build(self) -> Validator {
Validator::Bin(self)
}
pub(crate) fn validate(&self, parser: &mut Parser) -> Result<()> {
use std::iter::repeat;
let elem = parser
.next()
.ok_or_else(|| Error::FailValidate("expected binary data".to_string()))??;
let val = if let Element::Bin(v) = elem {
v
} else {
return Err(Error::FailValidate(format!(
"expected Bin, got {}",
elem.name()
)));
};
if (val.len() as u32) > self.max_len {
return Err(Error::FailValidate(
"Bin is longer than max_len".to_string(),
));
}
if (val.len() as u32) < self.min_len {
return Err(Error::FailValidate(
"Bin is shorter than min_len".to_string(),
));
}
if self
.bits_set
.iter()
.zip(val.iter().chain(repeat(&0u8)))
.any(|(bit, val)| (bit & val) != *bit)
{
return Err(Error::FailValidate(
"Bin does not have all required bits set".to_string(),
));
}
if self
.bits_clr
.iter()
.zip(val.iter().chain(repeat(&0u8)))
.any(|(bit, val)| (bit & val) != 0)
{
return Err(Error::FailValidate(
"Bin does not have all required bits cleared".to_string(),
));
}
use std::cmp::Ordering;
fn compare(lhs: &[u8], rhs: &[u8]) -> Ordering {
match lhs.len().cmp(&rhs.len()) {
Ordering::Equal => Iterator::cmp(lhs.iter().rev(), rhs.iter().rev()),
other => other,
}
}
fn trim(val: &[u8]) -> &[u8] {
let trim_amount = val.iter().rev().take_while(|v| **v == 0).count();
&val[0..(val.len() - trim_amount)]
}
if !self.max.is_empty() || !self.min.is_empty() || self.ex_min {
let trimmed_val = trim(val);
let max_pass = match (self.max.is_empty(), self.ex_max) {
(true, _) => true,
(false, true) => compare(trimmed_val, trim(&self.max)) == Ordering::Less,
(false, false) => compare(trimmed_val, trim(&self.max)) != Ordering::Greater,
};
let min_pass = match (self.min.is_empty(), self.ex_min) {
(true, true) => !trimmed_val.is_empty(),
(true, false) => true,
(false, true) => compare(trimmed_val, trim(&self.min)) == Ordering::Greater,
(false, false) => compare(trimmed_val, trim(&self.min)) != Ordering::Less,
};
if !max_pass {
return Err(Error::FailValidate(
"Bin greater than maximum allowed".to_string(),
));
}
if !min_pass {
return Err(Error::FailValidate(
"Bin less than minimum allowed".to_string(),
));
}
}
if !self.in_list.is_empty() && !self.in_list.iter().any(|v| *v == val) {
return Err(Error::FailValidate("Bin is not on `in` list".to_string()));
}
if self.nin_list.iter().any(|v| *v == val) {
return Err(Error::FailValidate("Bin is on `nin` list".to_string()));
}
Ok(())
}
fn query_check_self(&self, other: &Self) -> bool {
(self.query || (other.in_list.is_empty() && other.nin_list.is_empty()))
&& (self.bit || (other.bits_set.is_empty() && other.bits_clr.is_empty()))
&& (self.ord
|| (!other.ex_min && !other.ex_max && other.min.is_empty() && other.max.is_empty()))
&& (self.size || (u32_is_max(&other.max_len) && u32_is_zero(&other.min_len)))
}
pub(crate) fn query_check(&self, other: &Validator) -> bool {
match other {
Validator::Bin(other) => self.query_check_self(other),
Validator::Multi(list) => list.iter().all(|other| match other {
Validator::Bin(other) => self.query_check_self(other),
_ => false,
}),
Validator::Any => true,
_ => false,
}
}
}