Skip to main content

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