aboutsummaryrefslogtreecommitdiff
path: root/src/utils/cursor.rs
blob: c41270a71c1fdffe33e43b8baf4d345376efd1b2 (plain)
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
use std::io::{Error, ErrorKind, Read, Result, Seek, SeekFrom, Write};

pub struct IoCursor<Io> {
    io: Io,
    cursor: u64,
    bounds: (u64, u64),
}

impl<Io: Seek> IoCursor<Io> {
    pub fn new(mut io: Io, start: u64, end: u64) -> Result<Self> {
        let cursor = io.seek(SeekFrom::Start(start))?;
        Ok(Self {
            io,
            cursor,
            bounds: (cursor, end),
        })
    }
}

impl<Io: Read> Read for IoCursor<Io> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        let upper = buf.len().min((self.bounds.1 - self.cursor) as usize);
        let bytes = self.io.read(&mut buf[..upper])?;
        self.cursor += bytes as u64;
        Ok(bytes)
    }
}

impl<Io: Write> Write for IoCursor<Io> {
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        let upper = buf.len().min((self.bounds.1 - self.cursor) as usize);
        let bytes = self.io.write(&buf[..upper])?;
        self.cursor += bytes as u64;
        Ok(bytes)
    }

    #[inline]
    fn flush(&mut self) -> Result<()> {
        self.io.flush()
    }
}

impl<Io: Seek> Seek for IoCursor<Io> {
    fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
        self.cursor = match pos {
            SeekFrom::Start(0) => return Ok(self.cursor - self.bounds.0),
            SeekFrom::Start(offset) => self.bounds.0.checked_add(offset),
            SeekFrom::End(offset) => self.bounds.1.checked_add_signed(offset),
            SeekFrom::Current(offset) => self.cursor.checked_add_signed(offset),
        }
        .filter(|v| *v >= self.bounds.0)
        .ok_or(Error::new(
            ErrorKind::InvalidInput,
            "Invalid seek to a negative or overflowing position",
        ))?
        .min(self.bounds.1);

        Ok(self.io.seek(SeekFrom::Start(self.cursor))? - self.bounds.0)
    }
}