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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
#![crate_type = "lib"]
extern crate byteorder;
use std::io;
pub use std::io::{Write, Read};
use std::ops::Deref;
use std::cmp::min;
use std::borrow::{Cow, Borrow};
use std::error;
use std::result;
use std::string;
use std::fmt::{self, Display, Formatter};
use byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
pub mod record;
pub type Result<T> = result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
IOError(io::Error),
InvalidUtf8(string::FromUtf8Error),
InvalidCase,
InvalidEnum,
InvalidLen,
Generic(String),
}
impl Error {
pub fn invalidcase() -> Error {
Error::InvalidCase
}
pub fn invalidenum() -> Error {
Error::InvalidEnum
}
pub fn invalidlen() -> Error {
Error::InvalidLen
}
pub fn badutf8(err: string::FromUtf8Error) -> Error {
Error::InvalidUtf8(err)
}
pub fn generic<T>(err: T) -> Error
where T: Display + error::Error
{
Error::Generic(format!("{}", err))
}
}
impl From<String> for Error {
fn from(str: String) -> Self { Error::Generic(str) }
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Self { Error::IOError(err) }
}
impl<'a> From<&'a str> for Error {
fn from(err: &'a str) -> Self { Error::Generic(String::from(err)) }
}
impl From<string::FromUtf8Error> for Error {
fn from(err: string::FromUtf8Error) -> Self { Error::InvalidUtf8(err) }
}
unsafe impl Send for Error {}
unsafe impl Sync for Error {}
impl error::Error for Error {
fn description(&self) -> &str {
match self {
&Error::IOError(ref ioe) => ioe.description(),
&Error::InvalidUtf8(ref se) => se.description(),
&Error::Generic(ref s) => s,
&Error::InvalidCase => "invalid switch case",
&Error::InvalidEnum => "invalid enum value",
&Error::InvalidLen => "invalid string/array length",
}
}
fn cause(&self) -> Option<&error::Error> {
match self {
&Error::IOError(ref ioe) => Some(ioe),
&Error::InvalidUtf8(ref se) => Some(se),
_ => None
}
}
}
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut Formatter) -> result::Result<(), fmt::Error> {
use std::error::Error;
write!(fmt, "{}", self.description())
}
}
static PADDING: [u8; 4] = [0; 4];
#[inline]
pub fn padding(sz: usize) -> &'static [u8] {
&PADDING[..(4 - (sz % 4)) % 4]
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Opaque<'a>(pub Cow<'a, [u8]>);
impl<'a> Opaque<'a> {
pub fn owned(v: Vec<u8>) -> Opaque<'a> { Opaque(Cow::Owned(v)) }
pub fn borrowed(v: &'a [u8]) -> Opaque<'a> { Opaque(Cow::Borrowed(v)) }
}
impl<'a> Deref for Opaque<'a> {
type Target = [u8];
fn deref(&self) -> &[u8] { self.0.deref() }
}
impl<'a> From<&'a [u8]> for Opaque<'a> {
fn from(v: &'a [u8]) -> Self { Opaque::borrowed(v) }
}
pub fn pack<Out: Write, T: Pack<Out>>(val: &T, out: &mut Out) -> Result<()> {
val.pack(out).map(|_| ())
}
pub fn pack_array<Out, T>(val: &[T], sz: usize, out: &mut Out, defl: Option<&T>) -> Result<usize>
where Out: Write, T: Pack<Out>
{
let mut vsz = 0;
let val = &val[..min(sz, val.len())];
for v in val {
vsz += try!(v.pack(out))
}
assert!(vsz % 4 == 0);
if val.len() < sz {
if let Some(defl) = defl {
for _ in val.len()..sz {
vsz += try!(defl.pack(out))
}
} else {
return Err(Error::InvalidLen)
}
}
Ok(vsz)
}
pub fn pack_opaque_array<Out: Write>(val: &[u8], sz: usize, out: &mut Out) -> Result<usize> {
let mut vsz;
let val = &val[..min(sz, val.len())];
vsz = val.len();
try!(out.write_all(val));
let p = padding(sz);
for _ in val.len()..(sz + p.len()) {
try!(out.write_u8(0));
vsz += 1;
}
Ok(vsz)
}
#[inline]
pub fn pack_flex<Out: Write, T: Pack<Out>>(val: &[T], maxsz: Option<usize>, out: &mut Out) -> Result<usize> {
if maxsz.map_or(false, |m| val.len() > m) {
return Err(Error::InvalidLen)
}
val.pack(out)
}
#[inline]
pub fn pack_opaque_flex<Out: Write>(val: &[u8], maxsz: Option<usize>, out: &mut Out) -> Result<usize> {
if maxsz.map_or(false, |m| val.len() > m) {
return Err(Error::InvalidLen)
}
Opaque::borrowed(val).pack(out)
}
#[inline]
pub fn pack_string<Out: Write>(val: &str, maxsz: Option<usize>, out: &mut Out) -> Result<usize> {
pack_opaque_flex(val.as_bytes(), maxsz, out)
}
pub fn unpack_array<In, T>(input: &mut In, array: &mut [T], arraysz: usize, defl: Option<&T>) -> Result<usize>
where In: Read, T: Unpack<In> + Clone
{
let mut rsz = 0;
let sz = min(arraysz, array.len());
for elem in &mut array[..sz] {
let (v, sz) = try!(Unpack::unpack(input));
rsz += sz;
*elem = v;
}
if arraysz < array.len() {
if let Some(defl) = defl {
for elem in &mut array[arraysz..] {
*elem = defl.clone();
}
} else {
return Err(Error::InvalidLen)
}
}
if arraysz > array.len() {
for _ in array.len()..arraysz {
let (_, sz) = try!(T::unpack(input));
rsz += sz;
}
}
assert!(rsz % 4 == 0);
Ok(rsz)
}
pub fn unpack_opaque_array<In: Read>(input: &mut In, bytes: &mut [u8], bytesz: usize) -> Result<usize> {
let sz = min(bytesz, bytes.len());
let mut rsz = 0;
while rsz < sz {
let r = try!(input.read(&mut bytes[rsz..]));
rsz += r;
}
if sz < bytes.len() {
for b in &mut bytes[sz..] {
*b = 0;
}
}
let p = padding(bytesz).len();
if bytes.len() < bytesz + p {
for _ in bytes.len()..(bytesz + p) {
let _ = try!(input.read_u8());
rsz += 1;
}
}
Ok(rsz)
}
pub fn unpack_flex<In: Read, T: Unpack<In>>(input: &mut In, maxsz: Option<usize>) -> Result<(Vec<T>, usize)> {
let (elems, mut sz) = try!(Unpack::unpack(input));
if maxsz.map_or(false, |m| elems > m) {
return Err(Error::InvalidLen)
}
let mut out = Vec::with_capacity(elems);
for _ in 0..elems {
let (e, esz) = try!(Unpack::unpack(input));
out.push(e);
sz += esz;
}
let p = padding(sz);
for _ in 0..p.len() {
let _ = try!(input.read_u8());
}
sz += p.len();
Ok((out, sz))
}
pub fn unpack_opaque_flex<In: Read>(input: &mut In, maxsz: Option<usize>) -> Result<(Vec<u8>, usize)> {
let (elems, mut sz) = try!(Unpack::unpack(input));
if maxsz.map_or(false, |m| elems > m) {
return Err(Error::InvalidLen)
}
let mut out = Vec::with_capacity(elems);
sz += try!(input.take(elems as u64).read_to_end(&mut out));
let p = padding(sz);
for _ in 0..p.len() {
let _ = try!(input.read_u8());
}
sz += p.len();
Ok((out, sz))
}
pub fn unpack_string<In: Read>(input: &mut In, maxsz: Option<usize>) -> Result<(String, usize)> {
let (v, sz) = try!(unpack_opaque_flex(input, maxsz));
String::from_utf8(v).map_err(Error::from).map(|s| (s, sz))
}
pub trait Pack<Out: Write> {
fn pack(&self, out: &mut Out) -> Result<usize>;
}
impl<Out: Write> Pack<Out> for u32 {
#[inline]
fn pack(&self, out: &mut Out) -> Result<usize> {
out.write_u32::<BigEndian>(*self).map_err(Error::from).map(|_| 4)
}
}
impl<Out: Write> Pack<Out> for i32 {
#[inline]
fn pack(&self, out: &mut Out) -> Result<usize> {
out.write_i32::<BigEndian>(*self).map_err(Error::from).map(|_| 4)
}
}
impl<Out: Write> Pack<Out> for u64 {
#[inline]
fn pack(&self, out: &mut Out) -> Result<usize> {
out.write_u64::<BigEndian>(*self).map_err(Error::from).map(|_| 8)
}
}
impl<Out: Write> Pack<Out> for i64 {
#[inline]
fn pack(&self, out: &mut Out) -> Result<usize> {
out.write_i64::<BigEndian>(*self).map_err(Error::from).map(|_| 8)
}
}
impl<Out: Write> Pack<Out> for f32 {
#[inline]
fn pack(&self, out: &mut Out) -> Result<usize> {
out.write_f32::<BigEndian>(*self).map_err(Error::from).map(|_| 4)
}
}
impl<Out: Write> Pack<Out> for f64 {
#[inline]
fn pack(&self, out: &mut Out) -> Result<usize> {
out.write_f64::<BigEndian>(*self).map_err(Error::from).map(|_| 8)
}
}
impl<Out: Write> Pack<Out> for bool {
#[inline]
fn pack(&self, out: &mut Out) -> Result<usize> {
(*self as u32).pack(out)
}
}
impl<Out: Write> Pack<Out> for () {
#[inline]
fn pack(&self, _out: &mut Out) -> Result<usize> {
Ok(0)
}
}
impl<Out: Write> Pack<Out> for usize {
#[inline]
fn pack(&self, out: &mut Out) -> Result<usize> {
(*self as u32).pack(out)
}
}
impl<Out: Write, T: Pack<Out>> Pack<Out> for [T] {
fn pack(&self, out: &mut Out) -> Result<usize> {
let len = self.len();
let mut sz = try!(len.pack(out));
for it in self {
sz += try!(it.pack(out))
}
let p = padding(sz);
if p.len() > 0 {
try!(out.write_all(p));
sz += p.len();
}
Ok(sz)
}
}
impl<Out: Write, T: Pack<Out>> Pack<Out> for Vec<T> {
#[inline]
fn pack(&self, out: &mut Out) -> Result<usize> {
if self.len() > u32::max_value() as usize {
return Err(Error::InvalidLen);
}
(&self[..]).pack(out)
}
}
impl<'a, Out: Write> Pack<Out> for Opaque<'a> {
fn pack(&self, out: &mut Out) -> Result<usize> {
let mut sz;
let data: &[u8] = self.0.borrow();
if data.len() > u32::max_value() as usize {
return Err(Error::InvalidLen)
}
sz = try!(data.len().pack(out));
try!(out.write_all(data));
sz += data.len();
let p = padding(sz);
if p.len() > 0 {
try!(out.write_all(p));
sz += p.len();
}
Ok(sz)
}
}
impl<Out: Write> Pack<Out> for str {
#[inline]
fn pack(&self, out: &mut Out) -> Result<usize> {
Opaque::borrowed(self.as_bytes()).pack(out)
}
}
impl<Out: Write, T: Pack<Out>> Pack<Out> for Option<T> {
fn pack(&self, out: &mut Out) -> Result<usize> {
match self {
&None => false.pack(out),
&Some(ref v) => {
let sz = try!(true.pack(out)) + try!(v.pack(out));
Ok(sz)
}
}
}
}
impl<Out: Write, T: Pack<Out>> Pack<Out> for Box<T> {
fn pack(&self, out: &mut Out) -> Result<usize> {
let t: &T = self.borrow();
t.pack(out)
}
}
impl<'a, Out: Write, T> Pack<Out> for Cow<'a, T>
where T: 'a + Pack<Out> + ToOwned<Owned=T>
{
fn pack(&self, out: &mut Out) -> Result<usize> {
let t: &T = self.borrow();
t.pack(out)
}
}
pub fn unpack<In: Read, T: Unpack<In>>(input: &mut In) -> Result<T> {
T::unpack(input).map(|(v, _)| v)
}
pub trait Unpack<In: Read>: Sized {
fn unpack(input: &mut In) -> Result<(Self, usize)>;
}
impl<In: Read> Unpack<In> for u32 {
#[inline]
fn unpack(input: &mut In) -> Result<(Self, usize)> {
input.read_u32::<BigEndian>().map_err(Error::from).map(|v| (v, 4))
}
}
impl<In: Read> Unpack<In> for i32 {
#[inline]
fn unpack(input: &mut In) -> Result<(Self, usize)> {
input.read_i32::<BigEndian>().map_err(Error::from).map(|v| (v, 4))
}
}
impl<In: Read> Unpack<In> for u64 {
#[inline]
fn unpack(input: &mut In) -> Result<(Self, usize)> {
input.read_u64::<BigEndian>().map_err(Error::from).map(|v| (v, 8))
}
}
impl<In: Read> Unpack<In> for i64 {
#[inline]
fn unpack(input: &mut In) -> Result<(Self, usize)> {
input.read_i64::<BigEndian>().map_err(Error::from).map(|v| (v, 8))
}
}
impl<In: Read> Unpack<In> for f32 {
fn unpack(input: &mut In) -> Result<(Self, usize)> {
input.read_f32::<BigEndian>().map_err(Error::from).map(|v| (v, 4))
}
}
impl<In: Read> Unpack<In> for f64 {
fn unpack(input: &mut In) -> Result<(Self, usize)> {
input.read_f64::<BigEndian>().map_err(Error::from).map(|v| (v, 8))
}
}
impl<In: Read> Unpack<In> for bool {
#[inline]
fn unpack(input: &mut In) -> Result<(Self, usize)> {
u32::unpack(input)
.and_then(|(v, sz)|
match v {
0 => Ok((false, sz)),
1 => Ok((true, sz)),
_ => Err(Error::InvalidEnum)
})
}
}
impl<In: Read> Unpack<In> for () {
#[inline]
fn unpack(_input: &mut In) -> Result<(Self, usize)> {
Ok(((), 0))
}
}
impl<In: Read> Unpack<In> for usize {
#[inline]
fn unpack(input: &mut In) -> Result<(Self, usize)> {
u32::unpack(input).map(|(v, sz)| (v as usize, sz))
}
}
impl<In: Read, T: Unpack<In>> Unpack<In> for Vec<T> {
fn unpack(input: &mut In) -> Result<(Self, usize)> {
unpack_flex(input, None)
}
}
impl<In: Read> Unpack<In> for String {
fn unpack(input: &mut In) -> Result<(Self, usize)> {
let (v, sz) = try!(unpack_opaque_flex(input, None));
String::from_utf8(v).map_err(Error::from).map(|s| (s, sz))
}
}
impl<'a, In: Read> Unpack<In> for Opaque<'a> {
fn unpack(input: &mut In) -> Result<(Self, usize)> {
let (len, mut sz) = try!(usize::unpack(input));
let mut v = Vec::new();
sz += try!(input.by_ref().take(len as u64).read_to_end(&mut v));
let p = padding(sz);
for _ in 0..p.len() {
let _ = try!(input.read_u8());
sz += 1;
}
Ok((Opaque(Cow::Owned(v)), sz))
}
}
impl<In: Read, T: Unpack<In>> Unpack<In> for Option<T> {
fn unpack(input: &mut In) -> Result<(Self, usize)> {
let (have, mut sz) = try!(Unpack::unpack(input));
let ret = if have {
let (v, osz) = try!(Unpack::unpack(input));
sz += osz;
Some(v)
} else {
None
};
Ok((ret, sz))
}
}
impl<In: Read, T: Unpack<In>> Unpack<In> for Box<T> {
fn unpack(input: &mut In) -> Result<(Self, usize)> {
let (b, sz) = try!(Unpack::unpack(input));
Ok((Box::new(b), sz))
}
}
impl<'a, In: Read, T> Unpack<In> for Cow<'a, T>
where T: 'a + Unpack<In> + ToOwned<Owned=T>
{
fn unpack(input: &mut In) -> Result<(Self, usize)> {
let (b, sz) = try!(Unpack::unpack(input));
Ok((Cow::Owned(b), sz))
}
}