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
use byteorder::{ReadBytesExt, LE};
use std::convert::{TryFrom, TryInto};
use std::io::{self, Error, ErrorKind, Read, Result};

/// Read a 2-byte integer that uses -1 as an "absent" value.
///
/// ## Example
///
/// ```rust
/// use genie_support::read_opt_u16;
///
/// let mut minus_one = std::io::Cursor::new(vec![0xFF, 0xFF]);
/// let mut zero = std::io::Cursor::new(vec![0x00, 0x00]);
///
/// assert_eq!(read_opt_u16::<u16, _>(&mut minus_one).unwrap(), None);
/// assert_eq!(read_opt_u16(&mut zero).unwrap(), Some(0));
/// ```
#[inline]
pub fn read_opt_u16<T, R>(mut input: R) -> Result<Option<T>>
where
    T: TryFrom<u16>,
    T::Error: std::error::Error + Send + Sync + 'static,
    R: Read,
{
    let opt = match input.read_u16::<LE>()? {
        0xFFFF => None,
        v => Some(
            v.try_into()
                .map_err(|e| Error::new(ErrorKind::InvalidData, e))?,
        ),
    };
    Ok(opt)
}

/// Read a 4-byte integer that uses -1 as an "absent" value.
///
/// ## Example
///
/// ```rust
/// use genie_support::read_opt_u32;
///
/// let mut minus_one = std::io::Cursor::new(vec![0xFF, 0xFF, 0xFF, 0xFF]);
/// let mut one = std::io::Cursor::new(vec![0x01, 0x00, 0x00, 0x00]);
///
/// assert_eq!(read_opt_u32::<u32, _>(&mut minus_one).unwrap(), None);
/// assert_eq!(read_opt_u32(&mut one).unwrap(), Some(1));
/// ```
#[inline]
pub fn read_opt_u32<T, R>(mut input: R) -> Result<Option<T>>
where
    T: TryFrom<u32>,
    T::Error: std::error::Error + Send + Sync + 'static,
    R: Read,
{
    let opt = match input.read_u32::<LE>()? {
        0xFFFF_FFFF => None,
        // HD Edition uses -2 in some places.
        0xFFFF_FFFE => None,
        v => Some(
            v.try_into()
                .map_err(|e| Error::new(ErrorKind::InvalidData, e))?,
        ),
    };
    Ok(opt)
}

/// Extension trait that adds a `skip()` method to `Read` instances.
pub trait ReadSkipExt {
    /// Read and discard a number of bytes.
    fn skip(&mut self, dist: u64) -> Result<()>;
}

impl<T: Read> ReadSkipExt for T {
    fn skip(&mut self, dist: u64) -> Result<()> {
        io::copy(&mut self.by_ref().take(dist), &mut io::sink())?;
        Ok(())
    }
}