use std::io::{Read, Seek};
pub const MAX_UNCOMPRESSED_SIZE: u64 = 512 * 1024 * 1024;
pub const MAX_COMPRESSION_RATIO: u64 = 100;
pub const MAX_PART_SIZE: u64 = 4 << 30;
pub fn resolve<R: Read + Seek>(zip: &zip::ZipArchive<R>, path: &str) -> Option<String> {
if zip.index_for_name(path).is_some() {
return Some(path.to_owned());
}
zip.file_names()
.find(|name| same_part_name(name, path))
.map(ToOwned::to_owned)
}
fn same_part_name(a: &str, b: &str) -> bool {
a.len() == b.len()
&& a.bytes().zip(b.bytes()).all(|(x, y)| {
let (x, y) = (
if x == b'\\' { b'/' } else { x },
if y == b'\\' { b'/' } else { y },
);
x.eq_ignore_ascii_case(&y)
})
}
#[must_use]
pub fn expansion_allowed(expanded: u64, compressed: u64, max_expanded: u64) -> bool {
expanded <= max_expanded || expanded <= compressed.saturating_mul(MAX_COMPRESSION_RATIO)
}
pub fn compressed_size<R: Read + Seek>(zip: &mut zip::ZipArchive<R>) -> u64 {
let mut total: u64 = 0;
for i in 0..zip.len() {
if let Ok(entry) = zip.by_index_raw(i) {
total = total.saturating_add(entry.compressed_size());
}
}
total
}
pub fn uncompressed_size<R: Read + Seek>(zip: &mut zip::ZipArchive<R>) -> u64 {
let mut total: u64 = 0;
for i in 0..zip.len() {
if let Ok(entry) = zip.by_index_raw(i) {
total = total.saturating_add(entry.size());
}
}
total
}
pub fn read_bytes<R: Read + Seek>(
zip: &mut zip::ZipArchive<R>,
path: &str,
) -> Result<Vec<u8>, String> {
let name = resolve(zip, path).ok_or_else(|| format!("package has no part {path:?}"))?;
let mut file = zip
.by_name(&name)
.map_err(|_| format!("package has no part {path:?}"))?;
if file.size() > MAX_PART_SIZE {
return Err(format!("part {path:?} is too large"));
}
let mut out = Vec::with_capacity(usize::try_from(file.size()).unwrap_or(0));
let declared = file.size();
file.by_ref()
.take(declared)
.read_to_end(&mut out)
.map_err(|e| format!("part {path:?}: {e}"))?;
Ok(out)
}
pub fn open_part<'a, R: Read + Seek>(
zip: &'a mut zip::ZipArchive<R>,
path: &str,
) -> Result<impl Read + 'a, String> {
let name = resolve(zip, path).ok_or_else(|| format!("package has no part {path:?}"))?;
let file = zip
.by_name(&name)
.map_err(|_| format!("package has no part {path:?}"))?;
if file.size() > MAX_PART_SIZE {
return Err(format!("part {path:?} is too large"));
}
let declared = file.size();
Ok(file.take(declared))
}
pub fn read_part<R: Read + Seek>(
zip: &mut zip::ZipArchive<R>,
path: &str,
) -> Result<String, String> {
let name = resolve(zip, path).ok_or_else(|| format!("package has no part {path:?}"))?;
let mut file = zip
.by_name(&name)
.map_err(|_| format!("package has no part {path:?}"))?;
if file.size() > MAX_PART_SIZE {
return Err(format!("part {path:?} is too large"));
}
let mut text = String::with_capacity(usize::try_from(file.size()).unwrap_or(0));
let declared = file.size();
file.by_ref()
.take(declared)
.read_to_string(&mut text)
.map_err(|e| format!("part {path:?}: {e}"))?;
Ok(text)
}
pub fn is_true(value: &str) -> bool {
value == "1" || value == "true"
}
pub fn attr(e: &quick_xml::events::BytesStart<'_>, name: &str) -> Option<String> {
e.attributes()
.flatten()
.find(|a| a.key.local_name().as_ref() == name)
.map(|a| {
a.normalized_value(quick_xml::XmlVersion::Implicit1_0)
.unwrap_or_default()
.into_owned()
})
}
pub fn attrs(e: &quick_xml::events::BytesStart<'_>) -> Vec<(String, String)> {
e.attributes()
.flatten()
.map(|a| {
(
a.key.local_name().as_ref().to_owned(),
a.normalized_value(quick_xml::XmlVersion::Implicit1_0)
.unwrap_or_default()
.into_owned(),
)
})
.collect()
}
pub fn push_entity(out: &mut String, r: &quick_xml::events::BytesRef<'_>) {
let name = r.xml10_content();
if let Some(text) = quick_xml::escape::resolve_predefined_entity(&name) {
out.push_str(text);
return;
}
let code = match name.strip_prefix('#') {
Some(hex) if hex.starts_with(['x', 'X']) => u32::from_str_radix(&hex[1..], 16).ok(),
Some(dec) => dec.parse().ok(),
None => None,
};
if let Some(c) = code.and_then(char::from_u32) {
out.push(c);
}
}