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
use crate::{
    io::{Read, Seek},
    BinRead, BinResult, Endian,
};
use core::fmt;

/// A wrapper that stores a value’s position alongside the value.
///
/// # Examples
///
/// ```
/// use binrw::{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> {
    /// The read value.
    pub val: T,

    /// The byte position of the start of the value.
    pub pos: u64,
}

impl<T: BinRead> BinRead for PosValue<T> {
    type Args<'a> = T::Args<'a>;

    fn read_options<R: Read + Seek>(
        reader: &mut R,
        endian: Endian,
        args: Self::Args<'_>,
    ) -> BinResult<Self> {
        let pos = reader.stream_position()?;

        Ok(PosValue {
            pos,
            val: T::read_options(reader, endian, 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
    }
}