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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
use core::convert::TryInto;

use crate::endian::*;

/// This struct represents a data view for reading and writing data in a byte array.
/// When read/write, This increment current offset by the size of the value.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct DataView<T> {
    pub data: T,
    pub offset: usize,
}

impl<T: AsRef<[u8]>> DataView<T> {
    /// Returns remaining slice from the current offset.
    /// It doesn't change the offset.
    ///
    /// # Examples
    ///
    /// ```
    /// use data_view::DataView;
    ///
    /// let mut view = DataView::from([1, 2, 3]);
    ///
    /// assert_eq!(view.remaining_slice(), &[1, 2, 3]);
    /// view.offset = 3;
    /// assert!(view.remaining_slice().is_empty());
    /// ```
    #[inline]
    pub fn remaining_slice(&self) -> &[u8] {
        let data = self.data.as_ref();
        &data[self.offset.min(data.len())..]
    }

    /// Reads a value of type `E: Endian` from the DataView.
    ///
    /// # Examples
    ///
    /// ```
    /// use data_view::DataView;
    ///
    /// let mut view = DataView::from([0; 4]);
    ///
    /// view.write::<u16>(42);
    /// view.offset = 0;
    /// assert_eq!(view.read::<u16>().unwrap(), 42);
    /// ```
    #[inline]
    pub fn read<E: Endian>(&mut self) -> Option<E> {
        self.read_slice(E::SIZE)
            .map(|bytes| unsafe { num_from(bytes) })
    }

    /// Reads a value of type `E: Endian` from the DataView, without doing bounds checking.
    /// For a safe alternative see [`read`].
    ///
    /// [`read`]: #method.read
    ///
    /// # Safety
    ///
    /// Calling this method with an out-of-bounds index is *[undefined behavior]*
    #[inline]
    pub unsafe fn read_unchecked<E: Endian>(&mut self) -> E {
        num_from(self.read_slice_unchecked(E::SIZE))
    }

    /// Read slice from the current offset.
    ///
    /// # Example
    /// ```
    /// use data_view::DataView;
    ///
    /// let mut view = DataView::from([1, 2, 3, 4]);
    ///
    /// assert_eq!(view.read_slice(2).unwrap(), &[1, 2]);
    /// assert_eq!(view.read_slice(2).unwrap(), &[3, 4]);
    /// ```
    #[inline]
    pub fn read_slice(&mut self, len: usize) -> Option<&[u8]> {
        let total_len = self.offset + len;
        let slice = self.data.as_ref().get(self.offset..total_len)?;
        self.offset = total_len;
        Some(slice)
    }

    /// Read slice from the current offset, without doing bounds checking.
    /// For a safe alternative see [`read_slice`].
    ///
    /// [`read_slice`]: #method.read_slice
    ///
    /// # Example
    /// ```
    /// use data_view::DataView;
    /// let mut view = DataView::from([1, 2, 3, 4]);
    /// unsafe {
    ///     assert_eq!(view.read_slice_unchecked(2), &[1, 2]);
    ///     assert_eq!(view.read_slice_unchecked(2), &[3, 4]);
    /// }
    /// ```
    /// # Safety
    ///
    /// Calling this method with an out-of-bounds index is *[undefined behavior]*
    /// even if the resulting reference is not used.
    #[inline]
    pub unsafe fn read_slice_unchecked(&mut self, len: usize) -> &[u8] {
        let data = self.data.as_ref();
        let total_len = self.offset + len;
        debug_assert!(total_len <= data.len());

        let slice = data.get_unchecked(self.offset..total_len);
        self.offset = total_len;
        slice
    }

    /// Create a buffer and returns it, from the current offset.
    ///
    /// # Examples
    ///
    /// ```
    /// use data_view::DataView;
    ///
    /// let mut view = DataView::from([1, 2, 3, 4]);
    ///
    /// assert_eq!(view.read_buf::<2>().unwrap(), [1, 2]);
    /// assert_eq!(view.read_buf::<2>().unwrap(), [3, 4]);
    /// ```
    #[inline]
    pub fn read_buf<const N: usize>(&mut self) -> Option<[u8; N]> {
        self.read_slice(N)
            .map(|bytes| unsafe { bytes.try_into().unwrap_unchecked() })
    }

    /// Returns a reference to an element or subslice, without doing bounds checking.
    /// For a safe alternative see [`read_buf`].
    ///
    /// [`read_buf`]: #method.read_buf
    ///
    /// # Safety
    ///
    /// Calling this method with an out-of-bounds index is *[undefined behavior]*
    #[inline]
    pub unsafe fn read_buf_unchecked<const N: usize>(&mut self) -> [u8; N] {
        self.read_slice_unchecked(N).try_into().unwrap_unchecked()
    }
}

impl<T: AsMut<[u8]>> DataView<T> {
    /// Writes a value of type `E` to the data view. where `E` is a type that implements `Endian`.
    ///
    /// # Examples
    ///
    /// ```
    /// use data_view::DataView;
    ///
    /// let mut view = DataView::from([0; 2]);
    ///
    /// view.write::<u8>(12);
    /// view.write::<u8>(34);
    /// assert_eq!(view.data, [12, 34]);
    /// ```
    /// # Panics
    /// Panics if the offset is out of bounds.
    #[inline]
    pub fn write<E: Endian>(&mut self, num: E) {
        let dst = self.data.as_mut();
        let total_len = self.offset + E::SIZE;
        assert!(total_len <= dst.len());
        unsafe { num_write_at(num, dst.as_mut_ptr().add(self.offset)) };
        self.offset = total_len;
    }

    /// Writes a slice into the data view.
    ///
    /// # Examples
    ///
    /// ```
    /// use data_view::DataView;
    ///
    /// let mut view = DataView::from([0; 4]);
    /// view.write_slice([1, 2]);
    /// view.write_slice([3, 4]);
    /// assert_eq!(view.data, [1, 2, 3, 4]);
    /// ```
    /// # Panics
    /// Panics if the offset is out of bounds.
    #[inline]
    pub fn write_slice(&mut self, slice: impl AsRef<[u8]>) {
        let src = slice.as_ref();
        let dst = self.data.as_mut();
        let count = src.len();
        let total_len = self.offset + count;
        assert!(total_len <= dst.len());
        unsafe {
            core::ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr().add(self.offset), count);
        }
        self.offset = total_len;
    }
}

impl<T> From<T> for DataView<T> {
    /// Creates a new `View` from a byte array.
    /// The offset is set to 0.
    ///
    /// # Examples
    ///
    /// ```
    /// use data_view::DataView;
    ///
    /// let view = DataView::from([0; 16]);
    /// ```
    #[inline]
    fn from(data: T) -> Self {
        Self { data, offset: 0 }
    }
}