atmos/os_lib/web_engine/
cache_path.rs1extern crate alloc;
14use alloc::string::String;
15use alloc::vec::Vec;
16
17pub const MAX_CACHE_PATH_LEN: usize = 128;
19
20pub const CACHE_GZIP_MAGIC: &[u8; 4] = b"AGZ1";
22
23pub const MIN_COMPRESS_SIZE: usize = 512;
25
26pub fn cache_path_for(host: &str, path: &str) -> String {
32 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
33 for b in path.bytes() {
34 h ^= b as u64;
35 h = h.wrapping_mul(0x0000_0100_0000_01b3);
36 }
37 let safe_host: String = host
38 .chars()
39 .map(|c| if c == ':' { '-' } else { c })
40 .collect();
41 alloc::format!("/cache/browser/{}/{:016x}", safe_host, h)
42}
43
44pub fn is_already_compressed_resource(path: &str, data: &[u8]) -> bool {
46 if data.starts_with(CACHE_GZIP_MAGIC)
47 || data.starts_with(&[0x1f, 0x8b])
48 || data.starts_with(b"wOF2")
49 || data.starts_with(b"wOFF")
50 || data.starts_with(b"\x89PNG")
51 || data.starts_with(&[0xff, 0xd8, 0xff])
52 || data.starts_with(b"RIFF")
53 || data.starts_with(b"GIF8")
54 {
55 return true;
56 }
57 let clean = path.split('?').next().unwrap_or(path);
58 let lower = clean.to_ascii_lowercase();
59 lower.ends_with(".woff2")
60 || lower.ends_with(".woff")
61 || lower.ends_with(".png")
62 || lower.ends_with(".jpg")
63 || lower.ends_with(".jpeg")
64 || lower.ends_with(".webp")
65 || lower.ends_with(".gif")
66 || lower.ends_with(".mp4")
67 || lower.ends_with(".m4s")
68 || lower.ends_with(".webm")
69}
70
71pub fn pack_cache_payload(path: &str, data: &[u8]) -> Vec<u8> {
76 if data.len() < MIN_COMPRESS_SIZE || is_already_compressed_resource(path, data) {
77 return data.to_vec();
78 }
79 let compressed = crate::os_lib::deflate_enc::deflate_raw(data);
80 if compressed.len().saturating_add(8) < data.len() {
81 let mut out = Vec::with_capacity(8 + compressed.len());
82 out.extend_from_slice(CACHE_GZIP_MAGIC);
83 out.extend_from_slice(&(data.len() as u32).to_le_bytes());
84 out.extend_from_slice(&compressed);
85 out
86 } else {
87 data.to_vec()
88 }
89}
90
91pub fn unpack_cache_payload(stored: Vec<u8>) -> Option<Vec<u8>> {
93 if stored.is_empty() {
94 return None;
95 }
96 if stored.starts_with(CACHE_GZIP_MAGIC) {
97 if stored.len() < 8 {
98 return None;
99 }
100 let orig_len = u32::from_le_bytes([stored[4], stored[5], stored[6], stored[7]]) as usize;
101 if orig_len == 0 || orig_len > crate::os_lib::deflate_enc::MAX_DECOMPRESSED_BYTES {
102 return None;
103 }
104 let options = zune_inflate::DeflateOptions::default()
105 .set_limit(orig_len.saturating_add(64))
106 .set_size_hint(orig_len.saturating_add(1024));
109 let decoded = zune_inflate::DeflateDecoder::new_with_options(&stored[8..], options)
110 .decode_deflate()
111 .ok()?;
112 if decoded.len() != orig_len {
113 return None;
114 }
115 Some(decoded)
116 } else {
117 Some(stored)
118 }
119}