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
use std::collections::LinkedList;
use std::{io};
use std::io::{Error, ErrorKind, SeekFrom};
use crate::chunk::{Chunk, CHUNK_SIZE};
use crate::list::MoveTo;

pub struct Buffer {
    chunks: LinkedList<Chunk>,
    pos: usize,
}

impl Buffer {
    pub fn new() -> Buffer {
        Buffer {
            chunks: LinkedList::new(),
            pos: 0,
        }
    }

    fn grow_to(&mut self, index: usize) -> io::Result<()> {
        let chunk_index = index / CHUNK_SIZE;

        // check if already allocated
        let capacity = self.chunks.len();
        if chunk_index < capacity {
            return Ok(())
        }

        for _ in capacity..chunk_index {
            self.chunks.push_back(Chunk::new()?);
        }

        Ok(())
    }

    pub fn len(&mut self) -> usize {
        if self.chunks.is_empty() { 0 } else {
            let last = self.chunks.back().unwrap();
            (self.chunks.len() - 1) * CHUNK_SIZE + last.len()
        }
    }

    pub fn pop_front(&mut self) -> Option<Chunk> {
        self.pos = if self.pos > CHUNK_SIZE {self.pos - CHUNK_SIZE} else { 0 };
        self.chunks.pop_front()
    }
}

impl io::Write for Buffer {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        // ensure size
        self.grow_to(self.pos + buf.len() - 1)?;

        let mut iter = self.chunks.cursor_back_mut();

        for i in 0..buf.len() {
            let cursor = self.pos + i;
            let chunk_index = cursor / CHUNK_SIZE;
            let byte_index = cursor % CHUNK_SIZE;

            iter.move_to(chunk_index);
            iter.current().as_mut().unwrap().set(byte_index, buf[i])
        }

        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}


impl io::Seek for Buffer {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        let offset = match pos {
            SeekFrom::Start(offset) => offset as i64,
            SeekFrom::End(n) => self.len() as i64 + n,
            SeekFrom::Current(n) => self.pos as i64 + n
        };

        if offset < 0 {
            return Err(Error::new(ErrorKind::InvalidInput, "Seeking before start of buffer!"));
        }

        let trunc = offset as usize;
        if trunc as i64 != offset {
            return Err(Error::new(ErrorKind::OutOfMemory, "Tried seeking past the memory limit!"));
        }

        self.pos = offset as usize;
        Ok(self.pos as u64)
    }
}