queen_core/service/
bufstream.rs

1use std::io::Read;
2use std::io::Write;
3use std::io::Result as IoResult;
4use std::cmp;
5use std::mem;
6
7const DEFAULT_CAPACITY: usize = 16 * 1024;
8
9pub struct Stream {
10    pub reader: Vec<u8>,
11    pub writer: Vec<u8>,
12}
13
14impl Stream {
15    pub fn new() -> Stream {
16        Stream::with_capacity(DEFAULT_CAPACITY)
17    }
18
19    pub fn with_capacity(capacity: usize) -> Stream {
20        Stream {
21            reader: Vec::with_capacity(capacity),
22            writer: Vec::with_capacity(capacity)
23        }
24    }
25}
26
27impl Read for Stream {
28    #[inline]
29    fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
30        let amt = cmp::min(buf.len(), self.reader.len());
31        
32        let reader = mem::replace(&mut self.reader, Vec::new());
33        let (a, b) = reader.split_at(amt);
34        buf[..amt].copy_from_slice(a);
35        self.reader = b.to_vec();
36        
37        Ok(amt)
38    }
39}
40
41impl Write for Stream {
42    #[inline]
43    fn write(&mut self, data: &[u8]) -> IoResult<usize> {
44        self.writer.write(data)
45    }
46
47    fn flush(&mut self) -> IoResult<()> {
48        Ok(())
49    }
50}
51