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
use std::{error, fmt, fmt::Write, io, path::PathBuf};
#[derive(Debug)]
pub enum Error {
FileOpen(PathBuf, io::Error),
Mmap(io::Error),
PathNotDir,
RecordExists(Vec<u8>),
DataFileDamaged,
SeqNoIndexDamaged,
Extend(io::Error),
Flush(io::Error),
Metadata(io::Error),
Protect(io::Error),
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Error::FileOpen(_, source) => Some(source),
Error::Mmap(source) => Some(source),
Error::PathNotDir => None,
Error::RecordExists(_) => None,
Error::DataFileDamaged => None,
Error::SeqNoIndexDamaged => None,
Error::Extend(source) => Some(source),
Error::Flush(source) => Some(source),
Error::Metadata(source) => Some(source),
Error::Protect(source) => Some(source),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::FileOpen(path, _) => write!(f, "failed to open file `{}`", path.display()),
Error::Mmap(_) => write!(f, "memory map failed"),
Error::PathNotDir => write!(
f,
"database path already exists and does not point to a directory"
),
Error::RecordExists(id) => write!(f, "a record with id {} already exists", hex(&id)),
Error::DataFileDamaged => write!(f, "data file looks damaged"),
Error::SeqNoIndexDamaged => write!(f, "sequential number index file looks damaged"),
Error::Extend(_) => write!(f, "failed to extend a database file"),
Error::Flush(_) => write!(f, "failed to flush database records to disk"),
Error::Metadata(_) => write!(f, "failed to get file metadata"),
Error::Protect(_) => write!(f, "failed to make a memory mapping page immutable"),
}
}
}
fn hex(bytes: &[u8]) -> String {
let mut s = String::with_capacity(bytes.len() * 2);
for byte in bytes {
write!(&mut s, "{:2x}", byte).unwrap();
}
s
}