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