1use std::collections::BTreeMap;
4use std::fs;
5use std::path::PathBuf;
6
7#[derive(Clone, Debug, PartialEq, Eq)]
10pub(crate) enum Files {
11 Embedded(&'static [(&'static str, &'static [u8])]),
13 Folder(PathBuf),
15 Owned(BTreeMap<String, Vec<u8>>),
17}
18
19impl Files {
20 #[must_use]
22 pub(crate) fn read(&self, path: &str) -> Option<Vec<u8>> {
23 match self {
24 Self::Embedded(files) => files
25 .binary_search_by(|(name, _)| (*name).cmp(path))
26 .ok()
27 .map(|found| files[found].1.to_vec()),
28 Self::Folder(folder) => {
29 let file = path
30 .split('/')
31 .fold(folder.clone(), |file, part| file.join(part));
32 file.is_file().then(|| fs::read(file).ok()).flatten()
33 }
34 Self::Owned(files) => files.get(path).cloned(),
35 }
36 }
37}
38
39#[cfg(test)]
40mod tests {
41 use super::*;
42
43 const EMBEDDED: &[(&str, &[u8])] = &[
44 ("frames/a/chunks/runtime.js", b"export {}"),
45 ("frames/a/strict.html", b"<!doctype html>"),
46 ];
47
48 #[test]
49 fn an_embedded_file_is_found_by_its_path() {
50 let files = Files::Embedded(EMBEDDED);
51 assert_eq!(
52 files.read("frames/a/strict.html"),
53 Some(b"<!doctype html>".to_vec())
54 );
55 assert_eq!(
56 files.read("frames/a/chunks/runtime.js"),
57 Some(b"export {}".to_vec())
58 );
59 assert_eq!(files.read("frames/a/chunks"), None);
60 }
61
62 #[test]
63 fn a_folders_file_is_read_and_a_folder_is_not_a_file() {
64 let folder = std::env::temp_dir().join(format!("compmd-host-files-{}", std::process::id()));
65 fs::create_dir_all(folder.join("chunks")).expect("made");
66 fs::write(folder.join("chunks").join("runtime.js"), "export {}").expect("written");
67 let files = Files::Folder(folder.clone());
68 assert_eq!(files.read("chunks/runtime.js"), Some(b"export {}".to_vec()));
69 assert_eq!(files.read("chunks"), None);
70 assert_eq!(files.read("missing.js"), None);
71 drop(fs::remove_dir_all(folder));
72 }
73
74 #[test]
75 fn owned_files_are_found_by_their_path() {
76 let files = Files::Owned(BTreeMap::from([("a.js".to_owned(), b"1".to_vec())]));
77 assert_eq!(files.read("a.js"), Some(b"1".to_vec()));
78 assert_eq!(files.read("b.js"), None);
79 }
80}