1use super::*;
2use std::{
3 fs::{self, File, OpenOptions},
4 io::{Read, Write},
5 path::{Path, PathBuf},
6 sync::atomic::{AtomicU64, Ordering},
7};
8
9static NEXT_TEMP: AtomicU64 = AtomicU64::new(0);
10
11pub fn load(path: impl AsRef<Path>, limits: SaveLimits) -> Result<SaveData, SaveError> {
15 let mut file = File::open(path).map_err(|source| io_error(SaveStage::Read, source))?;
16 let metadata = file
17 .metadata()
18 .map_err(|source| io_error(SaveStage::Read, source))?;
19 if !metadata.is_file() {
20 return Err(SaveError::NotRegularFile);
21 }
22 let mut header = [0; HEADER_LEN];
23 let count = read_complete(&mut file, &mut header)?;
24 if count != HEADER_LEN {
25 return Err(SaveError::TruncatedHeader { bytes: count });
26 }
27 let (schema_version, size) = parse_header(&header, limits)?;
28 let total = (size as u64) + HEADER_LEN as u64;
29 if metadata.len() != total {
30 return Err(SaveError::LengthMismatch {
31 declared: size as u64,
32 actual: metadata.len().saturating_sub(HEADER_LEN as u64),
33 });
34 }
35 let mut payload = Vec::new();
36 payload
37 .try_reserve_exact(size)
38 .map_err(SaveError::Allocation)?;
39 payload.resize(size, 0);
40 let count = read_complete(&mut file, &mut payload)?;
41 if count != size {
42 return Err(SaveError::LengthMismatch {
43 declared: size as u64,
44 actual: count as u64,
45 });
46 }
47 if read_complete(&mut file, &mut [0])? != 0 {
48 return Err(SaveError::LengthMismatch {
49 declared: size as u64,
50 actual: size as u64 + 1,
51 });
52 }
53 verify_checksum(&header, &payload)?;
54 Ok(SaveData {
55 schema_version,
56 payload,
57 })
58}
59
60pub fn load_with<T, E>(
64 path: impl AsRef<Path>,
65 limits: SaveLimits,
66 decode: impl FnOnce(u32, &[u8]) -> Result<T, E>,
67) -> Result<T, CodecError<E>> {
68 let data = load(path, limits).map_err(CodecError::Container)?;
69 decode(data.schema_version, &data.payload).map_err(CodecError::Payload)
70}
71
72pub fn save_with<T, E>(
76 path: impl AsRef<Path>,
77 schema_version: u32,
78 value: &T,
79 options: SaveOptions,
80 encode: impl FnOnce(&T) -> Result<Vec<u8>, E>,
81) -> Result<(), CodecError<E>> {
82 let payload = encode(value).map_err(CodecError::Payload)?;
83 save(path, schema_version, &payload, options).map_err(CodecError::Container)
84}
85
86pub fn save(
96 path: impl AsRef<Path>,
97 schema_version: u32,
98 payload: &[u8],
99 options: SaveOptions,
100) -> Result<(), SaveError> {
101 save_using(
102 path.as_ref(),
103 schema_version,
104 payload,
105 options,
106 &mut NativeOps,
107 )
108}
109
110fn save_using(
111 path: &Path,
112 schema: u32,
113 payload: &[u8],
114 options: SaveOptions,
115 ops: &mut impl FileOps,
116) -> Result<(), SaveError> {
117 let header = make_header(schema, payload, options.limits)?;
118 if path.file_name().is_none() {
119 return Err(SaveError::InvalidPath);
120 }
121 let parent = path
122 .parent()
123 .filter(|p| !p.as_os_str().is_empty())
124 .unwrap_or(Path::new("."));
125 let directory = open_directory(parent, options.durability)?;
126 let mut temp = Temporary::create(parent)?;
127 let file = temp.file.as_mut().expect("temporary open");
128 ops.write(file, &header, payload)
129 .map_err(|source| io_error(SaveStage::WriteTemporary, source))?;
130 if options.durability == Durability::Durable {
131 ops.sync_file(file)
132 .map_err(|source| io_error(SaveStage::SyncTemporary, source))?;
133 }
134 drop(temp.file.take());
136 ops.rename(&temp.path, path)
137 .map_err(|source| io_error(SaveStage::Rename, source))?;
138 temp.committed = true;
139 if let Some(directory) = directory {
140 ops.sync_directory(&directory)
141 .map_err(|source| io_error(SaveStage::SyncDirectory, source))?;
142 }
143 Ok(())
144}
145
146fn open_directory(parent: &Path, durability: Durability) -> Result<Option<File>, SaveError> {
147 if durability == Durability::Atomic {
148 return Ok(None);
149 }
150 #[cfg(target_os = "linux")]
151 {
152 File::open(parent)
153 .map(Some)
154 .map_err(|source| io_error(SaveStage::OpenDirectory, source))
155 }
156 #[cfg(not(target_os = "linux"))]
157 {
158 let _ = parent;
159 Err(SaveError::UnsupportedDurability)
160 }
161}
162
163fn io_error(stage: SaveStage, source: io::Error) -> SaveError {
164 SaveError::Io { stage, source }
165}
166
167fn read_complete(file: &mut File, output: &mut [u8]) -> Result<usize, SaveError> {
168 let mut count = 0;
169 while count < output.len() {
170 match file.read(&mut output[count..]) {
171 Ok(0) => break,
172 Ok(bytes) => count += bytes,
173 Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
174 Err(source) => return Err(io_error(SaveStage::Read, source)),
175 }
176 }
177 Ok(count)
178}
179
180struct Temporary {
181 path: PathBuf,
182 file: Option<File>,
183 committed: bool,
184}
185impl Temporary {
186 fn create(parent: &Path) -> Result<Self, SaveError> {
187 for _ in 0..128 {
188 #[allow(deprecated)]
190 let id = NEXT_TEMP
191 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
192 .map_err(|_| {
193 io_error(
194 SaveStage::CreateTemporary,
195 io::Error::other("temporary name space exhausted"),
196 )
197 })?;
198 let path = parent.join(format!(
200 ".rayengine-save-{}-{id:016x}.tmp",
201 std::process::id()
202 ));
203 let mut options = OpenOptions::new();
204 options.write(true).create_new(true);
205 #[cfg(unix)]
206 {
207 use std::os::unix::fs::OpenOptionsExt;
208 options.mode(0o600);
209 }
210 match options.open(&path) {
211 Ok(file) => {
212 return Ok(Self {
213 path,
214 file: Some(file),
215 committed: false,
216 });
217 }
218 Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
219 Err(source) => return Err(io_error(SaveStage::CreateTemporary, source)),
220 }
221 }
222 Err(io_error(
223 SaveStage::CreateTemporary,
224 io::Error::new(
225 io::ErrorKind::AlreadyExists,
226 "temporary file collision limit exceeded",
227 ),
228 ))
229 }
230}
231impl Drop for Temporary {
232 fn drop(&mut self) {
233 drop(self.file.take());
234 if !self.committed {
235 let _ = fs::remove_file(&self.path);
236 }
237 }
238}
239
240trait FileOps {
243 fn write(&mut self, file: &mut File, header: &[u8], payload: &[u8]) -> io::Result<()>;
244 fn sync_file(&mut self, file: &File) -> io::Result<()>;
245 fn rename(&mut self, from: &Path, to: &Path) -> io::Result<()>;
246 fn sync_directory(&mut self, directory: &File) -> io::Result<()>;
247}
248struct NativeOps;
249impl FileOps for NativeOps {
250 fn write(&mut self, file: &mut File, header: &[u8], payload: &[u8]) -> io::Result<()> {
251 file.write_all(header)?;
252 file.write_all(payload)
253 }
254 fn sync_file(&mut self, file: &File) -> io::Result<()> {
255 file.sync_all()
256 }
257 fn rename(&mut self, from: &Path, to: &Path) -> io::Result<()> {
258 fs::rename(from, to)
259 }
260 fn sync_directory(&mut self, directory: &File) -> io::Result<()> {
261 directory.sync_all()
262 }
263}
264
265#[cfg(test)]
266mod tests;