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
use std::io::ErrorKind;
use crate::error_consts::*;
pub fn read_file(filepath: &str, must_exist: bool)
-> Result<Vec<String>, &'static str>
{
match read(filepath) {
Ok(data) => Ok(data),
Err(e) => match e.kind() {
ErrorKind::PermissionDenied => Err(PERMISSION_DENIED),
ErrorKind::NotFound => {
if must_exist { Err(NOT_FOUND) }
else { Ok(Vec::with_capacity(0)) }
}
_ => {
Err(UNKNOWN)
},
},
}
}
pub fn write_file<'a>(filepath: &str, data: impl Iterator<Item = &'a str>, append: bool)
-> Result<(), &'static str>
{
write(filepath, data, append)
.map_err(|e: std::io::Error| match e.kind() {
ErrorKind::PermissionDenied => PERMISSION_DENIED,
ErrorKind::NotFound => NOT_FOUND,
_ => {
UNKNOWN
},
})
}
fn read(filepath: &str)
-> std::io::Result<Vec<String>>
{
use std::io::{BufRead, BufReader};
let mut data = Vec::new();
let file = std::fs::OpenOptions::new()
.read(true)
.open(filepath)?;
let mut reader = BufReader::new(file);
loop {
let mut line = String::new();
match reader.read_line(&mut line)?
{
0 => break,
_ => data.push(line),
}
}
Ok(data)
}
fn write<'a>(filepath: &str, data: impl Iterator<Item = &'a str>, append: bool)
-> std::io::Result<()>
{
use std::io::{BufWriter, Write};
let file = std::fs::OpenOptions::new()
.write(true)
.append(append)
.truncate(!append)
.create(true)
.open(filepath)?;
let mut writer = BufWriter::new(file);
for line in data {
writer.write_all(line.as_bytes())?;
}
writer.flush()?;
Ok(())
}