summaryrefslogtreecommitdiff
path: root/src/types/path_buffer.rs
blob: d6a0861ae7b59e15ad0b5cb21e34c95df78a5118 (plain) (blame)
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
pub struct BedrockPathBuffer {
    buffer: [u8; 256],
    pointer: u8,
}

impl BedrockPathBuffer {
    pub fn new() -> Self {
        Self { buffer: [0; 256] , pointer: 0 }
    }

    /// Clear the buffer, returning the previous buffer contents.
    pub fn clear(&mut self) -> [u8; 256] {
        self.pointer = 0;
        std::mem::replace(&mut self.buffer, [0; 256])
    }

    /// Reset the pointer and hot-swap the byte buffer.
    pub fn populate(&mut self, buffer: [u8; 256]) {
        self.pointer = 0;
        self.buffer = buffer;
    }

    /// Move internal pointer to the start of the path or file name.
    ///
    /// If value is non-zero, the pointer will be moved to the byte
    /// directly following the final forward-slash.
    pub fn set_pointer(&mut self, value: u8) {
        self.pointer = 0;
        // Set the pointer to the start of the filename if value is truthy.
        if value != 0x00 {
            for (i, c) in self.buffer.iter().enumerate() {
                match c {
                    b'/' => self.pointer = (i as u8).saturating_add(1),
                    0x00 => break,
                    _ => continue,
                }
            }
        }
    }

    /// Read a single byte from the buffer.
    pub fn read(&mut self) -> u8 {
        let pointer = self.pointer as usize;
        self.pointer = self.pointer.wrapping_add(1);
        self.buffer[pointer]
    }

    /// Write a single byte to the buffer.
    ///
    /// If a null-byte is written, the buffer will be cleared and returned.
    pub fn write(&mut self, byte: u8) -> Option<[u8; 256]> {
        if byte == 0x00 {
            Some(self.clear())
        } else {
            self.buffer[self.pointer as usize] = byte;
            self.pointer = self.pointer.saturating_add(1);
            None
        }
    }
}