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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
//! This module contains the standard I/O streams, i.e. “emulated”
//! `stdin`, `stdout` and `stderr`.

use crate::{FileDescriptor, FsError, Result, VirtualFile};
use std::io::{self, Read, Seek, Write};

macro_rules! impl_virtualfile_on_std_streams {
    ($name:ident { readable: $readable:expr, writable: $writable:expr $(,)* }) => {
        /// A wrapper type around the standard I/O stream of the same
        /// name that implements `VirtualFile`.
        #[derive(Debug, Default)]
        pub struct $name {
            pub buf: Vec<u8>,
        }

        impl $name {
            const fn is_readable(&self) -> bool {
                $readable
            }

            const fn is_writable(&self) -> bool {
                $writable
            }
        }

        impl VirtualFile for $name {
            fn last_accessed(&self) -> u64 {
                0
            }

            fn last_modified(&self) -> u64 {
                0
            }

            fn created_time(&self) -> u64 {
                0
            }

            fn size(&self) -> u64 {
                0
            }

            fn set_len(&mut self, _new_size: u64) -> Result<()> {
                Err(FsError::PermissionDenied)
            }

            fn unlink(&mut self) -> Result<()> {
                Ok(())
            }

            fn bytes_available(&self) -> Result<usize> {
                unimplemented!();
            }

            fn get_fd(&self) -> Option<FileDescriptor> {
                None
            }
        }

        impl_virtualfile_on_std_streams!(impl Seek for $name);
        impl_virtualfile_on_std_streams!(impl Read for $name);
        impl_virtualfile_on_std_streams!(impl Write for $name);
    };

    (impl Seek for $name:ident) => {
        impl Seek for $name {
            fn seek(&mut self, _pos: io::SeekFrom) -> io::Result<u64> {
                Err(io::Error::new(
                    io::ErrorKind::PermissionDenied,
                    concat!("cannot seek `", stringify!($name), "`"),
                ))
            }
        }
    };

    (impl Read for $name:ident) => {
        impl Read for $name {
            fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
                if self.is_readable() {
                    let length = self.buf.as_slice().read(buf)?;

                    // Remove what has been consumed.
                    self.buf.drain(..length);

                    Ok(length)
                } else {
                    Err(io::Error::new(
                        io::ErrorKind::PermissionDenied,
                        concat!("cannot read from `", stringify!($name), "`"),
                    ))
                }
            }

            fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
                if self.is_readable() {
                    let length = self.buf.as_slice().read_to_end(buf)?;

                    // Remove what has been consumed.
                    self.buf.clear();

                    Ok(length)
                } else {
                    Err(io::Error::new(
                        io::ErrorKind::PermissionDenied,
                        concat!("cannot read from `", stringify!($name), "`"),
                    ))
                }
            }

            fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
                if self.is_readable() {
                    let length = self.buf.as_slice().read_to_string(buf)?;

                    // Remove what has been consumed.
                    self.buf.drain(..length);

                    Ok(length)
                } else {
                    Err(io::Error::new(
                        io::ErrorKind::PermissionDenied,
                        concat!("cannot read from `", stringify!($name), "`"),
                    ))
                }
            }

            fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
                if self.is_readable() {
                    self.buf.as_slice().read_exact(buf)?;

                    self.buf.drain(..buf.len());

                    Ok(())
                } else {
                    Err(io::Error::new(
                        io::ErrorKind::PermissionDenied,
                        concat!("cannot read from `", stringify!($name), "`"),
                    ))
                }
            }
        }
    };

    (impl Write for $name:ident) => {
        impl Write for $name {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                if self.is_writable() {
                    self.buf.write(buf)
                } else {
                    Err(io::Error::new(
                        io::ErrorKind::PermissionDenied,
                        concat!("cannot write to `", stringify!($name), "`"),
                    ))
                }
            }

            fn flush(&mut self) -> io::Result<()> {
                if self.is_writable() {
                    self.buf.flush()
                } else {
                    Err(io::Error::new(
                        io::ErrorKind::PermissionDenied,
                        concat!("cannot flush `", stringify!($name), "`"),
                    ))
                }
            }

            fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
                if self.is_writable() {
                    self.buf.write_all(buf)
                } else {
                    Err(io::Error::new(
                        io::ErrorKind::PermissionDenied,
                        concat!("cannot write to `", stringify!($name), "`"),
                    ))
                }
            }
        }
    };
}

