product_os_cursor/
cursor.rs

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
111
112
113
114
115
116
117
use crate::{Result, Error};

pub struct Cursor<T> {
    inner: T,
    position: usize,
}

impl<T> Cursor<T> {
    pub fn new(inner: T) -> Self {
        Self {
            inner,
            position: 0,
        }
    }

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

    pub fn set_position(&mut self, position: usize) {
        self.position = position;
    }

    pub fn get_ref(&self) -> &T {
        &self.inner
    }

    pub fn get_mut_ref(&mut self) -> &mut T {
        &mut self.inner
    }
}

impl<T: AsRef<[u8]>> Cursor<T> {
    pub fn remaining_slice(&self) -> &[u8] {
        let len = self.position.min(self.inner.as_ref().len());

        &self.inner.as_ref()[len..]
    }

    pub fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        let slice = self.remaining_slice();
        let amt = buf.len().min(slice.len());
        let a = &slice[..amt];

        if amt == 1 {
            buf[0] = a[0];
        } else {
            buf[..amt].copy_from_slice(a);
        }

        self.position += amt;

        Ok(amt)
    }

    pub fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
        let slice = self.remaining_slice();
        if buf.len() > slice.len() {
            return Err(Error::UnexpectedEof);
        }
        let a = &slice[..buf.len()];

        if buf.len() == 1 {
            buf[0] = a[0];
        } else {
            buf.copy_from_slice(a);
        }

        self.position += buf.len();

        Ok(())
    }
}

impl Cursor<&mut [u8]> {
    pub fn remaining_slice_mut(&mut self) -> &mut [u8] {
        let len = self.position.min(self.inner.as_mut().len());

        &mut self.inner.as_mut()[len..]
    }

    pub fn write(&mut self, data: &[u8]) -> Result<usize> {
        let slice = self.remaining_slice_mut();
        let amt = data.len().min(slice.len());

        slice[..amt].copy_from_slice(&data[..amt]);

        self.position += amt;

        Ok(amt)
    }
}

impl<const N: usize> Cursor<[u8; N]> {
    pub fn remaining_slice_mut(&mut self) -> &mut [u8] {
        let len = self.position.min(self.inner.as_mut().len());

        &mut self.inner.as_mut()[len..]
    }

    pub fn write(&mut self, data: &[u8]) -> Result<usize> {
        let slice = self.remaining_slice_mut();
        let amt = data.len().min(slice.len());

        slice[..amt].copy_from_slice(&data[..amt]);

        self.position += amt;

        Ok(amt)
    }
}

impl<T: AsRef<[u8]>> AsRef<T> for Cursor<T> {
    fn as_ref(&self) -> &T {
        &self.inner
    }
}