#[derive(Debug, Clone, Copy)]
pub struct EmbeddedFile {
pub path: &'static str,
pub bytes: &'static [u8],
pub hash: &'static str,
pub br: Option<&'static [u8]>,
pub gz: Option<&'static [u8]>,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Embedded {
pub config: Option<(&'static str, bool)>,
pub built_at: u64,
pub public: &'static [EmbeddedFile],
pub assets: &'static [EmbeddedFile],
pub client: &'static [EmbeddedFile],
}
impl Embedded {
pub fn is_empty(&self) -> bool {
self.config.is_none() && self.public.is_empty() && self.assets.is_empty() && self.client.is_empty()
}
}
pub fn find(files: &'static [EmbeddedFile], url_path: &str) -> Option<&'static EmbeddedFile> {
let mut rel = String::new();
for raw in url_path.split('/').filter(|s| !s.is_empty()) {
let seg = next_rust_router::decode_segment(raw)?;
if seg.starts_with('.') || seg.contains(['\\', '\0', '/', ':']) {
return None;
}
if !rel.is_empty() {
rel.push('/');
}
rel.push_str(&seg);
}
if rel.is_empty() {
return None;
}
files.binary_search_by(|f| f.path.cmp(rel.as_str())).ok().map(|i| &files[i])
}
#[cfg(test)]
mod tests {
use super::*;
const FILES: &[EmbeddedFile] = &[
EmbeddedFile { path: "favicon.svg", bytes: b"<svg/>", hash: "a", br: None, gz: None },
EmbeddedFile { path: "images/logo space.png", bytes: b"png", hash: "b", br: None, gz: None },
EmbeddedFile { path: "robots.txt", bytes: b"ok", hash: "c", br: None, gz: None },
];
#[test]
fn lookups_follow_disk_rules() {
assert_eq!(find(FILES, "/favicon.svg").map(|f| f.hash), Some("a"));
assert_eq!(find(FILES, "/images/logo%20space.png").map(|f| f.hash), Some("b"));
assert_eq!(find(FILES, "//robots.txt").map(|f| f.hash), Some("c"));
for bad in ["/", "/images", "/../robots.txt", "/.env", "/images%2Flogo%20space.png", "/nope.txt"] {
assert!(find(FILES, bad).is_none(), "{bad}");
}
}
}