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
use super::*;
use core::fmt;
pub struct PosValue<T> {
pub val: T,
pub pos: u64
}
impl<T: BinRead> BinRead for PosValue<T> {
type Args = T::Args;
fn read_options<R: Read + Seek>(reader: &mut R, options: &ReadOptions, args: T::Args)
-> BinResult<Self>
{
let pos = reader.seek(SeekFrom::Current(0))?;
Ok(PosValue {
pos,
val: T::read_options(reader, options, args)?
})
}
fn after_parse<R: Read + Seek>(&mut self, reader: &mut R, options: &ReadOptions, args: Self::Args)
-> BinResult<()>
{
self.val.after_parse(reader, options, args)
}
}
impl<T> core::ops::Deref for PosValue<T> {
type Target = T;
fn deref(&self) -> &T {
&self.val
}
}
impl<T> core::ops::DerefMut for PosValue<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.val
}
}
impl<T: fmt::Debug> fmt::Debug for PosValue<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.val.fmt(f)
}
}
impl<T: Clone> Clone for PosValue<T> {
fn clone(&self) -> Self {
Self {
val: self.val.clone(),
pos: self.pos
}
}
}
impl<U, T: PartialEq<U>> PartialEq<U> for PosValue<T> {
fn eq(&self, other: &U) -> bool {
self.val == *other
}
}
#[cfg(test)]
mod tests {
use crate as binread;
#[test]
fn pos_value() {
use binread::{BinRead, PosValue, BinReaderExt, io::Cursor};
#[derive(BinRead)]
struct MyType {
a: u16,
b: PosValue<u8>
}
let mut val = Cursor::new(b"\xFF\xFE\xFD").read_be::<MyType>().unwrap();
assert_eq!(val.a, 0xFFFE);
assert_eq!(val.b.pos, 2);
assert_eq!(*val.b, 0xFD);
assert_eq!(val.b, 0xFDu8);
*val.b = 1u8;
assert_eq!(*val.b, 1);
assert_eq!(format!("{:?}", val.b), "1");
let clone = val.b.clone();
assert_eq!(*clone, *val.b);
assert_eq!(clone.pos, val.b.pos);
}
}