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
//! Stream that reads from and writes to an owned buffer.
use crate::{BinaryError, ReadStream, BinaryResult, SeekStream, WriteStream};
use std::io::{Error, ErrorKind, Read, Write};

/// Stream that wraps an owned buffer.
pub struct MemoryStream {
    buffer: Vec<u8>,
    position: usize,
}

impl MemoryStream {
    /// Create a memory stream.
    pub fn new() -> Self {
        Self {
            buffer: Vec::new(),
            position: 0,
        }
    }
}

impl SeekStream for MemoryStream {
    fn seek(&mut self, to: usize) -> BinaryResult<usize> {
        self.position = to;
        Ok(self.position)
    }

    fn tell(&mut self) -> BinaryResult<usize> {
        Ok(self.position)
    }

    fn len(&self) -> BinaryResult<usize> {
        Ok(self.buffer.len())
    }
}

impl Read for MemoryStream {
    fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
        if self.position + buffer.len() > self.buffer.len() {
            return Err(Error::new(
                ErrorKind::UnexpectedEof,
                BinaryError::ReadPastEof,
            ));
        }

        let mut idx = 0;
        for i in self.position..self.position + buffer.len() {
            buffer[idx] = self.buffer[i];
            idx += 1;
        }

        self.position += buffer.len();

        Ok(buffer.len())
    }
}

impl Write for MemoryStream {
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        let bytes_to_end = self.buffer.len() - self.position;
        if bytes.len() > bytes_to_end {
            let bytes_out_of_buffer = bytes.len() - bytes_to_end;

            for _ in 0..bytes_out_of_buffer {
                self.buffer.push(0);
            }
        }

        let mut idx = 0;
        for i in self.position..self.position + bytes.len() {
            self.buffer[i] = bytes[idx];
            idx += 1;
        }

        self.position += bytes.len();

        Ok(bytes.len())
    }

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

impl From<Vec<u8>> for MemoryStream {
    fn from(buffer: Vec<u8>) -> Self {
        MemoryStream {
            buffer,
            position: 0,
        }
    }
}

impl Into<Vec<u8>> for MemoryStream {
    fn into(self) -> Vec<u8> {
        self.buffer
    }
}

impl ReadStream for MemoryStream {}
impl WriteStream for MemoryStream {}