craft-odf: taking inline items out of a flat document is linear (#2219) (#2237)

take_out searched the whole rest of the document for the next picture and the next inline
object on every item, so a document with many of one kind and none (or few) of the other cost
items × size. It now keeps where the next of each is and searches for a kind again only once
it has been passed. The output is the same.
This commit is contained in:
Hamza Naveed
2026-11-18 15:23:21 -05:00
committed by GitHub
parent 82fc745154
commit bd5c93cf50
2 changed files with 72 additions and 10 deletions
+50 -10
View File
@@ -116,34 +116,74 @@ fn inline_object(xml: &str) -> Option<usize> {
None
}
const PICTURE: &str = "<office:binary-data>";
#[cfg(test)]
thread_local! {
/// Bytes the searches for inline pictures and objects looked through on this thread (tests:
/// the work is linear in the document, #2219).
pub(crate) static SCANNED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Notes that a search looked through `xml[from..to]` (counted in tests only).
fn scanned(from: usize, to: usize) {
#[cfg(test)]
SCANNED.with(|s| s.set(s.get().saturating_add(to.saturating_sub(from))));
#[cfg(not(test))]
let _ = (from, to);
}
/// Where the next inline picture's data (`<office:binary-data>`) starts at or after `from`.
fn next_picture(xml: &str, from: usize) -> Option<usize> {
let found = xml.get(from..).and_then(|r| r.find(PICTURE)).map(|i| from + i);
scanned(from, found.map_or(xml.len(), |i| i + PICTURE.len()));
found
}
/// Where the next inline object ([`inline_object`]) starts at or after `from`.
fn next_object(xml: &str, from: usize) -> Option<usize> {
let found = xml.get(from..).and_then(inline_object).map(|i| from + i);
scanned(from, found.map_or(xml.len(), |i| i + "<draw:object".len()));
found
}
/// `xml` with its inline pictures and formulas moved into `files` (named as a package names
/// them) and pointed at there, as a package's content holds them.
fn take_out(xml: &str, files: &mut Vec<(String, Vec<u8>)>, folders: &mut Vec<(String, String)>, max_entry: u64) -> String {
let mut out = String::with_capacity(xml.len());
let mut rest = xml;
// How far `xml` has been copied or taken out.
let mut pos = 0;
// The next picture and the next inline object, each searched for again only once `pos` has
// passed it: searching the whole rest for both on every pass made a document with many of
// one and none of the other quadratic (#2219).
let (mut pic, mut obj) = (next_picture(xml, 0), next_object(xml, 0));
loop {
let pic = rest.find("<office:binary-data>");
let obj = inline_object(rest);
if pic.is_some_and(|p| p < pos) {
pic = next_picture(xml, pos);
}
if obj.is_some_and(|o| o < pos) {
obj = next_object(xml, pos);
}
let (at, picture) = match (pic, obj) {
(Some(p), Some(o)) if o < p => (o, false),
(Some(p), _) => (p, true),
(None, Some(o)) => (o, false),
(None, None) => break,
};
let (before, from) = rest.split_at(at);
let (Some(before), Some(from)) = (xml.get(pos..at), xml.get(at..)) else { break };
let close = if picture { "</office:binary-data>" } else { "</draw:object>" };
let Some(end) = from.find(close) else {
out.push_str(before);
rest = from;
pos = at;
break;
};
let open_len = if picture { "<office:binary-data>".len() } else { from.find('>').map_or(0, |e| e + 1) };
let open_len = if picture { PICTURE.len() } else { from.find('>').map_or(0, |e| e + 1) };
let body = from.get(open_len..end).unwrap_or("");
let after = from.get(end + close.len()..).unwrap_or("");
let after = (at + end + close.len()).min(xml.len());
let n = files.len() + 1;
if files.len() >= MAX_INLINE {
out.push_str(before);
rest = after;
pos = after;
continue;
}
if picture {
@@ -187,9 +227,9 @@ fn take_out(xml: &str, files: &mut Vec<(String, Vec<u8>)>, folders: &mut Vec<(St
None => files.push((format!("{dir}/content.xml"), body.as_bytes().to_vec())),
}
}
rest = after;
pos = after;
}
out.push_str(rest);
out.push_str(xml.get(pos..).unwrap_or(""));
out
}
+22
View File
@@ -369,6 +369,28 @@ fn hostile_flat_documents_do_not_panic() {
assert_eq!(flat::from_package(&zip_of(&[("content.xml", b"<a/>")]), &Limits::DEFAULT), Err(Error::Flat("the package has no media type")));
}
/// #2219: taking the inline objects and pictures out of a flat document looks through it a
/// bounded number of times, not once per item. A document of only objects (or only pictures)
/// searched its whole rest for the other kind on every item.
#[test]
fn taking_inline_items_out_is_linear() {
let cost = |item: &str, n: usize| {
let xml = format!("<office:document><office:body>{}</office:body></office:document>", item.repeat(n));
flat::SCANNED.with(|s| s.set(0));
let doc = flat::split(xml.as_bytes(), &Limits::DEFAULT).unwrap();
(flat::SCANNED.with(|s| s.get()), doc.files.len(), xml.len())
};
let object = "<draw:object><math:math/></draw:object>";
let picture = "<draw:frame><draw:image><office:binary-data>iVBORw0KGgo=</office:binary-data></draw:image></draw:frame>";
for item in [object, picture] {
let (small, files, _) = cost(item, 1_000);
let (large, more_files, len) = cost(item, 2_000);
assert_eq!((files, more_files), (1_000, 2_000), "every item is taken out");
assert!(large <= 3 * len, "{large} bytes searched in a document of {len}");
assert!(large < 3 * small, "twice the items, {small} then {large} bytes searched");
}
}
/// Two files of one name: `zip` keeps one, and which one the writer meant is not known.
#[test]
fn two_files_of_one_name_are_refused() {