grubbnet/
buffer.rs

1pub const MAX_BUFFER_SIZE: usize = 1024 * 16;
2
3// TODO (Declan, 10/12/2019)
4// We should probably be using a ring buffer instead.
5
6/// A simple byte buffer, useful for storing bytes that are going to be consumed in packets.
7pub struct NetworkBuffer {
8    pub data: [u8; MAX_BUFFER_SIZE],
9    pub offset: usize,
10}
11
12impl NetworkBuffer {
13    pub fn new() -> Self {
14        NetworkBuffer {
15            data: [0; MAX_BUFFER_SIZE],
16            offset: 0,
17        }
18    }
19
20    /// Deletes `count` bytes from the front of the buffer, then shifts the rest of the buffer back in place at index 0.
21    pub fn drain(&mut self, count: usize) {
22        unsafe {
23            use std::ptr;
24            ptr::copy(
25                self.data.as_ptr().offset(count as isize),
26                self.data.as_mut_ptr(),
27                self.offset - count,
28            );
29        }
30
31        self.offset -= count;
32    }
33
34    pub fn clear(&mut self) {
35        self.data = [0; MAX_BUFFER_SIZE];
36        self.offset = 0;
37    }
38}