Newer
Older
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
use alloc::string::String;
use alloc::vec::Vec;
use c_str::CStr;
use fs::File;
use header::fcntl;
use io::{self, BufRead, BufReader};
pub enum Separator {
Character(char),
Whitespace,
}
pub struct Db<R: BufRead> {
reader: R,
separator: Separator,
}
impl<R: BufRead> Db<R> {
pub fn new(reader: R, separator: Separator) -> Self {
Db {
reader,
separator
}
}
pub fn read(&mut self) -> io::Result<Option<Vec<String>>> {
let mut line = String::new();
if self.reader.read_line(&mut line)? == 0 {
return Ok(None);
}
let vec = if let Some(not_comment) = line.trim().split('#').next() {
match self.separator {
Separator::Character(c) => not_comment.split(c).map(String::from).collect(),
Separator::Whitespace => not_comment.split_whitespace().map(String::from).collect(),
}
} else {
Vec::new()
};
Ok(Some(vec))
}
}
pub type FileDb = Db<BufReader<File>>;
impl FileDb {
pub fn open(path: &CStr, separator: Separator) -> io::Result<Self> {
let file = File::open(path, fcntl::O_RDONLY | fcntl::O_CLOEXEC)?;
Ok(Db::new(
BufReader::new(file),
separator
))
}
}