bytecodec/
eos.rs

1use crate::ByteCount;
2
3/// `Eos` contains information on the distance to the end of a stream.
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd)]
5pub struct Eos(ByteCount);
6impl Eos {
7    /// Makes a new `Eos` instance.
8    pub fn new(is_eos_reached: bool) -> Self {
9        if is_eos_reached {
10            Eos(ByteCount::Finite(0))
11        } else {
12            Eos(ByteCount::Unknown)
13        }
14    }
15
16    /// Makes a new `Eos` instance that
17    /// has the given information about the number of remaining bytes in a stream.
18    pub fn with_remaining_bytes(n: ByteCount) -> Self {
19        Eos(n)
20    }
21
22    /// Returns `true` if the target stream has reached to the end, otherwise `false`.
23    pub fn is_reached(&self) -> bool {
24        self.0 == ByteCount::Finite(0)
25    }
26
27    /// Returns the information about the number of bytes remaining in the target stream.
28    pub fn remaining_bytes(&self) -> ByteCount {
29        self.0
30    }
31
32    /// Returns a new `Eos` instance that has moved backward from
33    /// the end of the target stream by the specified number of bytes.
34    ///
35    /// # Examples
36    ///
37    /// ```
38    /// use bytecodec::{ByteCount, Eos};
39    ///
40    /// let eos = Eos::new(true);
41    /// assert_eq!(eos.is_reached(), true);
42    /// assert_eq!(eos.remaining_bytes(), ByteCount::Finite(0));
43    ///
44    /// let eos = eos.back(5);
45    /// assert_eq!(eos.is_reached(), false);
46    /// assert_eq!(eos.remaining_bytes(), ByteCount::Finite(5));
47    /// ```
48    pub fn back(&self, bytes: u64) -> Self {
49        if let ByteCount::Finite(n) = self.0 {
50            Eos(ByteCount::Finite(n + bytes))
51        } else {
52            *self
53        }
54    }
55}