parsec_interface/requests/
utils.rs

1// Copyright 2019 Contributors to the Parsec project.
2// SPDX-License-Identifier: Apache-2.0
3//! Module containing helper macros and functions used in tests.
4#![macro_use]
5macro_rules! get_from_stream {
6    ($stream:expr, $type:ty) => {
7        match &mut $stream {
8            stream => {
9                let mut read_bytes = [0_u8; std::mem::size_of::<$type>()];
10                stream.read_exact(&mut read_bytes)?;
11                <$type>::from_le_bytes(read_bytes)
12            }
13        }
14    };
15    ($stream:expr; $size:expr) => {
16        match (&mut $stream, $size) {
17            (stream, size) => {
18                let mut read_bytes = vec![0; size];
19                stream.read_exact(&mut read_bytes)?;
20                read_bytes
21            }
22        }
23    };
24}
25
26#[cfg(test)]
27pub mod tests {
28    use std::io::{Error, ErrorKind, Read, Result, Write};
29
30    #[derive(Debug)]
31    pub struct MockReadWrite {
32        pub buffer: Vec<u8>,
33    }
34
35    impl Read for MockReadWrite {
36        fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
37            for val in buf.iter_mut() {
38                *val = self.buffer.remove(0);
39            }
40
41            Ok(buf.len())
42        }
43    }
44
45    impl Write for MockReadWrite {
46        fn write(&mut self, buf: &[u8]) -> Result<usize> {
47            for val in buf.iter() {
48                self.buffer.push(*val);
49            }
50            Ok(buf.len())
51        }
52
53        fn flush(&mut self) -> Result<()> {
54            Ok(())
55        }
56    }
57
58    #[derive(Copy, Clone, Debug)]
59    pub struct MockFailReadWrite;
60
61    impl Read for MockFailReadWrite {
62        fn read(&mut self, _: &mut [u8]) -> Result<usize> {
63            Err(Error::from(ErrorKind::Other))
64        }
65    }
66
67    impl Write for MockFailReadWrite {
68        fn write(&mut self, _: &[u8]) -> Result<usize> {
69            Err(Error::from(ErrorKind::Other))
70        }
71
72        fn flush(&mut self) -> Result<()> {
73            Err(Error::from(ErrorKind::Other))
74        }
75    }
76}