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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::UnalignedView;
use core::mem::size_of;
use zerocopy::{
    FromBytes, Immutable, KnownLayout, Ref, SplitByteSlice, SplitByteSliceMut, Unaligned,
};

/// Types that can be converted into a `BufferReader` over a `ByteSlice`.
///
/// Both `BufferReader` and `ByteSlice` types implement this trait and it can be used to accept
/// both byte slices and readers.
pub trait IntoBufferReader<B> {
    fn into_buffer_reader(self) -> BufferReader<B>;
}

impl<B: SplitByteSlice> IntoBufferReader<B> for B {
    fn into_buffer_reader(self) -> BufferReader<B> {
        BufferReader::new(self)
    }
}

pub struct BufferReader<B> {
    buffer: Option<B>,
    bytes_read: usize,
}

impl<B: SplitByteSlice> BufferReader<B> {
    pub fn new(bytes: B) -> Self {
        BufferReader { buffer: Some(bytes), bytes_read: 0 }
    }

    pub fn read<T>(&mut self) -> Option<Ref<B, T>>
    where
        T: Unaligned + KnownLayout + Immutable + FromBytes,
    {
        self.read_bytes(size_of::<T>()).map(|bytes| Ref::from_bytes(bytes).unwrap())
    }

    pub fn read_unaligned<T>(&mut self) -> Option<UnalignedView<B, T>>
    where
        T: FromBytes + Immutable,
    {
        self.read_bytes(size_of::<T>()).map(|bytes| UnalignedView::from_bytes(bytes).unwrap())
    }

    pub fn peek<T>(&self) -> Option<Ref<&[u8], T>>
    where
        T: Unaligned + Immutable + KnownLayout + FromBytes,
    {
        self.peek_bytes(size_of::<T>()).map(|bytes| Ref::from_bytes(bytes).unwrap())
    }

    pub fn peek_unaligned<T>(&self) -> Option<UnalignedView<&[u8], T>>
    where
        T: FromBytes + Immutable,
    {
        self.peek_bytes(size_of::<T>()).map(|bytes| UnalignedView::from_bytes(bytes).unwrap())
    }

    pub fn read_array<T>(&mut self, num_elems: usize) -> Option<Ref<B, [T]>>
    where
        T: Unaligned + FromBytes + Immutable,
    {
        self.read_bytes(size_of::<T>() * num_elems).map(|bytes| Ref::from_bytes(bytes).unwrap())
    }

    pub fn peek_array<T>(&self, num_elems: usize) -> Option<Ref<&[u8], [T]>>
    where
        T: Unaligned + FromBytes + Immutable,
    {
        self.peek_bytes(size_of::<T>() * num_elems).map(|bytes| Ref::from_bytes(bytes).unwrap())
    }

    pub fn read_byte(&mut self) -> Option<u8> {
        self.read_bytes(1).map(|bytes| bytes[0])
    }

    pub fn peek_byte(&mut self) -> Option<u8> {
        self.peek_bytes(1).map(|bytes| bytes[0])
    }

    /// Useful for reading integers.
    ///
    /// Example:
    /// ```
    /// let mut reader = BufferReader::new(&vec![1, 2, 3]);
    /// let val = reader.read_value::<u16>();
    /// assert_eq!(Some(1 + 256 * 2), val);
    /// ```
    pub fn read_value<T>(&mut self) -> Option<T>
    where
        T: FromBytes + Immutable + Copy,
    {
        self.read_unaligned::<T>().map(|view| view.get())
    }

    pub fn peek_value<T>(&self) -> Option<T>
    where
        T: FromBytes + Immutable + Copy,
    {
        self.peek_unaligned::<T>().map(|view| view.get())
    }

    pub fn read_bytes(&mut self, len: usize) -> Option<B> {
        if self.buffer.as_ref().unwrap().len() >= len {
            let (head, tail) = self.buffer.take().unwrap().split_at(len).ok().unwrap();
            self.buffer = Some(tail);
            self.bytes_read += len;
            Some(head)
        } else {
            None
        }
    }

    pub fn peek_bytes(&self, len: usize) -> Option<&[u8]> {
        let buffer = self.buffer.as_ref().unwrap();
        if buffer.len() >= len {
            Some(&buffer[0..len])
        } else {
            None
        }
    }

    pub fn peek_remaining(&self) -> &[u8] {
        &self.buffer.as_ref().unwrap()[..]
    }

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

