tokio_mockstream/
lib.rs

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
//! A fake stream for testing network applications backed by buffers.
#![warn(missing_docs)]

extern crate futures;
extern crate tokio_io;

use std::io;
use std::io::{Cursor, Read, Write};
use futures::Poll;
use tokio_io::{AsyncRead, AsyncWrite};

/// A fake stream for testing network applications backed by buffers.
#[derive(Clone, Debug)]
pub struct MockStream {
    written: Cursor<Vec<u8>>,
    received: Cursor<Vec<u8>>,
}

impl MockStream {
    /// Creates a new mock stream with nothing to read.
    pub fn empty() -> MockStream {
        MockStream::new(&[])
    }

    /// Creates a new mock stream with the specified bytes to read.
    pub fn new(initial: &[u8]) -> MockStream {
        MockStream {
            written: Cursor::new(vec![]),
            received: Cursor::new(initial.to_owned()),
        }
    }

    /// Gets a slice of bytes representing the data that has been written.
    pub fn written(&self) -> &[u8] {
        self.written.get_ref()
    }

    /// Gets a slice of bytes representing the data that has been received.
    pub fn received(&self) -> &[u8] {
        self.received.get_ref()
    }
}

impl Read for MockStream {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.received.read(buf)
    }
}

impl AsyncRead for MockStream {}

impl Write for MockStream {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.written.write(buf)
    }

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

impl AsyncWrite for MockStream {
    fn shutdown(&mut self) -> Poll<(), io::Error> {
        self.written.shutdown()
    }
}

#[cfg(test)]
mod tests;