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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#[cfg(feature = "std")]
use alloc::borrow::ToOwned;
use alloc::rc::Rc;
use core::cell::RefCell;
#[cfg(unix)]
use std::os::unix::prelude::{AsRawFd, RawFd};
use std::{
fs::{self, remove_file, File, OpenOptions},
io::{Seek, Write},
path::{Path, PathBuf},
};
use crate::Error;
pub const INPUTFILE_STD: &str = ".cur_input";
pub fn write_file_atomic<P>(path: P, bytes: &[u8]) -> Result<(), Error>
where
P: AsRef<Path>,
{
fn inner(path: &Path, bytes: &[u8]) -> Result<(), Error> {
let mut tmpfile_name = path.to_path_buf();
tmpfile_name.set_file_name(format!(
".{}.tmp",
tmpfile_name.file_name().unwrap().to_string_lossy()
));
let mut tmpfile = OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmpfile_name)?;
tmpfile.write_all(bytes)?;
fs::rename(&tmpfile_name, path)?;
Ok(())
}
inner(path.as_ref(), bytes)
}
#[cfg(feature = "std")]
#[derive(Debug)]
pub struct InputFile {
pub path: PathBuf,
pub file: File,
pub rc: Rc<RefCell<usize>>,
}
impl Eq for InputFile {}
impl PartialEq for InputFile {
fn eq(&self, other: &Self) -> bool {
self.path == other.path
}
}
impl Clone for InputFile {
fn clone(&self) -> Self {
{
let mut rc = self.rc.borrow_mut();
assert_ne!(*rc, usize::MAX, "InputFile rc overflow");
*rc += 1;
}
Self {
path: self.path.clone(),
file: self.file.try_clone().unwrap(),
rc: self.rc.clone(),
}
}
}
#[cfg(feature = "std")]
impl InputFile {
pub fn create<P>(filename: P) -> Result<Self, Error>
where
P: AsRef<Path>,
{
let f = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&filename)?;
f.set_len(0)?;
Ok(Self {
path: filename.as_ref().to_owned(),
file: f,
rc: Rc::new(RefCell::new(1)),
})
}
#[must_use]
#[cfg(unix)]
pub fn as_raw_fd(&self) -> RawFd {
self.file.as_raw_fd()
}
pub fn write_buf(&mut self, buf: &[u8]) -> Result<(), Error> {
self.rewind()?;
self.file.write_all(buf)?;
self.file.set_len(buf.len() as u64)?;
self.file.flush()?;
self.rewind()
}
#[inline]
pub fn rewind(&mut self) -> Result<(), Error> {
if let Err(err) = self.file.rewind() {
Err(err.into())
} else {
Ok(())
}
}
}
#[cfg(feature = "std")]
impl Drop for InputFile {
fn drop(&mut self) {
let mut rc = self.rc.borrow_mut();
assert_ne!(*rc, 0, "InputFile rc should never be 0");
*rc -= 1;
if *rc == 0 {
drop(remove_file(&self.path));
}
}
}
#[cfg(test)]
mod test {
use std::fs;
use crate::bolts::fs::{write_file_atomic, InputFile};
#[test]
fn test_atomic_file_write() {
let path = "test_atomic_file_write.tmp";
write_file_atomic(path, b"test").unwrap();
let content = fs::read_to_string(path).unwrap();
fs::remove_file(path).unwrap();
assert_eq!(content, "test");
}
#[test]
fn test_cloned_ref() {
let mut one = InputFile::create("test_cloned_ref.tmp").unwrap();
let two = one.clone();
one.write_buf("Welp".as_bytes()).unwrap();
drop(one);
assert_eq!("Welp", fs::read_to_string(two.path.as_path()).unwrap());
}
}