    pub fn bytes_remaining(&self) -> usize {
        self.buffer.as_ref().unwrap().len()
    }

    pub fn into_remaining(self) -> B {
        self.buffer.unwrap()
    }
}

impl<B: SplitByteSliceMut> BufferReader<B> {
    pub fn peek_mut<T>(&mut self) -> Option<Ref<&mut [u8], T>>
    where
        T: Unaligned + FromBytes + Immutable + KnownLayout,
    {
        self.peek_bytes_mut(size_of::<T>()).map(|bytes| Ref::from_bytes(bytes).unwrap())
    }

    pub fn peek_mut_unaligned<T>(&mut self) -> Option<UnalignedView<&mut [u8], T>>
    where
        T: FromBytes + KnownLayout + Immutable,
    {
        self.peek_bytes_mut(size_of::<T>()).map(|bytes| UnalignedView::from_bytes(bytes).unwrap())
    }

    pub fn peek_array_mut<T>(&mut self, num_elems: usize) -> Option<Ref<&mut [u8], [T]>>
    where
        T: Unaligned + FromBytes + Immutable,
    {
        self.peek_bytes_mut(size_of::<T>() * num_elems).map(|bytes| Ref::from_bytes(bytes).unwrap())
    }

    pub fn peek_bytes_mut(&mut self, len: usize) -> Option<&mut [u8]> {
        let buffer = self.buffer.as_mut().unwrap();
        if buffer.len() >= len {
            Some(&mut buffer[0..len])
        } else {
            None
        }
    }

    pub fn peek_remaining_mut(&mut self) -> &mut [u8] {
        &mut self.buffer.as_mut().unwrap()[..]
    }
}

