safe_buffer/
buffer.rs

1pub struct Buffer {
2    chunks: LinkedList<Chunk>,
3    pos: usize,
4}
5
6impl Buffer {
7    pub fn new() -> Buffer {
8        Buffer {
9            chunks: LinkedList::new(),
10            pos: 0,
11        }
12    }
13
14    fn grow_to(&mut self, index: usize) -> io::Result<()> {
15        let chunk_index = index / CHUNK_SIZE;
16
17        // check if already allocated
18        let capacity = self.chunks.len();
19        if chunk_index < capacity {
20            return Ok(());
21        }
22
23        for _ in capacity..(chunk_index + 1) {
24            self.chunks.push_back(Chunk::new()?);
25        }
26
27        Ok(())
28    }
29
30    pub fn len(&self) -> usize {
31        if self.chunks.is_empty() { 0 } else {
32            let last = self.chunks.back().unwrap();
33            (self.chunks.len() - 1) * CHUNK_SIZE + last.len()
34        }
35    }
36
37    pub fn pop_front(&mut self) -> Option<Chunk> {
38        self.pos = if self.pos > CHUNK_SIZE { self.pos - CHUNK_SIZE } else { 0 };
39        self.chunks.pop_front()
40    }
41}
42
43impl io::Write for Buffer {
44    fn write(&mut self, data: &[u8]) -> io::Result<usize> {
45        if data.is_empty() { return Ok(0); }
46
47        // ensure size
48        self.grow_to(self.pos + data.len() - 1)?;
49
50        let len = self.chunks.len();
51
52        let first_index = self.pos / CHUNK_SIZE;
53        let mut iter = if first_index < len - first_index {
54            self.chunks.cursor_front_mut()
55        } else {
56            self.chunks.cursor_back_mut()
57        };
58
59        let mut written: usize = 0;
60        for i in 0..data.len() {
61            let cursor = self.pos + i;
62            let chunk_index = cursor / CHUNK_SIZE;
63            let byte_index = cursor % CHUNK_SIZE;
64
65            iter.at(chunk_index).set(byte_index, data[i]);
66            written += 1;
67        }
68
69        self.pos += written;
70        Ok(written)
71    }
72
73    fn flush(&mut self) -> io::Result<()> {
74        Ok(())
75    }
76}
77
78
79impl io::Seek for Buffer {
80    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
81        let offset = match pos {
82            SeekFrom::Start(offset) => offset as i128,
83            SeekFrom::End(n) => self.len() as i128 + n as i128,
84            SeekFrom::Current(n) => self.pos as i128 + n as i128,
85        };
86
87        if offset < 0 {
88            return Err(Error::new(ErrorKind::InvalidInput, "Seeking before start of buffer!"));
89        }
90
91        let trunc = offset as usize;
92        if trunc as i128 != offset {
93            return Err(Error::new(ErrorKind::OutOfMemory, "Tried seeking past the memory limit!"));
94        }
95
96        self.pos = offset as usize;
97        Ok(self.pos as u64)
98    }
99
100    fn stream_position(&mut self) -> io::Result<u64> {
101        Ok(self.pos as u64)
102    }
103}