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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
use std::collections::HashMap;
use std::ffi::NulError;
use std::fs::OpenOptions;
use std::io::{BufRead, BufReader, Write};
use std::path::Path;
use std::{fmt, io};
#[derive(Debug)]
pub struct PortMetadataFile<P: AsRef<Path>> {
path: P,
}
impl<P: AsRef<Path>> PortMetadataFile<P> {
pub fn open(
path: P,
port_metadata: &HashMap<String, u16>,
) -> Result<PortMetadataFile<P>, Error> {
let port_metadata = serde_json::to_string(&port_metadata)
.unwrap_or_else(|_| panic!("failed to serialize {:?}", port_metadata));
let mut file = OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(&path)?;
write!(file, "{port_metadata}")?;
Ok(PortMetadataFile { path })
}
pub fn open_existing(path: P) -> PortMetadataFile<P> {
assert!(
path.as_ref().exists(),
"missing port metadata file: {}",
path.as_ref().as_os_str().to_str().unwrap()
);
PortMetadataFile { path }
}
pub fn read(path: P) -> Result<HashMap<String, u16>, Error> {
let file = OpenOptions::new().read(true).open(path)?;
let reader = BufReader::new(file);
let port_metadata = reader.lines().next().expect("empty port metadata file")?;
Ok(serde_json::from_str(port_metadata.as_str()).expect("malformed port metadata"))
}
}
impl<P: AsRef<Path>> Drop for PortMetadataFile<P> {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
if let Some(parent_path) = self.path.as_ref().parent() {
let _ = std::fs::File::open(parent_path).and_then(|h| h.sync_all());
}
}
}
#[derive(Debug)]
pub enum Error {
Io(io::Error),
Nul(NulError),
}
impl From<NulError> for Error {
fn from(e: NulError) -> Error {
Error::Nul(e)
}
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Self {
Error::Io(e)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::Io(e) => write!(f, "unable to open port metadata file: {}", e),
Error::Nul(e) => write!(f, "port metadata file path contained null bytes: {}", e),
}
}
}
impl std::error::Error for Error {}