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
use std::{
    io::{self, prelude::*},
    time::Duration,
};

use crate::{error::*, PositionalResult};

/// Position within a readable source
#[derive(Debug, Clone)]
pub struct ReadPosition {
    pub(crate) byte_offset: u64,
    pub(crate) duration: Duration,
}

impl ReadPosition {
    pub(crate) const fn new() -> Self {
        Self {
            byte_offset: 0,
            duration: Duration::ZERO,
        }
    }

    /// The number of bytes that have been consumed
    #[must_use]
    pub const fn byte_offset(&self) -> u64 {
        self.byte_offset
    }

    /// The accumulated duration since the start of the stream
    #[must_use]
    pub const fn duration(&self) -> Duration {
        self.duration
    }
}

pub struct Reader<'r, T> {
    reader: &'r mut T,
    position: ReadPosition,
}

impl<'r, T: Read> Reader<'r, T> {
    pub fn new(reader: &'r mut T) -> Self {
        Reader {
            reader,
            position: ReadPosition::new(),
        }
    }

    fn read_exact(&mut self, buffer: &mut [u8]) -> PositionalResult<()> {
        self.reader
            .read_exact(buffer)
            .map(|()| {
                self.position.byte_offset += buffer.len() as u64;
            })
            .map_err(|e| self.positional_error(e.into()))
    }

    pub fn try_read_exact_until_eof(&mut self, buffer: &mut [u8]) -> PositionalResult<bool> {
        self.read_exact(buffer).map(|()| true).or_else(|err| {
            if err.is_unexpected_eof() {
                Ok(false)
            } else {
                Err(err)
            }
        })
    }

    fn skip(&mut self, max_bytes: u64) -> PositionalResult<u64> {
        match io::copy(&mut self.reader.take(max_bytes), &mut io::sink()) {
            Err(e) => Err(self.positional_error(e.into())),
            Ok(num_bytes_skipped) => {
                debug_assert!(num_bytes_skipped <= max_bytes);
                self.position.byte_offset += num_bytes_skipped;
                Ok(num_bytes_skipped)
            }
        }
    }

    pub fn try_skip_exact_until_eof(&mut self, num_bytes: u64) -> PositionalResult<bool> {
        match self.skip(num_bytes) {
            Ok(skipped_bytes) => {
                debug_assert!(skipped_bytes <= num_bytes);
                Ok(skipped_bytes == num_bytes)
            }
            Err(err) => {
                if err.is_unexpected_eof() {
                    Ok(false)
                } else {
                    Err(err)
                }
            }
        }
    }

    pub fn position(&self) -> &ReadPosition {
        &self.position
    }

    pub fn add_duration(&mut self, duration: Duration) {
        self.position.duration += duration;
    }

    pub fn positional_error(&self, source: Error) -> PositionalError {
        let Self { position, .. } = self;
        PositionalError {
            source,
            position: position.to_owned(),
        }
    }
}