impl_virtualfile_on_std_streams!(Stdin {
    readable: true,
    writable: false,
});
impl_virtualfile_on_std_streams!(Stdout {
    readable: false,
    writable: true,
});
impl_virtualfile_on_std_streams!(Stderr {
    readable: false,
    writable: true,
});

#[cfg(test)]
mod test_read_write_seek {
    use crate::mem_fs::*;
    use std::io::{self, Read, Seek, Write};

    #[test]
    fn test_read_stdin() {
        let mut stdin = Stdin {
            buf: vec![b'f', b'o', b'o', b'b', b'a', b'r'],
        };
        let mut buffer = [0; 3];

        assert!(
            matches!(stdin.read(&mut buffer), Ok(3)),
            "reading bytes from `stdin`",
        );
        assert_eq!(
            buffer,
            [b'f', b'o', b'o'],
            "checking the bytes read from `stdin`"
        );

        let mut buffer = Vec::new();

        assert!(
            matches!(stdin.read_to_end(&mut buffer), Ok(3)),
            "reading bytes again from `stdin`",
        );
        assert_eq!(
            buffer,
            &[b'b', b'a', b'r'],
            "checking the bytes read from `stdin`"
        );

        let mut buffer = [0; 1];

        assert!(
            stdin.read_exact(&mut buffer).is_err(),
            "cannot read bytes again because `stdin` has fully consumed",
        );
    }

    #[test]
    fn test_write_stdin() {
        let mut stdin = Stdin { buf: vec![] };

        assert!(stdin.write(b"bazqux").is_err(), "cannot write into `stdin`");
    }

    #[test]
    fn test_seek_stdin() {
        let mut stdin = Stdin {
            buf: vec![b'f', b'o', b'o', b'b', b'a', b'r'],
        };

        assert!(
            stdin.seek(io::SeekFrom::End(0)).is_err(),
            "cannot seek `stdin`",
        );
    }

    #[test]
    fn test_read_stdout() {
        let mut stdout = Stdout {
            buf: vec![b'f', b'o', b'o', b'b', b'a', b'r'],
        };
        let mut buffer = String::new();

        assert!(
            stdout.read_to_string(&mut buffer).is_err(),
            "cannot read from `stdout`"
        );
    }

    #[test]
    fn test_write_stdout() {
        let mut stdout = Stdout { buf: vec![] };

        assert!(
            matches!(stdout.write(b"baz"), Ok(3)),
            "writing into `stdout`",
        );
        assert!(
            matches!(stdout.write(b"qux"), Ok(3)),
            "writing again into `stdout`",
        );
        assert_eq!(
            stdout.buf,
            &[b'b', b'a', b'z', b'q', b'u', b'x'],
            "checking the content of `stdout`",
        );
    }

    #[test]
    fn test_seek_stdout() {
        let mut stdout = Stdout {
            buf: vec![b'f', b'o', b'o', b'b', b'a', b'r'],
        };

        assert!(
            stdout.seek(io::SeekFrom::End(0)).is_err(),
            "cannot seek `stdout`",
        );
    }

    #[test]
    fn test_read_stderr() {
        let mut stderr = Stderr {
            buf: vec![b'f', b'o', b'o', b'b', b'a', b'r'],
        };
        let mut buffer = String::new();

        assert!(
            stderr.read_to_string(&mut buffer).is_err(),
            "cannot read from `stderr`"
        );
    }

    #[test]
    fn test_write_stderr() {
        let mut stderr = Stderr { buf: vec![] };

        assert!(
            matches!(stderr.write(b"baz"), Ok(3)),
            "writing into `stderr`",
        );
        assert!(
            matches!(stderr.write(b"qux"), Ok(3)),
            "writing again into `stderr`",
        );
        assert_eq!(
            stderr.buf,
            &[b'b', b'a', b'z', b'q', b'u', b'x'],
            "checking the content of `stderr`",
        );
    }

    #[test]
    fn test_seek_stderr() {
        let mut stderr = Stderr {
            buf: vec![b'f', b'o', b'o', b'b', b'a', b'r'],
        };

        assert!(
            stderr.seek(io::SeekFrom::End(0)).is_err(),
            "cannot seek `stderr`",
        );
    }
}