binread/
pos_value.rs

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
use super::*;
use core::fmt;

/// A wrapper where the position it was read from is stored alongside the value
/// ```rust
/// use binread::{BinRead, PosValue, BinReaderExt, io::Cursor};
///
/// #[derive(BinRead)]
/// struct MyType {
///     a: u16,
///     b: PosValue<u8>
/// }
///
/// let val = Cursor::new(b"\xFF\xFE\xFD").read_be::<MyType>().unwrap();
/// assert_eq!(val.b.pos, 2);
/// assert_eq!(*val.b, 0xFD);
/// ```
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.stream_pos()?;

        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::{io::Cursor, BinRead, BinReaderExt, PosValue};

        #[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);
    }
}