Skip to content

ProCraft for Android: An Android native painting app written in Rust

Rust

fix(import): readers cap what a crafted file can ask for, and real Krita and Clip Studio files come in right

Joshd45260e5856c
diff --git a/apps/procraft-android/src/brush_files.rs b/apps/procraft-android/src/brush_files.rs
index 51e5277..f0e3baf 100644
--- a/apps/procraft-android/src/brush_files.rs
+++ b/apps/procraft-android/src/brush_files.rs
@@ -16,6 +16,9 @@ const IMPORTED: &str = "Imported";
/// The size of the preview a brush file carries.
const THUMBNAIL: (u32, u32) = (327, 100);
+/// The most a brush file's picture may decode to (8192 × 8192 in colour), bytes.
+const MOST_PNG_BYTES: usize = 256 << 20;
+
/// A brush file's pictures, made: the shape, the grain if any and the preview (PNGs).
struct Made {
shape: Vec<u8>,
@@ -224,11 +227,12 @@ fn other_brushes(bytes: &[u8], name: String) -> Option<(String, Vec<Brush>)> {
/// A brush of a Clip Studio sub tool: its tip (an image, else round with its edge and roundness),
/// spacing and angle.
fn csp_brush(c: &procraft_engine::csp::CspBrush) -> Brush {
- // its tips paint white, or else dark
+ // the first of its pictures that paints anything: white, or else dark
+ let paints = |t: &procraft_engine::abr::AbrTip| t.pixels.iter().any(|&v| v > 0);
let tip = c
- .tip_png
- .as_deref()
- .and_then(|png| png_tip(png, true).filter(|t| t.pixels.iter().any(|&v| v > 0)).or_else(|| png_tip(png, false)));
+ .tip_pngs
+ .iter()
+ .find_map(|png| png_tip(png, true).filter(paints).or_else(|| png_tip(png, false).filter(paints)));
let mut b = match tip {
Some(t) => tip_brush(&procraft_engine::abr::AbrTip { name: c.name.clone(), ..t }),
None => Brush { name: c.name.clone(), ..Brush::round_pen() },
@@ -240,7 +244,7 @@ fn csp_brush(c: &procraft_engine::csp::CspBrush) -> Brush {
b.shape.roundness = r.clamp(0.01, 1.0);
}
if let Some(spacing) = c.spacing {
- b.spacing = spacing.clamp(0.01, 10.0);
+ b.spacing = Brush::spacing_within_reach(spacing);
}
b.shape.rotation = c.angle;
b
@@ -252,7 +256,7 @@ fn tip_brush(t: &procraft_engine::abr::AbrTip) -> Brush {
b.shape.image = None;
b.shape.source = Source::new(fitted(t));
if let Some(spacing) = t.spacing {
- b.spacing = spacing.clamp(0.01, 10.0);
+ b.spacing = Brush::spacing_within_reach(spacing);
}
b
}
@@ -280,7 +284,7 @@ fn krita_brush(k: &procraft_engine::krita::KritaBrush) -> Brush {
b.shape.roundness = roundness.clamp(0.01, 1.0);
}
if let Some(spacing) = k.spacing {
- b.spacing = spacing.clamp(0.01, 10.0);
+ b.spacing = Brush::spacing_within_reach(spacing);
}
b.shape.rotation = k.angle;
if !k.pressure_size {
@@ -399,7 +403,8 @@ fn decode_png(bytes: &[u8]) -> Option<(usize, usize, usize, Vec<u8>)> {
let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
let mut reader = decoder.read_info().ok()?;
- let mut buf = vec![0; reader.output_buffer_size()?];
+ // a small file can claim a picture of gigabytes
+ let mut buf = vec![0; reader.output_buffer_size().filter(|n| *n <= MOST_PNG_BYTES)?];
let info = reader.next_frame(&mut buf).ok()?;
let (w, h) = (info.width as usize, info.height as usize);
(w > 0 && h > 0).then_some((w, h, info.color_type.samples(), buf))
diff --git a/crates/engine/src/csp.rs b/crates/engine/src/csp.rs
index 99b4855..a2f5577 100644
--- a/crates/engine/src/csp.rs
+++ b/crates/engine/src/csp.rs
@@ -16,13 +16,16 @@ pub struct CspBrush {
pub roundness: Option<f32>,
/// The tip's angle, radians.
pub angle: f32,
- /// The tip's image (a PNG), if it isn't round.
- pub tip_png: Option<Vec<u8>>,
+ /// The pictures (PNGs) its tip may be, largest first (one may be empty), none if it is round.
+ pub tip_pngs: Vec<Vec<u8>>,
}
-/// The most brushes read from one file, and PNGs looked at in a material.
+/// The most brushes read from one file, PNGs looked at in a material, pictures a tip may be, and
+/// bytes of them all the brushes may have together (each has its own copy).
const MOST_BRUSHES: usize = 256;
const MOST_PNGS: usize = 32;
+const MOST_TIPS: usize = 4;
+const MOST_TIP_BYTES: usize = 256 << 20;
const PNG: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
/// The brushes in a sub tool file, in its order; none if it isn't one.
@@ -36,6 +39,7 @@ pub fn read(bytes: &[u8]) -> Option<Vec<CspBrush>> {
};
// the nodes with settings of their own (a folder of sub tools has none)
let mut out = Vec::new();
+ let mut left = MOST_TIP_BYTES;
for row in &nodes.rows {
let Some(name) = named(row) else { continue };
let id = nodes.get(row, "NodeVariantID").and_then(Value::as_int);
@@ -44,7 +48,7 @@ pub fn read(bytes: &[u8]) -> Option<Vec<CspBrush>> {
.map(|r| (v, r))
});
if variant.is_some() {
- out.push(brush(&name, variant, materials.as_ref()));
+ out.push(brush(&name, variant, materials.as_ref(), &mut left));
}
if out.len() >= MOST_BRUSHES {
break;
@@ -52,23 +56,27 @@ pub fn read(bytes: &[u8]) -> Option<Vec<CspBrush>> {
}
// none: the first named node, round
if out.is_empty() {
- out.extend(nodes.rows.iter().find_map(named).map(|name| brush(&name, None, materials.as_ref())));
+ out.extend(nodes.rows.iter().find_map(named).map(|name| brush(&name, None, materials.as_ref(), &mut left)));
}
(!out.is_empty()).then_some(out)
}
-fn brush(name: &str, variant: Option<(&Table, &Vec<Value>)>, materials: Option<&Table>) -> CspBrush {
+/// A brush from its settings; its tip's pictures taken from what is `left` of the bytes they may
+/// have (round once that runs out).
+fn brush(name: &str, variant: Option<(&Table, &Vec<Value>)>, materials: Option<&Table>, left: &mut usize) -> CspBrush {
let number =
|key: &str| variant.and_then(|(t, r)| t.get(r, key)).and_then(Value::as_real).filter(|v| v.is_finite());
let pattern =
variant.and_then(|(t, r)| t.get(r, "BrushPatternImageArray")).and_then(Value::as_blob).and_then(pattern_key);
+ let mut tips = pattern.and_then(|key| materials.map(|m| material_pngs(m, &key))).unwrap_or_default();
+ tips.retain(|png| left.checked_sub(png.len()).map(|l| *left = l).is_some());
CspBrush {
name: name.to_owned(),
hardness: number("BrushHardness").filter(|v| (0.0..=100.0).contains(v)).map(|v| (v / 100.0) as f32),
spacing: number("BrushInterval").filter(|v| *v > 0.0).map(|v| (v / 100.0) as f32),
roundness: number("BrushThickness").filter(|v| (1.0..=100.0).contains(v)).map(|v| (v / 100.0) as f32),
angle: number("BrushRotation").map_or(0.0, |v| v.to_radians() as f32),
- tip_png: pattern.and_then(|key| materials.and_then(|m| material_png(m, &key))),
+ tip_pngs: tips,
}
}
@@ -86,9 +94,9 @@ fn pattern_key(blob: &[u8]) -> Option<String> {
found.into_iter().find(|s| s.contains(":data:") && s.len() >= 8)
}
-/// The largest PNG in the material `key` names (a row with it in a text column), else in one that
-/// holds a brush pattern, else in any.
-fn material_png(table: &Table, key: &str) -> Option<Vec<u8>> {
+/// The PNGs in the material `key` names (a row with it in a text column), else in one that holds a
+/// brush pattern, else in any; the [`MOST_TIPS`] largest, largest first.
+fn material_pngs(table: &Table, key: &str) -> Vec<Vec<u8>> {
let named: Vec<&Vec<Value>> =
table.rows.iter().filter(|r| r.iter().any(|v| v.as_text().is_some_and(|t| t.contains(key)))).collect();
let rows = if !named.is_empty() {
@@ -101,10 +109,11 @@ fn material_png(table: &Table, key: &str) -> Option<Vec<u8>> {
.collect();
if patterns.is_empty() { table.rows.iter().collect() } else { patterns }
};
- rows.into_iter()
- .flat_map(|r| r.iter().filter_map(Value::as_blob).flat_map(pngs))
- .max_by_key(|(area, _)| *area)
- .map(|(_, png)| png.to_vec())
+ let mut found: Vec<(u64, &[u8])> =
+ rows.into_iter().flat_map(|r| r.iter().filter_map(Value::as_blob).flat_map(pngs)).take(MOST_PNGS).collect();
+ // largest first, in the material's order where they are as large
+ found.sort_by_key(|(area, _)| std::cmp::Reverse(*area));
+ found.into_iter().take(MOST_TIPS).map(|(_, png)| png.to_vec()).collect()
}
/// The PNGs inside `bytes` (each from its signature through its end chunk), with their areas.
@@ -201,9 +210,9 @@ mod tests {
assert_eq!(b.name, "Dry Pencil");
assert_eq!((b.hardness, b.spacing, b.roundness), (Some(0.8), Some(0.25), Some(0.5)));
assert!((b.angle - std::f32::consts::FRAC_PI_2).abs() < 1e-6);
- // the material its pattern names, the larger of its two pictures
- let tip = b.tip_png.as_ref().unwrap();
- assert_eq!(&tip[16..24], &[0, 0, 0, 64, 0, 0, 0, 32]);
+ // the material its pattern names, the larger of its two pictures first
+ let sizes: Vec<&[u8]> = b.tip_pngs.iter().map(|t| &t[16..24]).collect();
+ assert_eq!(sizes, [&[0, 0, 0, 64, 0, 0, 0, 32][..], &[0, 0, 0, 4, 0, 0, 0, 4][..]]);
}
#[test]
diff --git a/crates/engine/src/gif.rs b/crates/engine/src/gif.rs
index ff80016..5f2a756 100644
--- a/crates/engine/src/gif.rs
+++ b/crates/engine/src/gif.rs
@@ -35,7 +35,9 @@ pub fn frames(bytes: &[u8], mut frame: impl FnMut(&[u8], u32) -> bool) -> Option
if stopped {
return None;
}
- let indices = lzw(data, image.min_code, usize::from(image.width) * usize::from(image.height))?;
+ // a frame may be no bigger than a canvas may (it can be bigger than its own canvas)
+ let count = u64::from(image.width) * u64::from(image.height);
+ let indices = lzw(data, image.min_code, usize::try_from(count).ok().filter(|_| count <= MOST_PIXELS)?)?;
let before = (image.disposal == 3).then(|| canvas.clone());
draw(&mut canvas, wu, hu, &image, &indices);
given += 1;
@@ -462,6 +464,15 @@ mod tests {
let g = sample();
// cut in its last frame: the two before it come
assert_eq!(frames(&g[..g.len() - 6], |_, _| true).map(|f| f.2), Some(2));
+ // a frame far bigger than any canvas (a few bytes asking for gigabytes) ends it there
+ let mut huge = b"GIF89a".to_vec();
+ huge.extend_from_slice(&[1, 0, 1, 0, 0x80, 0, 0, 0, 0, 0, 255, 255, 255]);
+ for _ in 0..2 {
+ huge.extend_from_slice(&[0x2C, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0, 2, 0]);
+ }
+ huge.push(0x3B);
+ assert_eq!(frame_count(&huge), 2);
+ assert_eq!(frames(&huge, |_, _| true).map(|f| f.2), Some(0));
crate::damaged::survives("GIF", &g, |b| {
let _ = frames(b, |_, _| true);
let _ = frame_count(b);
diff --git a/crates/engine/src/krita.rs b/crates/engine/src/krita.rs
index 67020b0..2cfd228 100644
--- a/crates/engine/src/krita.rs
+++ b/crates/engine/src/krita.rs
@@ -32,8 +32,9 @@ pub enum KritaTip {
Png(Vec<u8>),
}
-/// The most presets read from a bundle.
+/// The most presets read from a bundle, and the most bytes their tip files may come to together.
const MOST_PRESETS: usize = 512;
+const MOST_TIP_BYTES: usize = 256 << 20;
/// The most a text chunk inflates to.
const MOST_TEXT: usize = 16 << 20;
/// The side a drawn rectangular tip is made at.
@@ -81,15 +82,16 @@ pub fn read_bundle(bytes: &[u8]) -> Option<(String, Vec<KritaBrush>)> {
.and_then(|m| ["title", "name"].iter().find_map(|k| m.find(k).map(|e| e.text.trim().to_owned())))
.filter(|t| !t.is_empty())
.unwrap_or_default();
- // a tip named by a preset: in the brushes folder, by its file name
+ // a tip named by a preset: in the brushes folder, by its file name; each preset has its own
+ // copy, so all of them together may be only so big (round tips after that)
+ let left = std::cell::Cell::new(MOST_TIP_BYTES);
let file = |wanted: &str| {
let wanted = wanted.rsplit(['/', '\\']).next().unwrap_or(wanted).to_ascii_lowercase();
- names
- .iter()
- .find(|n| {
- n.starts_with("brushes/") && n.rsplit('/').next().is_some_and(|f| f.to_ascii_lowercase() == wanted)
- })
- .and_then(|n| zip.read(n))
+ let name = names.iter().find(|n| {
+ n.starts_with("brushes/") && n.rsplit('/').next().is_some_and(|f| f.to_ascii_lowercase() == wanted)
+ })?;
+ left.set(left.get().checked_sub(zip.size(name)?)?);
+ zip.read(name)
};
let presets: Vec<KritaBrush> = names
.iter()
@@ -179,15 +181,18 @@ pub fn png_text(png: &[u8]) -> Vec<(String, String)> {
),
None => continue,
};
+ // tEXt and zTXt are Latin-1, iTXt UTF-8
+ let latin1 = |b: &[u8]| b.iter().map(|&b| char::from(b)).collect::<String>();
let text = match kind {
- b"tEXt" => Some(rest.iter().map(|&b| char::from(b)).collect()),
- b"zTXt" => rest.get(1..).and_then(inflate),
+ b"tEXt" => Some(latin1(rest)),
+ b"zTXt" => rest.get(1..).and_then(inflate).map(|t| latin1(&t)),
b"iTXt" => {
// compressed or not, the method, then the language and translated keyword
let (Some(&compressed), Some(body)) = (rest.first(), rest.get(2..)) else { continue };
let mut parts = body.splitn(3, |&b| b == 0);
let (_, _, text) = (parts.next(), parts.next(), parts.next().unwrap_or_default());
- if compressed == 1 { inflate(text) } else { Some(String::from_utf8_lossy(text).into_owned()) }
+ let utf8 = if compressed == 1 { inflate(text) } else { Some(text.to_vec()) };
+ utf8.map(|t| String::from_utf8_lossy(&t).into_owned())
}
b"IEND" => break,
_ => None,
@@ -199,9 +204,8 @@ pub fn png_text(png: &[u8]) -> Vec<(String, String)> {
out
}
-fn inflate(data: &[u8]) -> Option<String> {
- let bytes = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(data, MOST_TEXT).ok()?;
- Some(String::from_utf8_lossy(&bytes).into_owned())
+fn inflate(data: &[u8]) -> Option<Vec<u8>> {
+ miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(data, MOST_TEXT).ok()
}
#[cfg(test)]
diff --git a/crates/engine/src/sqlite.rs b/crates/engine/src/sqlite.rs
index da33771..708fb87 100644
--- a/crates/engine/src/sqlite.rs
+++ b/crates/engine/src/sqlite.rs
@@ -128,6 +128,9 @@ impl Database<'_> {
let mut out = Vec::new();
let mut seen = vec![false; self.bytes.len() / self.page_size + 1];
let mut pending = vec![root];
+ // each byte of a table's payloads is in the file once: more than that is cells sharing
+ // their bytes (a damaged or crafted file asking for far more memory than it has)
+ let mut budget = self.bytes.len();
while let Some(n) = pending.pop() {
if out.len() >= MOST_ROWS {
break;
@@ -153,7 +156,10 @@ impl Database<'_> {
0x0D => {
for i in 0..count {
let Some(at) = be16(page, h + 8 + 2 * usize::from(i)) else { break };
- if let Some(row) = self.cell(page, usize::from(at)) {
+ if out.len() >= MOST_ROWS {
+ break;
+ }
+ if let Some(row) = self.cell(page, usize::from(at), &mut budget) {
out.push(row);
}
}
@@ -164,11 +170,13 @@ impl Database<'_> {
out
}
- /// A leaf cell: its row id and record, the payload gathered from overflow pages.
- fn cell(&self, page: &[u8], at: usize) -> Option<(i64, Vec<Value>)> {
+ /// A leaf cell: its row id and record, the payload gathered from overflow pages (taken from
+ /// `budget`, none if more than is left).
+ fn cell(&self, page: &[u8], at: usize, budget: &mut usize) -> Option<(i64, Vec<Value>)> {
let (len, a) = varint(page, at)?;
let (id, b) = varint(page, at + a)?;
let len = usize::try_from(len).ok().filter(|l| *l <= MOST_PAYLOAD)?;
+ *budget = budget.checked_sub(len)?;
let start = at + a + b;
// how much of the payload is on this page (the rest on overflow pages)
let u = self.usable;
@@ -275,26 +283,40 @@ fn columns(sql: &str) -> (Vec<String>, Option<usize>) {
}
}
parts.push(inside.get(from..).unwrap_or_default());
+ let unquote =
+ |s: &str| s.trim().trim_matches(|c| c == '"' || c == '`' || c == '[' || c == ']' || c == '\'').to_owned();
let mut names = Vec::new();
+ let mut integer = Vec::new();
+ // the primary key: a column's own (and whether it is the row's id), or the table's columns
let mut rowid = None;
+ let mut table_key = Vec::new();
for part in parts {
- let part = part.trim();
- let first = part.split_whitespace().next().unwrap_or_default();
- let upper = part.to_ascii_uppercase();
+ // the words in capitals, one space apart (as `PRIMARY KEY` may not be)
+ let flat = part.split_whitespace().collect::<Vec<_>>().join(" ").to_ascii_uppercase();
+ let key = flat.find("PRIMARY KEY").and_then(|at| flat.get(at + "PRIMARY KEY".len()..));
// table constraints, not columns (their keyword may run into a parenthesis)
- let word: String = part
- .chars()
- .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
- .collect::<String>()
- .to_ascii_uppercase();
+ let word: String = flat.chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
if ["PRIMARY", "UNIQUE", "CHECK", "FOREIGN", "CONSTRAINT"].contains(&word.as_str()) {
+ if let Some(list) = key.and_then(|k| k.split_once('(')).and_then(|(_, l)| l.split_once(')')).map(|(l, _)| l)
+ {
+ table_key = list.split(',').map(|c| unquote(c.split_whitespace().next().unwrap_or_default())).collect();
+ }
continue;
}
- let name = first.trim_matches(|c| c == '"' || c == '`' || c == '[' || c == ']' || c == '\'');
- if upper.contains("INTEGER") && upper.contains("PRIMARY KEY") {
+ let mut words = part.split_whitespace();
+ let name = unquote(words.next().unwrap_or_default());
+ let is_integer = words.next().is_some_and(|t| t.eq_ignore_ascii_case("INTEGER"));
+ // the row's id: an INTEGER PRIMARY KEY, though not one declared DESC there
+ if is_integer && key.is_some_and(|k| !k.trim_start().starts_with("DESC")) {
rowid = Some(names.len());
}
- names.push(name.to_owned());
+ names.push(name);
+ integer.push(is_integer);
+ }
+ if rowid.is_none()
+ && let [only] = table_key.as_slice()
+ {
+ rowid = names.iter().position(|n| n.eq_ignore_ascii_case(only)).filter(|&at| integer.get(at) == Some(&true));
}
(names, rowid)
}
@@ -471,6 +493,35 @@ pub(crate) mod tests {
assert!(d.table("Nothing").is_none());
}
+ #[test]
+ fn the_row_id_column_is_found_however_the_key_is_written() {
+ let rowid = |sql: &str| columns(sql).1;
+ assert_eq!(rowid("CREATE TABLE t(id INTEGER PRIMARY KEY, x)"), Some(0));
+ assert_eq!(rowid("CREATE TABLE t(x, id integer not null primary\n key autoincrement)"), Some(1));
+ assert_eq!(rowid("CREATE TABLE t(x TEXT, id INTEGER, PRIMARY KEY(id))"), Some(1));
+ assert_eq!(rowid("CREATE TABLE t(\"id\" INTEGER, CONSTRAINT k PRIMARY KEY (\"ID\" ASC))"), Some(0));
+ // not the row's id: another type, a key of two columns, the DESC quirk
+ assert_eq!(rowid("CREATE TABLE t(IntegerName TEXT PRIMARY KEY)"), None);
+ assert_eq!(rowid("CREATE TABLE t(a INTEGER, b INTEGER, PRIMARY KEY(a, b))"), None);
+ assert_eq!(rowid("CREATE TABLE t(id INTEGER PRIMARY KEY DESC)"), None);
+ assert_eq!(rowid("CREATE TABLE t(id INT PRIMARY KEY)"), None);
+ }
+
+ #[test]
+ fn cells_sharing_their_bytes_take_no_more_than_the_file_has() {
+ let db = database(&[("T", "CREATE TABLE T (b BLOB)", vec![vec![Value::Blob(vec![7; 3000])]])]);
+ // the table's leaf (page 2) made to list its one cell 500 times
+ let mut bad = db.clone();
+ let leaf = 4096;
+ let at = [bad[leaf + 8], bad[leaf + 9]];
+ bad[leaf + 3..leaf + 5].copy_from_slice(&500u16.to_be_bytes());
+ for i in 0..500 {
+ bad[leaf + 8 + 2 * i..leaf + 10 + 2 * i].copy_from_slice(&at);
+ }
+ let rows = open(&bad).unwrap().table("T").unwrap().rows;
+ assert!(!rows.is_empty() && rows.len() * 3000 <= bad.len(), "{} rows", rows.len());
+ }
+
#[test]
fn other_files_and_damaged_ones_are_refused_not_a_crash() {
assert!(open(b"not a database").is_none());
diff --git a/crates/engine/src/studio.rs b/crates/engine/src/studio.rs
index 2a03a33..c1299ff 100644
--- a/crates/engine/src/studio.rs
+++ b/crates/engine/src/studio.rs
@@ -109,6 +109,12 @@ pub(crate) const SPACING_SPAN: f32 = 2.0 * std::f32::consts::SQRT_2;
const SPACING_CURVE: f32 = 2.2;
impl Brush {
+ /// `spacing` (stamp diameters, as another app's file has it) within what the studio's control
+ /// reaches.
+ pub fn spacing_within_reach(spacing: f32) -> f32 {
+ spacing.clamp(SPACING_FLOOR, SPACING_FLOOR + SPACING_SPAN)
+ }
+
/// The most size (brush-file units) the brush may have: [`MOST_SIZE`] when spaced at least
/// [`ROOMY_SPACING`] apart, less the closer its stamps are (so a stroke stays a manageable
/// number of stamps), 1 at no spacing.
diff --git a/crates/engine/src/xml.rs b/crates/engine/src/xml.rs
index 371ecd6..18bab96 100644
--- a/crates/engine/src/xml.rs
+++ b/crates/engine/src/xml.rs
@@ -162,7 +162,8 @@ pub fn unescape(s: &str) -> String {
while let Some(amp) = rest.find('&') {
out.push_str(rest.get(..amp).unwrap_or_default());
let after = rest.get(amp + 1..).unwrap_or_default();
- let Some(semi) = after.find(';').filter(|&n| n <= 10) else {
+ // an entity is short: only that far is looked at (else a run of `&` scans to the end each)
+ let Some(semi) = after.bytes().take(11).position(|b| b == b';') else {
out.push('&');
rest = after;
continue;
@@ -226,6 +227,11 @@ mod tests {
assert_eq!(root.child("b").map(|b| b.text.as_str()), Some("text"));
assert_eq!(parse("no markup"), None);
assert_eq!(unescape("a &bogus; b & c"), "a &bogus; b & c");
+ // a long run of `&` with no `;` takes a moment, not hours
+ let run = "&".repeat(4 << 20);
+ let started = std::time::Instant::now();
+ assert_eq!(unescape(&run).len(), run.len());
+ assert!(started.elapsed().as_secs() < 5);
let deep = "<a>".repeat(1000);
assert_eq!(parse(&deep), None);
crate::damaged::survives("XML", br#"<a k="v"><b><![CDATA[x]]></b>&amp;<!-- c --></a>"#, |b| {
diff --git a/crates/engine/src/zip.rs b/crates/engine/src/zip.rs
index 6fab82a..4fd1dfe 100644
--- a/crates/engine/src/zip.rs
+++ b/crates/engine/src/zip.rs
@@ -56,6 +56,11 @@ impl<'a> ZipReader<'a> {
self.entries.iter().map(|e| e.name.as_str())
}
+ /// The size entry `name` says it has once read (`read` gives no more).
+ pub fn size(&self, name: &str) -> Option<usize> {
+ self.entries.iter().find(|e| e.name == name).map(|e| e.size)
+ }
+
/// The contents of entry `name`; `None` if it is missing, damaged or of a kind not read.
pub fn read(&self, name: &str) -> Option<Vec<u8>> {
let e = self.entries.iter().find(|e| e.name == name)?;