next_rust_server/
embed.rs1#[derive(Debug, Clone, Copy)]
9pub struct EmbeddedFile {
10 pub path: &'static str,
11 pub bytes: &'static [u8],
12 pub hash: &'static str,
15}
16
17#[derive(Debug, Clone, Copy, Default)]
19pub struct Embedded {
20 pub config: Option<(&'static str, bool)>,
22 pub built_at: u64,
24 pub public: &'static [EmbeddedFile],
26 pub assets: &'static [EmbeddedFile],
28 pub client: &'static [EmbeddedFile],
30}
31
32impl Embedded {
33 pub fn is_empty(&self) -> bool {
34 self.config.is_none() && self.public.is_empty() && self.assets.is_empty() && self.client.is_empty()
35 }
36}
37
38pub fn find(files: &'static [EmbeddedFile], url_path: &str) -> Option<&'static EmbeddedFile> {
41 let mut rel = String::new();
42 for raw in url_path.split('/').filter(|s| !s.is_empty()) {
43 let seg = next_rust_router::decode_segment(raw)?;
44 if seg.starts_with('.') || seg.contains(['\\', '\0', '/', ':']) {
45 return None;
46 }
47 if !rel.is_empty() {
48 rel.push('/');
49 }
50 rel.push_str(&seg);
51 }
52 if rel.is_empty() {
53 return None;
54 }
55 files.binary_search_by(|f| f.path.cmp(rel.as_str())).ok().map(|i| &files[i])
56}
57
58#[cfg(test)]
59mod tests {
60 use super::*;
61
62 const FILES: &[EmbeddedFile] = &[
63 EmbeddedFile { path: "favicon.svg", bytes: b"<svg/>", hash: "a" },
64 EmbeddedFile { path: "images/logo space.png", bytes: b"png", hash: "b" },
65 EmbeddedFile { path: "robots.txt", bytes: b"ok", hash: "c" },
66 ];
67
68 #[test]
69 fn lookups_follow_disk_rules() {
70 assert_eq!(find(FILES, "/favicon.svg").map(|f| f.hash), Some("a"));
71 assert_eq!(find(FILES, "/images/logo%20space.png").map(|f| f.hash), Some("b"));
72 assert_eq!(find(FILES, "//robots.txt").map(|f| f.hash), Some("c"));
73 for bad in ["/", "/images", "/../robots.txt", "/.env", "/images%2Flogo%20space.png", "/nope.txt"] {
74 assert!(find(FILES, bad).is_none(), "{bad}");
75 }
76 }
77}