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
use crate::{fmt, Debug, Display, Formatter, Outcome};
use std::error;
use std::fs;
use std::io;
#[derive(Clone, Debug)]
pub struct File<'a> {
path: String,
explorer: &'a dyn Explorer,
}
impl<'a> File<'a> {
pub fn new(explorer: &'a dyn Explorer, path: String) -> Self {
Self { path, explorer }
}
pub(crate) fn read(&self) -> Outcome<String> {
self.explorer.read(&self.path)
}
pub(crate) fn write(&self, data: &str) -> Outcome<()> {
self.explorer.write(&self.path, data)
}
}
impl Default for File<'_> {
fn default() -> Self {
Self {
path: String::new(),
explorer: &Local,
}
}
}
pub trait Explorer: Debug {
fn read(&self, path: &str) -> Outcome<String>;
fn write(&self, path: &str, data: &str) -> Outcome<()>;
}
#[derive(Debug)]
pub(crate) struct Local;
impl Explorer for Local {
fn read(&self, path: &str) -> Outcome<String> {
Ok(fs::read_to_string(path).map(|data| data.replace('\r', ""))?)
}
fn write(&self, path: &str, data: &str) -> Outcome<()> {
fs::write(path, data)?;
Ok(())
}
}
#[derive(Clone, Copy, Debug)]
pub struct Error {
kind: io::ErrorKind,
}
impl error::Error for Error {}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "IO Error")
}
}
impl From<io::Error> for Error {
fn from(value: io::Error) -> Self {
Self { kind: value.kind() }
}
}