1#[cfg(any(target_family = "windows", target_family = "unix"))]
2mod async_io;
3mod async_traits;
4mod unix;
5mod windows;
6mod windows_api;
7
8use std::{
9 env::{args, current_dir, set_current_dir, Args},
10 fs::{self, create_dir, File},
11 io::{self, Stdout},
12 time::Instant,
13};
14
15use io_trait::Io;
16
17#[derive(Default)]
18pub struct RealIo();
19
20impl Io for RealIo {
21 type Args = Args;
22
23 type Stdout = Stdout;
24 type File = File;
25 type Metadata = fs::Metadata;
26 type DirEntry = fs::DirEntry;
27 type Instant = Instant;
28
29 fn args(&self) -> Self::Args {
30 args()
31 }
32
33 fn create(&self, path: &str) -> io::Result<Self::File> {
34 File::create(path)
35 }
36
37 fn open(&self, path: &str) -> io::Result<Self::File> {
38 File::open(path)
39 }
40
41 fn metadata(&self, path: &str) -> io::Result<fs::Metadata> {
42 fs::metadata(path)
43 }
44
45 fn read_dir(&self, path: &str) -> io::Result<Vec<Self::DirEntry>> {
46 fs::read_dir(path)?.collect()
47 }
48
49 fn create_dir(&self, path: &str) -> io::Result<()> {
50 create_dir(path)
51 }
52
53 fn stdout(&self) -> Self::Stdout {
54 io::stdout()
55 }
56
57 fn now(&self) -> Instant {
58 Instant::now()
59 }
60
61 fn current_dir(&self) -> io::Result<String> {
62 current_dir().map(|x| x.to_string_lossy().to_string())
63 }
64
65 fn set_current_dir(&self, path: &str) -> io::Result<()> {
66 set_current_dir(path)
67 }
68}
69
70#[cfg(test)]
71mod test {
72 use std::{
73 fs,
74 io::{Read, Write},
75 };
76
77 use io_trait::{File, Io};
78
79 #[test]
80 fn test_arg() {
81 let io = super::RealIo::default();
82 let a = io.args().collect::<Vec<_>>();
83 assert!(a.len() > 0);
84 }
85
86 #[test]
87 fn test_file() {
88 let io = super::RealIo::default();
89 {
90 let mut file = io.create("_test_file").unwrap();
91 file.write_all(b"test").unwrap();
92 }
93 {
94 let mut file = io.open("_test_file").unwrap();
95 let mut buf = Vec::default();
96 file.read_to_end(&mut buf).unwrap();
97 let x = File::metadata(&file).unwrap();
98 assert_eq!(x.len(), 4);
99 assert!(x.is_file());
100 assert_eq!(buf, b"test");
101 }
102 io.metadata("_test_file").unwrap();
103 io.read_dir(".").unwrap();
104 fs::remove_file("_test_file").unwrap();
105 io.create_dir("_test_dir").unwrap();
106 fs::remove_dir("_test_dir").unwrap();
107 let _ = io.stdout();
108 }
109
110 #[test]
111 fn test_now() {
112 let io = super::RealIo::default();
113 let _ = io.now();
114 }
115
116 #[test]
117 fn test_current_dir() {
118 let io = super::RealIo::default();
119 let _ = io.current_dir();
120 }
121
122 #[test]
123 fn test_set_current_dir() {
124 let io = super::RealIo::default();
125 let _ = io.set_current_dir(".");
126 }
127}