impl<B: SplitByteSlice> IntoBufferReader<B> for BufferReader<B> {
    fn into_buffer_reader(self) -> BufferReader<B> {
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use zerocopy::{Immutable, IntoBytes};

    #[repr(C, packed)]
    #[derive(IntoBytes, KnownLayout, FromBytes, Immutable, Unaligned)]
    struct Foo {
        x: u8,
        y: u16,
    }

    #[test]
    pub fn read() {
        let mut data = vec![1u8, 2, 3, 4, 5, 6, 7];
        let mut reader = BufferReader::new(&mut data[..]);
        let foo = reader.read::<Foo>().expect("expected a Foo to be read");
        assert_eq!(1, foo.x);
        let y = foo.y;
        assert_eq!(2 + 3 * 256, y); // assuming little endian
        assert_eq!(3, reader.bytes_read());
        assert_eq!(4, reader.bytes_remaining());

        let bytes = reader.read_bytes(2).expect("expected 2 bytes to be read");
        assert_eq!(&[4, 5], bytes);
        assert_eq!(5, reader.bytes_read());
        assert_eq!(2, reader.bytes_remaining());

        assert!(reader.read::<Foo>().is_none());

        let rest = reader.into_remaining();
        assert_eq!(&[6, 7], rest);
    }

    #[test]
    pub fn peek() {
        let mut data = vec![1u8, 2, 3, 4, 5, 6, 7];
        let mut reader = BufferReader::new(&mut data[..]);

        let foo = reader.peek::<Foo>().expect("expected a Foo (1)");
        assert_eq!(1, foo.x);

        let foo = reader.peek::<Foo>().expect("expected a Foo (2)");
        assert_eq!(1, foo.x);

        assert_eq!(0, reader.bytes_read());
        assert_eq!(7, reader.bytes_remaining());

        reader.read_bytes(5);

        let bytes = reader.peek_bytes(2).expect("expected a slice of 2 bytes");
        assert_eq!(&[6, 7], bytes);

        assert!(reader.peek_bytes(3).is_none());

        assert_eq!(&[6, 7], reader.peek_remaining());
    }

    #[test]
    pub fn peek_mut() {
        let mut data = vec![1u8, 2, 3, 4, 5, 6, 7];
        let mut reader = BufferReader::new(&mut data[..]);

        let foo = reader.peek_mut::<Foo>().expect("expected a Foo (1)");
        assert_eq!(1, foo.x);

        let foo = reader.peek_mut::<Foo>().expect("expected a Foo (2)");
        assert_eq!(1, foo.x);

        assert_eq!(0, reader.bytes_read());
        assert_eq!(7, reader.bytes_remaining());

        reader.read_bytes(5);

        let bytes = reader.peek_bytes_mut(2).expect("expected a slice of 2 bytes");
        assert_eq!(&[6, 7], bytes);

        assert!(reader.peek_bytes_mut(3).is_none());

        assert_eq!(&[6, 7], reader.peek_remaining_mut());
    }

    #[test]
    pub fn peek_and_read_value() {
        let mut data = vec![1u8, 2, 3, 4];
        let mut reader = BufferReader::new(&mut data[..]);

        assert_eq!(Some(1), reader.peek_byte());
        assert_eq!(0, reader.bytes_read());
        assert_eq!(4, reader.bytes_remaining());

        assert_eq!(Some(1), reader.read_byte());
        assert_eq!(1, reader.bytes_read());
        assert_eq!(3, reader.bytes_remaining());

        assert_eq!(Some(2 + 256 * 3), reader.peek_value::<u16>()); // assuming little endian
        assert_eq!(1, reader.bytes_read());
        assert_eq!(3, reader.bytes_remaining());

        assert_eq!(Some(2 + 256 * 3), reader.read_value::<u16>()); // assuming little endian
        assert_eq!(3, reader.bytes_read());
        assert_eq!(1, reader.bytes_remaining());

        assert_eq!(None, reader.peek_value::<u16>());
        assert_eq!(None, reader.read_value::<u16>());
        assert_eq!(3, reader.bytes_read());
        assert_eq!(1, reader.bytes_remaining());
    }

    #[test]
    pub fn peek_and_read_array() {
        let mut data = vec![1u8, 2, 3, 4, 5, 6, 7, 8];
        let mut reader = BufferReader::new(&mut data[..]);

        let arr = reader.peek_array::<Foo>(2).expect("expected peek() to return Some");
        assert_eq!(2, arr.len());
        assert_eq!(1, arr[0].x);
        assert_eq!(4, arr[1].x);

        assert_eq!(0, reader.bytes_read());
        assert_eq!(8, reader.bytes_remaining());

        let arr = reader.peek_array_mut::<Foo>(2).expect("expected peek() to return Some");
        assert_eq!(2, arr.len());
        assert_eq!(1, arr[0].x);
        assert_eq!(4, arr[1].x);

        assert_eq!(0, reader.bytes_read());
        assert_eq!(8, reader.bytes_remaining());

        let arr = reader.read_array::<Foo>(2).expect("expected peek() to return Some");
        assert_eq!(2, arr.len());
        assert_eq!(1, arr[0].x);
        assert_eq!(4, arr[1].x);

        assert_eq!(6, reader.bytes_read());
        assert_eq!(2, reader.bytes_remaining());

        assert!(reader.peek_array::<Foo>(1).is_none());
        assert!(reader.read_array::<Foo>(1).is_none());
        assert_eq!(6, reader.bytes_read());
        assert_eq!(2, reader.bytes_remaining());
    }

    #[test]
    pub fn peek_mut_and_modify() {
        let mut data = vec![1u8, 2, 3, 4, 5, 6, 7, 8];
        let mut reader = BufferReader::new(&mut data[..]);

        let mut foo = reader.peek_mut::<Foo>().expect("expected peek() to return Some");
        foo.y = 0xaabb;

        let foo = reader.read::<Foo>().expect("expected read() to return Some");
        let y = foo.y;
        assert_eq!(0xaabb, y);
        assert_eq!(0xbb, data[1]);
        assert_eq!(0xaa, data[2]);
    }

    #[test]
    pub fn unaligned_access() {
        let mut data = vec![1u8, 2, 3, 4, 5, 6];
        let mut reader = BufferReader::new(&mut data[..]);

        reader.read_byte().expect("expected read_byte to return Ok");

        let mut number =
            reader.peek_mut_unaligned::<u32>().expect("expected peek_mut_unaligned to return Ok");
        assert_eq!(0x05040302, number.get());
        number.set(0x0a090807);
        assert_eq!(1, reader.bytes_read());

        let number = reader.peek_unaligned::<u32>().expect("expected peek_unaligned to return Ok");
        assert_eq!(0x0a090807, number.get());
        assert_eq!(1, reader.bytes_read());

        let number = reader.read_unaligned::<u32>().expect("expected read_unaligned to return Ok");
        assert_eq!(0x0a090807, number.get());
        assert_eq!(5, reader.bytes_read());

        assert_eq!(&[1, 7, 8, 9, 10, 6], &data[..]);
    }
}