Skip to main content

Mountain/Cache/AssetMemoryMap/
LoadOrInsert.rs

1
2//! Load `Path` into the cache (or return the existing entry).
3//!
4//! Returns `Err` only if the file cannot be opened or memory-mapped; missing
5//! brotli siblings are silently ignored (best-effort optimisation).
6
7use std::{
8	path::{Path, PathBuf},
9	sync::Arc,
10};
11
12use memmap2::Mmap;
13
14use crate::{
15	Cache::AssetMemoryMap::{Entry, Map, MimeFromExtension},
16	dev_log,
17};
18
19pub fn Fn(Path:&Path) -> std::io::Result<Arc<Entry::Struct>> {
20	if let Some(Existing) = Map::Fn().get(Path) {
21		return Ok(Existing.clone());
22	}
23
24	let File = std::fs::File::open(Path)?;
25
26	let Length = File.metadata()?.len() as usize;
27
28	// SAFETY: caller agrees the file is not truncated underneath us for the
29	// lifetime of the MemoryMap. The bundle directory is read-only at runtime;
30	// mutations happen at build time and require a binary restart.
31	let Mapping = unsafe { Mmap::map(&File)? };
32
33	let BrotliPath = {
34		let mut B = Path.as_os_str().to_owned();
35
36		B.push(".br");
37
38		PathBuf::from(B)
39	};
40
41	let Brotli = std::fs::File::open(&BrotliPath)
42		.ok()
43		.and_then(|F| unsafe { Mmap::map(&F).ok() });
44
45	let Mime = MimeFromExtension::Fn(Path);
46
47	let MarkerEntry = Arc::new(Entry::Struct { Mapping, Mime, Length, Brotli });
48
49	dev_log!(
50		"asset-cache",
51		"mmap insert path={} bytes={} brotli={}",
52		Path.display(),
53		Length,
54		MarkerEntry.Brotli.is_some()
55	);
56
57	Map::Fn().insert(Path.to_path_buf(), MarkerEntry.clone());
58
59	Ok(MarkerEntry)
60}