mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-27 16:59:56 +01:00
Merge pull request #2945 from dotCooCoo/fix/cmx-resync-known-chunk
craft-cdr: .cmx no longer drops a page that stray letters' length covers
This commit is contained in:
5 files changed
+1064
-77
No files matched your search
@@ -121,7 +121,7 @@ file is committed.
|
||||
| R50 | Bit 5 (0x20) of the outline's line type scales the outline's width and dashes with the shape's matrix. The engine multiplies them by the square root of the matrix's area factor (VectorCraft's own value for a matrix that scales x and y differently) | S: UC `outl_scale_with_cdr7.cdr` to `outl_scale_with_cdr12.cdr`, of whose outlines only one, 3.969 mm wide, has line type 0x22 and the others 0x02 or 0x01; TDF 76771 (version 15), whose outline of line type 0x22 is 10 mm wide on a shape that the matrix stretches and skews, and whose picture draws that outline several times wider and skewed | sample (the bit; the single width for a matrix that scales x and y differently: VectorCraft's own) |
|
||||
| R51 | A `trfd` offsets table holds one offset more than the entries; each entry runs from its offset to the next, and the last offset is the record's end | KF L1079, L1113-L1121; S: every `trfd` of versions 4 to 25 in the sample files (25,425 records) has the extra offset, equal to the record's length | public-spec |
|
||||
| R52 | Byte 0 of argument 14001 is the fill's winding flag. VectorCraft reads a byte other than 0 as the nonzero fill rule, and 0 or an object without the argument as even-odd | KF L575-L583, L1047; S: the argument is 4 bytes in the sample files that carry it, with byte 0 = 1 on LT `complexshape_blackfill_nooutline` of `testset/12` and `testset/15` to `testset/25` and on objects of TDF 127576 (13) and 60026 (14), and 0 on 27 objects of TP `example.cdr` (17) | public-spec (the flag: KF; which rule each value means, and the rule without the argument: VectorCraft's own reading, and a wrong reading fills or leaves holes where a curve's subpaths overlap) |
|
||||
| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list (VectorCraft's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample |
|
||||
| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list. When that chunk is one the reader passes over or a `page`, the reader may resume instead at a `page` chunk that starts 8 to 64 bytes after it, inside its body, is not empty, ends inside the list and, when the chunk found ends inside the list, reaches its end. It does so only when that page reads with objects and without damage in its instructions, and when walking on from the chunk found and from the page, each without this recovery and entering lists as the reader does, reaches the same position inside the same lists, or leaves the list (at its end, or at stray bytes with no chunk id after them), within 16 steps, with every chunk the reader uses that the first walk reads before then also read by the second, with its body cut at the same place (pages that read without objects aside). Of the chunks that only the second walk reads, or that it reads with its body cut at another place than the first walk does, the header or a table is used only when no other chunk of its id is read, and a page is kept only when it reads with objects and without damage in its instructions. Letters spelling `page` whose length runs past the list are checked the same way. In one read, the search for pages to resume at spends at most four times the length of the RIFF form (cut at the file's length), or 1,048,576 when that is more, counting 64 for each step of a walk and the length of each page body judged; past that, the reader resumes at the first chunk id found. It does the same when a limit stops the read of a page it judges. Pages kept this way are read after the other pages, so they spend only what the limits leave, and keep their place in the file; each is judged once more before it is read. One that a limit stops, or leaves without objects, is left out with the warning for limits; one the limits cut short is read as far as they allow, as other pages are. When the chunks that only these recoveries read make the read stop at a limit, the file is read again without the recoveries, with the warning for limits. Resuming at an inner page, at a chunk the reader passes over that is not followed by another chunk id or by the list's end, or after letters whose length runs past the list is reported as damage (this reader's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample |
|
||||
| R54 | `cont`: byte 52 is the coordinate size as an ASCII digit, `4` for 32-bit coordinates and `2` for 16-bit ones (refused); bytes 64 to 72 hold an f64, the size of a coordinate unit in meters. A value that isn't above 0 and at most 1 reads as 0.1 µm (VectorCraft's own fallback) | CN "Container"; S: the nine CX files with `4` all hold 1e-7; `abydos.cmx`, `CM33.CMX`, `LIZARDS.CMX`, `output.000.cmx` and `test.cmx` hold `2` | sample |
|
||||
| R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample |
|
||||
| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) |
|
||||
|
||||
+304
-34
@@ -4,6 +4,8 @@
|
||||
//! and outlines (R63). Text, images, rectangles, ellipses, clipping paths, other fills and lenses
|
||||
//! are left out with a warning.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::bytes::{Rd, u32_at};
|
||||
use crate::geometry::path_of;
|
||||
use crate::layout::{self, Profile};
|
||||
@@ -19,6 +21,16 @@ const FORM: [u8; 4] = *b"CMX1";
|
||||
const DEFAULT_UNIT: f64 = 1e-7;
|
||||
/// How far past a chunk that runs short the next chunk id is looked for (R53).
|
||||
const RESYNC: usize = 64;
|
||||
/// How many steps (a chunk, or a jump over stray bytes) the reader walks on from a position it
|
||||
/// could resume at, to compare it with the first chunk id found (R53).
|
||||
const LOOKAHEAD: usize = 16;
|
||||
/// The work counted for one step of a walk ([`walk`]) against [`PROBE_FLOOR`] (R53).
|
||||
const STEP_COST: usize = 64;
|
||||
/// The least work one read may spend on recoveries after stray bytes (R53), counted as
|
||||
/// [`STEP_COST`] for each step of a walk and as the length of each page body judged. A read may
|
||||
/// spend four times the length of the RIFF form, cut at the file's length, when that is more. Past it, the reader resumes at the
|
||||
/// first chunk id found.
|
||||
const PROBE_FLOOR: usize = 1 << 20;
|
||||
/// The chunks the reader uses (R53 to R60).
|
||||
const READ_IDS: [[u8; 4]; 9] = [*b"LIST", *b"cont", *b"page", *b"rclr", *b"rpen", *b"rott", *b"rdot", *b"rotl", *b"rota"];
|
||||
/// The most UTF-16 units read of a layer's name; [`name`] keeps 256 of them.
|
||||
@@ -52,6 +64,15 @@ struct Chunk<'a> {
|
||||
id: [u8; 4],
|
||||
body: &'a [u8],
|
||||
start: usize,
|
||||
/// Only a recovery after stray bytes reads the chunk ([`inner_page`]): the header or a table
|
||||
/// is taken from it only when no other chunk of its id is read, and a page is kept only when it
|
||||
/// reads with objects and without damage in its instructions.
|
||||
recovered: bool,
|
||||
}
|
||||
|
||||
/// The first chunk of id `id` that is not recovered, or else the first recovered one.
|
||||
fn first_of<'c, 'a>(chunks: &'c [Chunk<'a>], id: &[u8; 4]) -> Option<&'c Chunk<'a>> {
|
||||
chunks.iter().find(|c| c.id == *id && !c.recovered).or_else(|| chunks.iter().find(|c| c.id == *id))
|
||||
}
|
||||
|
||||
/// The tables that page instructions refer to by 1-based index (R55 to R59).
|
||||
@@ -66,9 +87,35 @@ struct Tables {
|
||||
/// Line type, screen, color, arrowheads, pen and dashes.
|
||||
outlines: Vec<Option<[u16; 6]>>,
|
||||
arrowheads: Vec<(u16, u16)>,
|
||||
/// Missing entries are not reported as damage: a page is read only to judge its instructions
|
||||
/// ([`page_reads`]).
|
||||
quiet: bool,
|
||||
}
|
||||
|
||||
/// The drawing in `bytes` (R53 to R63). When the chunks that only a recovery after stray bytes
|
||||
/// reads make the read stop at a limit, the file is read again without the recovery, with the
|
||||
/// warning for limits.
|
||||
pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result<Drawing, Error> {
|
||||
let fresh = budget.clone();
|
||||
match read_drawing(bytes, budget, true) {
|
||||
Err(Error::Limit(_)) => {
|
||||
*budget = fresh;
|
||||
let mut d = read_drawing(bytes, budget, false)?;
|
||||
push(&mut d.warnings, Warning::TooDeep);
|
||||
Ok(d)
|
||||
}
|
||||
read => read,
|
||||
}
|
||||
}
|
||||
|
||||
/// The drawing as the reader reads it when it resumes after stray bytes only at the first chunk
|
||||
/// id found, never at a page inside that chunk (R53).
|
||||
#[cfg(any(test, feature = "synth"))]
|
||||
pub(crate) fn drawing_without_recovery(bytes: &[u8], budget: &mut Budget) -> Result<Drawing, Error> {
|
||||
read_drawing(bytes, budget, false)
|
||||
}
|
||||
|
||||
fn read_drawing(bytes: &[u8], budget: &mut Budget, recover: bool) -> Result<Drawing, Error> {
|
||||
if !is_cmx(bytes) {
|
||||
return Err(Error::NotCmx);
|
||||
}
|
||||
@@ -76,8 +123,8 @@ pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result<Drawing, Erro
|
||||
return Err(Error::Unsupported("big-endian CMX files"));
|
||||
}
|
||||
let mut warn = Vec::new();
|
||||
let chunks = chunks(bytes, budget, &mut warn)?;
|
||||
let cont = chunks.iter().find(|c| c.id == *b"cont").map(|c| c.body).ok_or(Error::Damaged("CMX header"))?;
|
||||
let chunks = chunks(bytes, budget, &mut warn, recover)?;
|
||||
let cont = first_of(&chunks, b"cont").map(|c| c.body).ok_or(Error::Damaged("CMX header"))?;
|
||||
match cont.get(52) {
|
||||
Some(b'4') => {}
|
||||
Some(b'2') => return Err(Error::Unsupported("CMX files with 16-bit coordinates")),
|
||||
@@ -86,15 +133,38 @@ pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result<Drawing, Erro
|
||||
let meters = Rd::at(cont, 64).f64().filter(|m| *m > 0.0 && *m <= 1.0).unwrap_or(DEFAULT_UNIT);
|
||||
let unit = meters / 0.0254 * 72.0;
|
||||
let tables = Tables::read(&chunks, unit, budget, &mut warn)?;
|
||||
// The pages read without the recovery go first, so that recovered pages spend only what the
|
||||
// limits leave after them; the pages keep the order of the file.
|
||||
let mut pages = Vec::new();
|
||||
for c in chunks.iter().filter(|c| c.id == *b"page") {
|
||||
pages.push(PageRead::new(&tables, unit, budget, &mut warn).read(c)?);
|
||||
for c in chunks.iter().filter(|c| c.id == *b"page" && !c.recovered) {
|
||||
pages.push((c.start, PageRead::new(&tables, unit, budget, &mut warn).read(c)?));
|
||||
}
|
||||
for c in chunks.iter().filter(|c| c.id == *b"page" && c.recovered) {
|
||||
// A recovered page is judged however much the recoveries spent. One that a limit stops,
|
||||
// or leaves without objects, is left out with the warning that says so; one the limits
|
||||
// cut short is read as far as they allow, as the other pages are.
|
||||
let read = match judgement(c, budget) {
|
||||
Ok((true, false, _)) => PageRead::new(&tables, unit, budget, &mut warn).read(c),
|
||||
Ok((_, _, true)) | Err(Error::Limit(_)) => {
|
||||
push(&mut warn, Warning::TooDeep);
|
||||
continue;
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
match read {
|
||||
Ok(page) => pages.push((c.start, page)),
|
||||
Err(Error::Limit(_)) => push(&mut warn, Warning::TooDeep),
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
pages.sort_by_key(|(start, _)| *start);
|
||||
let pages = pages.into_iter().map(|(_, page)| page).collect();
|
||||
Ok(Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: warn })
|
||||
}
|
||||
|
||||
/// The chunks of the file in order, those inside `LIST` chunks in place (R53).
|
||||
fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<Vec<Chunk<'a>>, Error> {
|
||||
/// The chunks of the file in order, those inside `LIST` chunks in place (R53). With `recover`, the
|
||||
/// reader may resume after stray bytes at a page inside the first chunk id found ([`inner_page`]).
|
||||
fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec<Warning>, recover: bool) -> Result<Vec<Chunk<'a>>, Error> {
|
||||
let declared = u32_at(b, 4).and_then(|n| (n as usize).checked_add(8)).unwrap_or(b.len());
|
||||
if declared > b.len() {
|
||||
// The file was cut short of the size its header gives.
|
||||
@@ -102,15 +172,23 @@ fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec<Warning>) -> Resu
|
||||
}
|
||||
let end = declared.min(b.len());
|
||||
let mut out = Vec::new();
|
||||
// (position, end, depth) of the lists still to walk; a list's children go before the rest of
|
||||
// the list that holds it.
|
||||
let mut stack = vec![(12usize, end, 0usize)];
|
||||
while let Some((mut pos, end, depth)) = stack.pop() {
|
||||
// Where the chunks start that only a recovery reads ([`rejoins`]).
|
||||
let mut extra = BTreeSet::new();
|
||||
// The work the recoveries may still spend ([`PROBE_FLOOR`]).
|
||||
let mut left = end.saturating_mul(4).max(PROBE_FLOOR);
|
||||
// (position, end, depth, recovered) of the lists still to walk; a list's children go before
|
||||
// the rest of the list that holds it.
|
||||
let mut stack = vec![(12usize, end, 0usize, false)];
|
||||
while let Some((mut pos, end, depth, in_recovered)) = stack.pop() {
|
||||
while pos.saturating_add(8) <= end {
|
||||
let Some(id) = Rd::at(b, pos).fourcc() else { break };
|
||||
if !is_id(&id) {
|
||||
match resync(b, pos, end) {
|
||||
Some(next) => {
|
||||
match resync(b, pos, end, depth, recover.then_some(&*budget), &mut left) {
|
||||
Some((next, damaged, found)) => {
|
||||
if damaged {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
extra.extend(found);
|
||||
pos = next;
|
||||
continue;
|
||||
}
|
||||
@@ -126,30 +204,38 @@ fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec<Warning>) -> Resu
|
||||
let stop = start.saturating_add(size);
|
||||
if stop > end {
|
||||
// Stray bytes that happen to start with four letters give a length past the list:
|
||||
// look for the next chunk id after them. A chunk the reader uses is kept, cut at
|
||||
// the end of the list.
|
||||
if !READ_IDS.contains(&id)
|
||||
&& let Some(next) = resync(b, pos, end)
|
||||
{
|
||||
// look for the next chunk id after them, and report the damage. A chunk the reader
|
||||
// uses is kept, cut at the end of the list, unless it is a page that holds a page
|
||||
// the reader resumes at.
|
||||
push(warn, Warning::Damaged);
|
||||
let resume = if !READ_IDS.contains(&id) {
|
||||
resync(b, pos, end, depth, recover.then_some(&*budget), &mut left).map(|(next, _, found)| (next, found))
|
||||
} else if recover && id == *b"page" {
|
||||
inner_page(b, pos, end, depth, budget, &mut left)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some((next, found)) = resume {
|
||||
extra.extend(found);
|
||||
pos = next;
|
||||
continue;
|
||||
}
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
let stop = stop.min(end);
|
||||
let next = stop.saturating_add(size & 1);
|
||||
let recovered = in_recovered || extra.contains(&pos);
|
||||
if id == LIST {
|
||||
if depth >= budget.limits.depth {
|
||||
push(warn, Warning::TooDeep);
|
||||
pos = next;
|
||||
continue;
|
||||
}
|
||||
stack.push((next, end, depth));
|
||||
stack.push((start + 4, stop, depth + 1));
|
||||
stack.push((next, end, depth, in_recovered));
|
||||
stack.push((start + 4, stop, depth + 1, recovered));
|
||||
break;
|
||||
}
|
||||
if let Some(body) = b.get(start..stop) {
|
||||
out.push(Chunk { id, body, start });
|
||||
out.push(Chunk { id, body, start, recovered });
|
||||
}
|
||||
pos = next;
|
||||
}
|
||||
@@ -162,15 +248,199 @@ fn is_id(t: &[u8]) -> bool {
|
||||
matches!(t, [first, rest @ ..] if t.len() == 4 && first.is_ascii_alphabetic() && rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b' '))
|
||||
}
|
||||
|
||||
/// Where the next chunk after `pos` lies: the first chunk id at an even distance of 2 to [`RESYNC`]
|
||||
/// bytes that names a chunk the reader uses, or another chunk whose length keeps it inside the list
|
||||
/// that ends at `end` (R53).
|
||||
fn resync(b: &[u8], pos: usize, end: usize) -> Option<usize> {
|
||||
let fits = |p: usize| u32_at(b, p + 4).and_then(|s| (p + 8).checked_add(s as usize)).is_some_and(|stop| stop <= end);
|
||||
let chunk_at = |p: usize| Rd::at(b, p).fourcc().is_some_and(|id| is_id(&id) && (READ_IDS.contains(&id) || fits(p)));
|
||||
/// The chunk id at `p`, when the four bytes there read as one.
|
||||
fn id_at(b: &[u8], p: usize) -> Option<[u8; 4]> {
|
||||
Rd::at(b, p).fourcc().filter(|id| is_id(id))
|
||||
}
|
||||
|
||||
/// Where the body of the chunk at `p` ends by its length, before its pad byte.
|
||||
fn chunk_stop(b: &[u8], p: usize) -> Option<usize> {
|
||||
u32_at(b, p + 4).and_then(|s| (p + 8).checked_add(s as usize))
|
||||
}
|
||||
|
||||
/// The first chunk id after `pos`, at an even distance of 2 to [`RESYNC`] bytes, that names a
|
||||
/// chunk the reader uses or another chunk whose length keeps it inside the list that ends at `end`
|
||||
/// (R53).
|
||||
fn first_chunk(b: &[u8], pos: usize, end: usize) -> Option<usize> {
|
||||
let fits = |p: usize| chunk_stop(b, p).is_some_and(|stop| stop <= end);
|
||||
let chunk_at = |p: usize| id_at(b, p).is_some_and(|id| READ_IDS.contains(&id) || fits(p));
|
||||
(pos + 2..=pos.saturating_add(RESYNC).min(end.saturating_sub(8))).step_by(2).find(|&p| chunk_at(p))
|
||||
}
|
||||
|
||||
/// Where the next chunk after stray bytes at `pos` lies, whether the bytes passed over are
|
||||
/// reported as damage, and where the chunks start that only the recovery reads (R53). It is
|
||||
/// [`first_chunk`], or, with `judge` (the read's budget), a page inside that chunk ([`inner_page`]),
|
||||
/// found with at most `left` work ([`PROBE_FLOOR`]). The flag is set when the reader resumes at an
|
||||
/// inner page, or at a chunk it passes over that is not followed by another chunk id or by the end
|
||||
/// of the list. `depth` is how many lists hold the one that ends at `end`.
|
||||
fn resync(b: &[u8], pos: usize, end: usize, depth: usize, judge: Option<&Budget>, left: &mut usize) -> Option<(usize, bool, Vec<usize>)> {
|
||||
let p = first_chunk(b, pos, end)?;
|
||||
if let Some((k, found)) = judge.and_then(|budget| inner_page(b, p, end, depth, budget, left)) {
|
||||
return Some((k, true, found));
|
||||
}
|
||||
let known = id_at(b, p).is_some_and(|id| READ_IDS.contains(&id));
|
||||
let followed = chunk_stop(b, p).filter(|stop| *stop <= end).is_some_and(|stop| {
|
||||
let n = stop.saturating_add((stop - p - 8) & 1);
|
||||
n >= end || (n.saturating_add(8) <= end && id_at(b, n).is_some())
|
||||
});
|
||||
Some((p, !known && !followed, Vec::new()))
|
||||
}
|
||||
|
||||
/// A page the reader resumes at instead of the chunk at `p`, the first chunk id after stray bytes
|
||||
/// or letters spelling `page` whose length runs past the list (R53). It is a page id at an even
|
||||
/// distance of 8 to [`RESYNC`] bytes after `p`, inside the body of that chunk, whose length is not
|
||||
/// 0, keeps it inside the list and, when the chunk at `p` ends inside the list, reaches the end of
|
||||
/// that chunk. A `LIST`, the header and the tables at `p` are always kept. Walking on from `p` and
|
||||
/// from the page by the reader's rule without this recovery must meet ([`rejoins`]). The first page
|
||||
/// that meets is taken, with the chunks only the walk from it reads. The walks and the pages judged
|
||||
/// spend `left` ([`PROBE_FLOOR`]); when it runs out, no page is taken. `depth` is how many lists
|
||||
/// hold the one that ends at `end`.
|
||||
fn inner_page(b: &[u8], p: usize, end: usize, depth: usize, budget: &Budget, left: &mut usize) -> Option<(usize, Vec<usize>)> {
|
||||
let id = id_at(b, p)?;
|
||||
if READ_IDS.contains(&id) && id != *b"page" {
|
||||
return None;
|
||||
}
|
||||
let stop = chunk_stop(b, p).filter(|stop| *stop <= end);
|
||||
let body_end = stop.unwrap_or(end);
|
||||
// The chunk at `k` ends, with its pad byte, at or past the end of the chunk at `p`.
|
||||
let reaches =
|
||||
|k: usize| chunk_stop(b, k).is_some_and(|s| s > k + 8 && s <= end && stop.is_none_or(|stop| s.saturating_add((s - k - 8) & 1) >= stop));
|
||||
let mut found = (p + 8..=p.saturating_add(RESYNC).min(end.saturating_sub(8)))
|
||||
.step_by(2)
|
||||
.filter(|&k| k < body_end && id_at(b, k) == Some(*b"page") && reaches(k))
|
||||
.peekable();
|
||||
found.peek()?;
|
||||
let lists = budget.limits.depth.saturating_sub(depth);
|
||||
let first = walk(b, p, end, lists, left)?;
|
||||
found.find_map(|k| {
|
||||
let alt = walk(b, k, end, lists, left)?;
|
||||
rejoins(b, &first, &alt, budget, left).map(|extra| (k, extra))
|
||||
})
|
||||
}
|
||||
|
||||
/// Positions a walk through a list passes and the chunks it reads, for at most [`LOOKAHEAD`]
|
||||
/// steps.
|
||||
struct Walk {
|
||||
/// Where the walk starts, and its place after each step: the position, and for each `LIST`
|
||||
/// chunk it is inside, where that list's body ends and where the reader goes on after it.
|
||||
at: Vec<(usize, Vec<(usize, usize)>)>,
|
||||
/// Where each chunk the walk read starts, and where its body ends, cut at the end of the list
|
||||
/// that holds it; a `LIST` chunk it enters counts by the chunks inside.
|
||||
read: Vec<(usize, usize)>,
|
||||
/// The walk left the list it started in: at its end, or at stray bytes with no chunk id after
|
||||
/// them, where [`chunks`] stops reading that list too.
|
||||
ended: bool,
|
||||
}
|
||||
|
||||
/// Walk the list that ends at `end` from `from` as [`chunks`] does without recovery, entering at
|
||||
/// most `lists` nested `LIST` chunks as it does, and spending [`STEP_COST`] of `left` for each step;
|
||||
/// `None` when `left` runs out first.
|
||||
fn walk(b: &[u8], from: usize, end: usize, lists: usize, left: &mut usize) -> Option<Walk> {
|
||||
let mut w = Walk { at: vec![(from, Vec::new())], read: Vec::new(), ended: false };
|
||||
let mut pos = from;
|
||||
let mut inside: Vec<(usize, usize)> = Vec::new();
|
||||
for _ in 0..LOOKAHEAD {
|
||||
*left = left.checked_sub(STEP_COST)?;
|
||||
let list_end = inside.last().map_or(end, |&(stop, _)| stop);
|
||||
match step(b, pos, list_end) {
|
||||
Some((next, Some(chunk))) if id_at(b, chunk) == Some(LIST) && inside.len() < lists => {
|
||||
// [`chunks`] reads the list's children before the rest of the list that holds it.
|
||||
let stop = chunk_stop(b, chunk).map_or(list_end, |stop| stop.min(list_end));
|
||||
inside.push((stop, next));
|
||||
pos = chunk + 12;
|
||||
}
|
||||
Some((next, chunk)) => {
|
||||
w.read.extend(chunk.map(|c| (c, chunk_stop(b, c).map_or(list_end, |stop| stop.min(list_end)))));
|
||||
pos = next;
|
||||
}
|
||||
None => match inside.pop() {
|
||||
Some((_, after)) => pos = after,
|
||||
None => {
|
||||
w.ended = true;
|
||||
break;
|
||||
}
|
||||
},
|
||||
}
|
||||
w.at.push((pos, inside.clone()));
|
||||
}
|
||||
Some(w)
|
||||
}
|
||||
|
||||
/// One step of [`chunks`] without recovery at `pos`: the position after it, and where the chunk
|
||||
/// it read starts when it read one; `None` when the walk ends there.
|
||||
fn step(b: &[u8], pos: usize, end: usize) -> Option<(usize, Option<usize>)> {
|
||||
if pos.saturating_add(8) > end {
|
||||
return None;
|
||||
}
|
||||
let id = Rd::at(b, pos).fourcc()?;
|
||||
if !is_id(&id) {
|
||||
return first_chunk(b, pos, end).map(|next| (next, None));
|
||||
}
|
||||
let size = u32_at(b, pos + 4).map_or(0, |s| s as usize);
|
||||
let stop = (pos + 8).saturating_add(size);
|
||||
if stop > end
|
||||
&& !READ_IDS.contains(&id)
|
||||
&& let Some(next) = first_chunk(b, pos, end)
|
||||
{
|
||||
return Some((next, None));
|
||||
}
|
||||
Some((stop.min(end).saturating_add(size & 1), Some(pos)))
|
||||
}
|
||||
|
||||
/// Where the chunks start that the walk from an inner page `alt` reads and the walk from the first
|
||||
/// chunk id `first` does not read with the same body, when the two walks meet at a place both pass (a position inside the
|
||||
/// same lists) or both end, and `alt` reads at least what `first` reads until then (R53). The page
|
||||
/// `alt` starts at reads with objects and without damage in its instructions. Each chunk the reader
|
||||
/// uses that `first` reads before that point, `alt` reads too, with the same body, unless it is a
|
||||
/// page that reads without objects. The pages judged spend `left`; when it runs out, or when the
|
||||
/// read of a page judged stops, the walks do not meet.
|
||||
fn rejoins(b: &[u8], first: &Walk, alt: &Walk, budget: &Budget, left: &mut usize) -> Option<Vec<usize>> {
|
||||
let meet = first.at.iter().find(|q| alt.at.contains(q)).map(|(q, _)| *q).or((first.ended && alt.ended).then_some(usize::MAX))?;
|
||||
let uses = |q: usize| q < meet && id_at(b, q).is_some_and(|id| READ_IDS.contains(&id));
|
||||
let used = |w: &Walk| -> Vec<(usize, usize)> { w.read.iter().copied().filter(|&(q, _)| uses(q)).collect() };
|
||||
let (kept, taken) = (used(first), used(alt));
|
||||
let (start, stop) = *alt.read.first()?;
|
||||
if page_reads(b, start, stop, budget, left)? != (true, false) {
|
||||
return None;
|
||||
}
|
||||
for &(q, stop) in kept.iter().filter(|q| !taken.contains(q)) {
|
||||
// A page that reads without objects is the only chunk the walk from `alt` may leave out,
|
||||
// or read with a body cut shorter by a list.
|
||||
if id_at(b, q) != Some(*b"page") || page_reads(b, q, stop, budget, left)?.0 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(taken.into_iter().filter(|q| !kept.contains(q)).map(|(q, _)| q).collect())
|
||||
}
|
||||
|
||||
/// Whether the page chunk at `at` reads with objects, and whether its instructions read with
|
||||
/// damage ([`judge_page`]); `None` when `left` does not cover its body or the read stops.
|
||||
fn page_reads(b: &[u8], at: usize, end: usize, budget: &Budget, left: &mut usize) -> Option<(bool, bool)> {
|
||||
let stop = chunk_stop(b, at).map_or(end, |stop| stop.min(end));
|
||||
let Some(body) = b.get(at + 8..stop) else { return Some((false, true)) };
|
||||
judge_page(&Chunk { id: *b"page", body, start: at + 8, recovered: true }, budget, left)
|
||||
}
|
||||
|
||||
/// Whether page `c` reads with objects, and whether its instructions read with damage. It is read
|
||||
/// with empty tables whose missing entries are not reported, and with a copy of `budget` so that the
|
||||
/// read's own budget is not spent. The length of its body is taken from `left` first; `None` when
|
||||
/// `left` holds less, or when the read stops.
|
||||
fn judge_page(c: &Chunk, budget: &Budget, left: &mut usize) -> Option<(bool, bool)> {
|
||||
*left = left.checked_sub(c.body.len())?;
|
||||
judgement(c, budget).ok().map(|(objects, damaged, _)| (objects, damaged))
|
||||
}
|
||||
|
||||
/// Whether page `c` reads with objects, whether its instructions read with damage, and whether
|
||||
/// the read left something out at one of the limits, read as [`judge_page`] reads it; the error
|
||||
/// when the read stops.
|
||||
fn judgement(c: &Chunk, budget: &Budget) -> Result<(bool, bool, bool), Error> {
|
||||
let tables = Tables { quiet: true, ..Tables::default() };
|
||||
let mut scratch = budget.clone();
|
||||
let mut warn = Vec::new();
|
||||
let page = PageRead::new(&tables, 1.0, &mut scratch, &mut warn).read(c)?;
|
||||
Ok((!page.layers.is_empty(), warn.contains(&Warning::Damaged), warn.contains(&Warning::TooDeep)))
|
||||
}
|
||||
|
||||
/// The end of the field list at `pos` of `b`: after its 0xff, or the end of `b` when a field runs
|
||||
/// past it (R55).
|
||||
fn list_end(b: &[u8], mut pos: usize) -> usize {
|
||||
@@ -224,7 +494,7 @@ fn entries<'a>(d: &'a [u8], budget: &mut Budget) -> Result<Vec<&'a [u8]>, Error>
|
||||
impl Tables {
|
||||
/// The first chunk of each table; a table that is missing is empty.
|
||||
fn read(chunks: &[Chunk], unit: f64, budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<Tables, Error> {
|
||||
let first = |id: &[u8; 4]| chunks.iter().find(|c| c.id == *id).map_or(&[][..], |c| c.body);
|
||||
let first = |id: &[u8; 4]| first_of(chunks, id).map_or(&[][..], |c| c.body);
|
||||
// A color record of field 10 holds a property list as a `.cdr` fill does (R56).
|
||||
let record = layout::for_version(1300);
|
||||
let mut t = Tables::default();
|
||||
@@ -265,26 +535,26 @@ impl Tables {
|
||||
}
|
||||
|
||||
/// Entry `index` (1-based) of `list`, or `None` with a warning when there is none.
|
||||
fn get<T: Clone>(list: &[Option<T>], index: u16, warn: &mut Vec<Warning>) -> Option<T> {
|
||||
fn get<T: Clone>(&self, list: &[Option<T>], index: u16, warn: &mut Vec<Warning>) -> Option<T> {
|
||||
let found = usize::from(index).checked_sub(1).and_then(|i| list.get(i)).cloned().flatten();
|
||||
if found.is_none() {
|
||||
if found.is_none() && !self.quiet {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn color(&self, index: u16, warn: &mut Vec<Warning>) -> Color {
|
||||
Tables::get(&self.colors, index, warn).unwrap_or(Color::Rgb([0.0; 3]))
|
||||
self.get(&self.colors, index, warn).unwrap_or(Color::Rgb([0.0; 3]))
|
||||
}
|
||||
|
||||
/// The outline of `rotl` entry `index`, or `None` when its line type draws none (R57, R58).
|
||||
fn outline(&self, index: u16, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Outline> {
|
||||
let [line, _screen, color, arrows, pen, dash] = Tables::get(&self.outlines, index, warn)?;
|
||||
let (flags, caps_join) = Tables::get(&self.line_types, line, warn).unwrap_or((2, 0));
|
||||
let [line, _screen, color, arrows, pen, dash] = self.get(&self.outlines, index, warn)?;
|
||||
let (flags, caps_join) = self.get(&self.line_types, line, warn).unwrap_or((2, 0));
|
||||
if flags & 1 != 0 {
|
||||
return None;
|
||||
}
|
||||
let width = Tables::get(&self.pens, pen, warn).unwrap_or(0.0);
|
||||
let width = self.get(&self.pens, pen, warn).unwrap_or(0.0);
|
||||
let mut dashes = Vec::new();
|
||||
if flags & 4 != 0 {
|
||||
let stored = usize::from(dash).checked_sub(1).and_then(|i| self.dashes.get(i));
|
||||
|
||||
@@ -74,7 +74,7 @@ impl Default for Limits {
|
||||
}
|
||||
|
||||
/// The running counters of one read against its [`Limits`].
|
||||
#[derive(Debug)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Budget {
|
||||
pub(crate) limits: Limits,
|
||||
inflated: usize,
|
||||
|
||||
@@ -285,3 +285,12 @@ pub fn sample() -> Vec<u8> {
|
||||
children.extend(tables());
|
||||
riff(&children)
|
||||
}
|
||||
|
||||
/// Read `bytes` as [`crate::read_cmx`] does, except that after stray bytes the reader resumes only
|
||||
/// at the first chunk id found, never at a page inside that chunk (R53). Tests compare the two.
|
||||
pub fn read_cmx_without_recovery(bytes: &[u8], limits: crate::Limits) -> Result<crate::Drawing, crate::Error> {
|
||||
if bytes.len() > limits.input {
|
||||
return Err(crate::Error::Limit("input size"));
|
||||
}
|
||||
crate::cmx::drawing_without_recovery(bytes, &mut crate::limits::Budget::new(limits))
|
||||
}
|
||||
+749
-41
@@ -1,11 +1,39 @@
|
||||
//! Reading synthetic `.cmx` files built from the layouts in `PROVENANCE.md` (R53 to R63), and
|
||||
//! hostile ones.
|
||||
|
||||
use craft_cdr::model::{Cap, Color, Geometry, Join, Object, Shape};
|
||||
use craft_cdr::model::{Cap, Color, Geometry, Join, Object, Page, Shape};
|
||||
use craft_cdr::synth_cmx::*;
|
||||
use craft_cdr::{Error, Limits, Warning, is_cdr, is_cmx, read_cmx};
|
||||
use craft_cdr::{Drawing, Error, Limits, Warning, is_cdr, is_cmx, read_cmx};
|
||||
use proptest::prelude::*;
|
||||
|
||||
/// Read `bytes`, and check that the reader never reads less than it does when it resumes after
|
||||
/// stray bytes only at the first chunk id found (R53): when that read succeeds, this one does too,
|
||||
/// and every page that read holds with objects is read here unchanged and in the same order.
|
||||
fn read_checked(bytes: &[u8], limits: Limits) -> Result<Drawing, Error> {
|
||||
read_compared(bytes, limits, |p, q| p == q)
|
||||
}
|
||||
|
||||
/// As [`read_checked`], except that a page only has to keep its layers and the number of objects
|
||||
/// on each: a header or a table that only the recovery reads may change their colors and sizes
|
||||
/// (R53).
|
||||
fn read_kept(bytes: &[u8], limits: Limits) -> Result<Drawing, Error> {
|
||||
read_compared(bytes, limits, |p, q| {
|
||||
p.layers.len() == q.layers.len() && p.layers.iter().zip(&q.layers).all(|(a, b)| a.name == b.name && a.objects.len() == b.objects.len())
|
||||
})
|
||||
}
|
||||
|
||||
fn read_compared(bytes: &[u8], limits: Limits, same: fn(&Page, &Page) -> bool) -> Result<Drawing, Error> {
|
||||
let d = read_cmx(bytes, limits);
|
||||
if let Ok(first) = read_cmx_without_recovery(bytes, limits) {
|
||||
let Ok(read) = &d else { panic!("{d:?} where the first chunk id gives {first:?}") };
|
||||
let mut rest = read.pages.iter();
|
||||
for p in first.pages.iter().filter(|p| !p.layers.is_empty()) {
|
||||
assert!(rest.any(|q| same(q, p)), "{p:?} is not read");
|
||||
}
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
fn shape(o: &Object) -> &Shape {
|
||||
match o {
|
||||
Object::Shape(s) => s,
|
||||
@@ -52,7 +80,7 @@ fn a_cmx_file_is_told_from_a_cdr_drawing() {
|
||||
|
||||
#[test]
|
||||
fn pages_layers_groups_and_curves() {
|
||||
let d = read_cmx(&sample(), Limits::default()).unwrap();
|
||||
let d = read_checked(&sample(), Limits::default()).unwrap();
|
||||
assert_eq!(d.version, 0);
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
@@ -107,7 +135,7 @@ fn layer_names_and_layers_without_objects() {
|
||||
end_layer(),
|
||||
end_page(),
|
||||
]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
|
||||
let page = &d.pages[0];
|
||||
assert_eq!(page.size, None);
|
||||
// The empty layer is left out, and the UTF-16 name wins over the 8-bit one.
|
||||
@@ -118,7 +146,7 @@ fn layer_names_and_layers_without_objects() {
|
||||
#[test]
|
||||
fn objects_before_any_layer_get_one() {
|
||||
let p = page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages[0].layers.len(), 1);
|
||||
// The layer is left unnamed, as a `.cdr` drawing's is; the importer names it by its place.
|
||||
assert_eq!(d.pages[0].layers[0].name, "");
|
||||
@@ -134,7 +162,7 @@ fn a_page_without_a_size_takes_the_drawings_bounds() {
|
||||
end_layer(),
|
||||
end_page(),
|
||||
]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
|
||||
let page = &d.pages[0];
|
||||
let side = 100.0 / 25.4 * 72.0;
|
||||
let (w, h) = page.size.unwrap();
|
||||
@@ -150,7 +178,7 @@ fn curves_and_open_groups() {
|
||||
curve(&attrs(None, Some(1), false), &[(0, 0), (100, 0), (100, 100), (0, 100), (200, 200), (300, 200)], &[0x00, 0xc0, 0xc0, 0x84, 0x00, 0x44]);
|
||||
// A group the layer leaves open closes with it.
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), begin_group(), c, end_layer()]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
|
||||
let objects = &d.pages[0].layers[0].objects;
|
||||
let Object::Group { objects: kids, .. } = &objects[0] else { panic!("{objects:?}") };
|
||||
let s = shape(&kids[0]);
|
||||
@@ -164,7 +192,7 @@ fn curves_and_open_groups() {
|
||||
#[test]
|
||||
fn a_curve_without_its_points_is_reported() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), instr(67, &fields(&[field(1, &attrs(Some(1), None, false))])), end_layer()]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
}
|
||||
|
||||
@@ -174,7 +202,7 @@ fn a_layer_name_too_short_to_read_in_utf_16_reads_in_8_bit() {
|
||||
d.extend(b"Art");
|
||||
let layer = instr(11, &fields(&[field(1, &d), field(4, &[3, 0])]));
|
||||
let p = page(&[begin_page(None), layer, square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages[0].layers[0].name, "Art");
|
||||
}
|
||||
|
||||
@@ -192,7 +220,7 @@ fn what_is_not_read_is_reported() {
|
||||
square(&attrs(Some(1), None, true), 0, 0, 1000),
|
||||
end_layer(),
|
||||
]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
|
||||
for w in [Warning::UnsupportedObjects, Warning::UnsupportedFills, Warning::Lenses] {
|
||||
assert!(d.warnings.contains(&w), "{w:?}: {:?}", d.warnings);
|
||||
}
|
||||
@@ -213,7 +241,7 @@ fn colors_of_other_models_and_missing_entries() {
|
||||
square(&attrs(Some(2), None, false), 0, 0, 1000),
|
||||
]));
|
||||
children.push(table(b"rclr", &[color(7, &[1, 2, 3, 4]), color(3, &[255, 0, 0, 255])]));
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::UnknownColors) && d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
let objects = &d.pages[0].layers[0].objects;
|
||||
assert_eq!(shape(&objects[0]).fill, Some(Color::Cmyk([1.0, 0.0, 0.0, 1.0])));
|
||||
@@ -231,7 +259,7 @@ fn gray_cmy_and_rgb_colors_of_the_older_fields() {
|
||||
square(&attrs(Some(3), None, false), 0, 0, 1000),
|
||||
]));
|
||||
children.push(table(b"rclr", &[color(9, &[51]), color(4, &[255, 0, 51]), color(5, &[255, 0, 0])]));
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
let objects = &d.pages[0].layers[0].objects;
|
||||
// The model holds objects front to back: the RGB square, the CMY one, then the gray one.
|
||||
@@ -251,7 +279,7 @@ fn outline_arrowheads_are_reported() {
|
||||
children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(None, Some(1), false), 0, 0, 1000)]));
|
||||
children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rota")));
|
||||
children.push(arrowheads(&[(0, 2)]));
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.warnings, vec![Warning::Arrowheads]);
|
||||
}
|
||||
|
||||
@@ -275,7 +303,7 @@ fn a_long_instruction_and_a_jump_over_image_bytes() {
|
||||
.concat();
|
||||
let mut children = vec![cont(b'4', 1e-7), chunk(b"page", &body)];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
// The images jumped over are not read, and the warning says so.
|
||||
assert_eq!(d.warnings, [Warning::UnsupportedObjects]);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
@@ -286,7 +314,7 @@ fn bytes_after_a_chunk_that_runs_short_are_passed_over() {
|
||||
let stray = vec![0x10, 0x00, 0x16, 0x00, 0x01, 0x0b, 0x00, 0x01, 0, 0, 0, 0, 0, 0, 0, 0xff];
|
||||
let mut children = vec![cont(b'4', 1e-7), stray, list(b"pgls", &[page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)])])];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
@@ -295,12 +323,12 @@ fn bytes_after_a_chunk_that_runs_short_are_passed_over() {
|
||||
fn other_byte_orders_and_coordinate_sizes_are_refused() {
|
||||
let mut f = sample();
|
||||
f[..4].copy_from_slice(b"RIFX");
|
||||
assert_eq!(read_cmx(&f, Limits::default()), Err(Error::Unsupported("big-endian CMX files")));
|
||||
assert_eq!(read_checked(&f, Limits::default()), Err(Error::Unsupported("big-endian CMX files")));
|
||||
let mut children = vec![cont(b'2', 1e-3)];
|
||||
children.extend(tables());
|
||||
assert_eq!(read_cmx(&riff(&children), Limits::default()), Err(Error::Unsupported("CMX files with 16-bit coordinates")));
|
||||
assert_eq!(read_cmx(&riff(&tables()), Limits::default()), Err(Error::Damaged("CMX header")));
|
||||
assert_eq!(read_cmx(&riff(&[cont(b'9', 1e-7)]), Limits::default()), Err(Error::Damaged("CMX header")));
|
||||
assert_eq!(read_checked(&riff(&children), Limits::default()), Err(Error::Unsupported("CMX files with 16-bit coordinates")));
|
||||
assert_eq!(read_checked(&riff(&tables()), Limits::default()), Err(Error::Damaged("CMX header")));
|
||||
assert_eq!(read_checked(&riff(&[cont(b'9', 1e-7)]), Limits::default()), Err(Error::Damaged("CMX header")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -308,7 +336,7 @@ fn a_header_without_a_usable_unit_reads_0_1_micrometers() {
|
||||
for meters in [0.0, -1.0, f64::NAN, 2.0] {
|
||||
let mut children = vec![cont(b'4', meters), page(&[begin_page(Some((2_100_000, 2_970_000)))])];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
let (w, _) = d.pages[0].size.unwrap();
|
||||
assert!(near(w, 210.0 / 25.4 * 72.0), "{meters}: {w}");
|
||||
}
|
||||
@@ -325,7 +353,7 @@ fn groups_past_the_depth_limit_are_left_out() {
|
||||
ins.push(end_group());
|
||||
}
|
||||
ins.push(square(&attrs(Some(1), None, false), 0, 0, 1000));
|
||||
let d = read_cmx(&file(&[page(&ins)]), Limits { depth: 3, ..Limits::default() }).unwrap();
|
||||
let d = read_checked(&file(&[page(&ins)]), Limits { depth: 3, ..Limits::default() }).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::TooDeep));
|
||||
// The square after the groups is still read, beside the three groups kept.
|
||||
let objects = &d.pages[0].layers[0].objects;
|
||||
@@ -346,18 +374,18 @@ fn groups_past_the_depth_limit_are_left_out() {
|
||||
fn counts_past_the_limits_are_bounded() {
|
||||
let ins: Vec<Vec<u8>> = std::iter::once(begin_page(None)).chain((0..50).map(|_| square(&attrs(Some(1), None, false), 0, 0, 1000))).collect();
|
||||
let f = file(&[page(&ins)]);
|
||||
let d = read_cmx(&f, Limits { objects: 10, ..Limits::default() }).unwrap();
|
||||
let d = read_checked(&f, Limits { objects: 10, ..Limits::default() }).unwrap();
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 10);
|
||||
assert!(d.warnings.contains(&Warning::TooDeep));
|
||||
let d = read_cmx(&f, Limits { coordinates: 12, ..Limits::default() }).unwrap();
|
||||
let d = read_checked(&f, Limits { coordinates: 12, ..Limits::default() }).unwrap();
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 2);
|
||||
assert_eq!(read_cmx(&f, Limits { chunks: 20, ..Limits::default() }), Err(Error::Limit("chunk count")));
|
||||
assert_eq!(read_cmx(&f, Limits { input: 10, ..Limits::default() }), Err(Error::Limit("input size")));
|
||||
assert_eq!(read_checked(&f, Limits { chunks: 20, ..Limits::default() }), Err(Error::Limit("chunk count")));
|
||||
assert_eq!(read_checked(&f, Limits { input: 10, ..Limits::default() }), Err(Error::Limit("input size")));
|
||||
let dashed = |n: u16| {
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.push(page(&[begin_page(None), square(&attrs(None, Some(3), false), 0, 0, 1000), square(&attrs(None, Some(3), false), 0, 0, 1000)]));
|
||||
children.extend(tables());
|
||||
read_cmx(&riff(&children), Limits { dashes: usize::from(n), ..Limits::default() }).unwrap()
|
||||
read_checked(&riff(&children), Limits { dashes: usize::from(n), ..Limits::default() }).unwrap()
|
||||
};
|
||||
let d = dashed(3);
|
||||
let o: Vec<usize> = d.pages[0].layers[0].objects.iter().map(|o| shape(o).outline.as_ref().unwrap().dashes.len()).collect();
|
||||
@@ -372,7 +400,7 @@ fn a_curve_cut_short_keeps_the_points_it_holds() {
|
||||
let at = c.windows(2).position(|w| w == [3, 0]).unwrap();
|
||||
c[at] = 9;
|
||||
let p = page(&[begin_page(None), c]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged));
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
@@ -387,7 +415,7 @@ fn a_curve_that_lost_type_bytes_keeps_its_first_points() {
|
||||
}
|
||||
g.extend([0x0c, 0x44]);
|
||||
let c = instr(67, &fields(&[field(1, &attrs(None, Some(1), false)), field(2, &g)]));
|
||||
let d = read_cmx(&file(&[page(&[begin_page(None), c])]), Limits::default()).unwrap();
|
||||
let d = read_checked(&file(&[page(&[begin_page(None), c])]), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
let Geometry::Path(p) = &shape(&d.pages[0].layers[0].objects[0]).geometry else { panic!() };
|
||||
let side = 100.0 / 25.4 * 72.0;
|
||||
@@ -403,14 +431,14 @@ fn a_file_cut_short_of_its_declared_size_is_reported() {
|
||||
let mut f = file(&[]);
|
||||
let declared = (f.len() as u32 - 8 + 100).to_le_bytes();
|
||||
f[4..8].copy_from_slice(&declared);
|
||||
let d = read_cmx(&f, Limits::default()).unwrap();
|
||||
let d = read_checked(&f, Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_that_ends_inside_an_instruction_is_reported() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), vec![1, 0]]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
@@ -420,7 +448,7 @@ fn a_chunk_64_bytes_past_stray_bytes_is_found() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut children = vec![cont(b'4', 1e-7), [vec![1u8; 64], p].concat()];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
@@ -432,7 +460,687 @@ fn stray_letters_with_a_length_past_the_file_are_passed_over() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut children = vec![cont(b'4', 1e-7), [stray, p].concat()];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
/// Stray bytes, then letters whose length covers exactly the page chunk after them, then the page.
|
||||
fn page_inside_stray_letters(stray: &[u8]) -> Vec<u8> {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut b = stray.to_vec();
|
||||
b.extend(b"abcd");
|
||||
b.extend((p.len() as u32).to_le_bytes());
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
riff(&children)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_letters_the_page_is_preferred_to_letters_that_hold_it() {
|
||||
let mut stray = b"wxyz".to_vec();
|
||||
stray.extend(0xFFFF_FF00u32.to_le_bytes());
|
||||
let d = read_checked(&page_inside_stray_letters(&stray), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_the_page_is_preferred_to_letters_that_hold_it() {
|
||||
let d = read_checked(&page_inside_stray_letters(&[1, 1]), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn letters_64_bytes_past_stray_bytes_do_not_hide_the_page_they_hold() {
|
||||
let d = read_checked(&page_inside_stray_letters(&[1; 64]), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_page_after_three_page_headers_that_do_not_read_inside_letters_is_read() {
|
||||
// Stray bytes, then letters whose length covers three page headers that reach its end and
|
||||
// whose instructions do not fit, then the page.
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let len = 24 + p.len();
|
||||
let mut body = Vec::new();
|
||||
for k in 0..3 {
|
||||
body.extend(b"page");
|
||||
body.extend(((len - 8 * k - 8) as u32).to_le_bytes());
|
||||
}
|
||||
body.extend(p);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(b"abcd");
|
||||
b.extend((body.len() as u32).to_le_bytes());
|
||||
b.extend(body);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_recoveries_stop_once_a_read_has_spent_its_allowance() {
|
||||
// Many copies of stray bytes followed by a chunk the reader passes over that holds a page:
|
||||
// the first pages are read, and once the checks have spent the read's allowance the reader
|
||||
// resumes at the chunk that holds each page, as it does without the recovery.
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut unit = vec![1u8; 2];
|
||||
unit.extend(chunk(b"inf1", &p));
|
||||
let copies = 2000;
|
||||
let mut children = vec![cont(b'4', 1e-7), unit.repeat(copies)];
|
||||
children.extend(tables());
|
||||
let f = riff(&children);
|
||||
let d = read_checked(&f, Limits::default()).unwrap();
|
||||
assert!(!d.pages.is_empty() && d.pages.len() < copies, "{} of {copies} pages", d.pages.len());
|
||||
assert!(read_cmx_without_recovery(&f, Limits::default()).unwrap().pages.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_page_past_a_limit_is_left_out_with_a_warning() {
|
||||
let f = page_inside_stray_letters(&[1, 1]);
|
||||
let all = read_cmx(&f, Limits::default()).unwrap().pages.len();
|
||||
assert_eq!(all, 1);
|
||||
let mut cut = 0;
|
||||
for chunks in 1..200 {
|
||||
let Ok(d) = read_checked(&f, Limits { chunks, ..Limits::default() }) else { continue };
|
||||
if d.pages.len() < all {
|
||||
cut += 1;
|
||||
assert!(d.warnings.contains(&Warning::TooDeep), "{chunks}: {:?}", d.warnings);
|
||||
}
|
||||
}
|
||||
assert!(cut > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recovered_page_spends_only_what_the_limits_leave_after_the_other_pages() {
|
||||
// Stray bytes, letters whose length covers a page, the page, then another page: with room for
|
||||
// one object, the last page keeps it and the warning tells of the page left out; with room for
|
||||
// both, the recovered page reads first.
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let q = page(&[begin_page(None), begin_layer("M", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(b"abcd");
|
||||
b.extend((p.len() as u32).to_le_bytes());
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b, q];
|
||||
children.extend(tables());
|
||||
let f = riff(&children);
|
||||
let d = read_checked(&f, Limits { objects: 1, ..Limits::default() }).unwrap();
|
||||
assert_eq!(d.pages.len(), 1, "{:?}", d.pages);
|
||||
let last = d.pages.last().unwrap();
|
||||
assert_eq!((last.layers[0].name.as_str(), last.layers[0].objects.len()), ("M", 1));
|
||||
assert!(d.warnings.contains(&Warning::TooDeep), "{:?}", d.warnings);
|
||||
let d = read_checked(&f, Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.iter().map(|p| p.layers[0].name.as_str()).collect::<Vec<_>>(), ["L", "M"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunks_only_a_recovery_reads_do_not_stop_a_read_that_fits_without_them() {
|
||||
// A page, then letters spelling `page` whose length runs past the file and that hold another
|
||||
// page and an empty chunk: at every chunk limit at which the file opens without the recovery,
|
||||
// it opens with it, and where the recovered page does not fit, the warning tells of it.
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let q = page(&[begin_page(None), begin_layer("M", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]);
|
||||
let mut b = b"page".to_vec();
|
||||
b.extend(0xFFFF_FF00u32.to_le_bytes());
|
||||
b.extend(q);
|
||||
b.extend(chunk(b"junk", &[]));
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.extend(tables());
|
||||
children.push(p);
|
||||
children.push(b);
|
||||
let f = riff(&children);
|
||||
let names = |d: &Drawing| d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.clone()).collect::<Vec<_>>();
|
||||
assert_eq!(names(&read_checked(&f, Limits::default()).unwrap()), ["L", "M"]);
|
||||
let mut cut = 0;
|
||||
for chunks in 1..200 {
|
||||
let limits = Limits { chunks, ..Limits::default() };
|
||||
if read_cmx_without_recovery(&f, limits).is_err() {
|
||||
continue;
|
||||
}
|
||||
let d = read_checked(&f, limits).unwrap();
|
||||
if names(&d) != ["L", "M"] {
|
||||
cut += 1;
|
||||
assert!(d.warnings.contains(&Warning::TooDeep), "{chunks}: {:?}", d.warnings);
|
||||
}
|
||||
}
|
||||
assert!(cut > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_page_is_read_when_the_chunk_found_lands_inside_a_list() {
|
||||
// Stray bytes, then letters whose length ends on the header of an empty page at the end of the
|
||||
// page after them. That empty page's length ends on the first page inside the list that
|
||||
// follows. Walking on from the page reads the same page inside the list, so the page is read.
|
||||
let (name, q) = ["Q", "Qa"]
|
||||
.iter()
|
||||
.map(|n| {
|
||||
let carried = long_instr(-1, &[b"page".as_slice(), &12u32.to_le_bytes()].concat());
|
||||
(*n, [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), carried].concat())
|
||||
})
|
||||
.find(|(_, body)| body.len() % 2 == 0)
|
||||
.unwrap();
|
||||
let r = page(&[begin_page(None), begin_layer("R", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(b"abcd");
|
||||
b.extend((q.len() as u32).to_le_bytes());
|
||||
b.extend(chunk(b"page", &q));
|
||||
b.extend(list(b"pgls", &[r]));
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
let names: Vec<&str> = d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.as_str()).collect();
|
||||
assert_eq!(names, [name, "R"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_page_is_not_read_when_a_list_cuts_short_the_page_both_walks_reach() {
|
||||
// As above, except that the list ends after the header of the page inside it, so walking on
|
||||
// from the inner page reads that page without its body. Walking on from the letters reads the
|
||||
// whole page, so the reader resumes at the letters and the page keeps its square.
|
||||
let (name, q) = ["Q", "Qa"]
|
||||
.iter()
|
||||
.map(|n| {
|
||||
let carried = long_instr(-1, &[b"page".as_slice(), &12u32.to_le_bytes()].concat());
|
||||
(*n, [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), carried].concat())
|
||||
})
|
||||
.find(|(_, body)| body.len() % 2 == 0)
|
||||
.unwrap();
|
||||
let r = page(&[begin_page(None), begin_layer("R", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(b"abcd");
|
||||
b.extend((q.len() as u32).to_le_bytes());
|
||||
b.extend(chunk(b"page", &q));
|
||||
b.extend(b"LIST");
|
||||
b.extend(12u32.to_le_bytes());
|
||||
b.extend(b"pgls");
|
||||
b.extend(r);
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.extend(tables());
|
||||
children.push(b);
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
let names: Vec<&str> = d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.as_str()).collect();
|
||||
assert!(!names.contains(&name), "{names:?}");
|
||||
assert_eq!(names, ["R"]);
|
||||
assert_eq!(d.pages.last().unwrap().layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_page_a_list_cuts_short_only_without_the_recovery_is_judged_as_recovered() {
|
||||
// Stray bytes, then letters whose length ends on the header of a list at the end of the page
|
||||
// after them. The list ends after the header of the next page, so the walk from the letters
|
||||
// reads that page without its body, and the walk from the page inside the letters reads the
|
||||
// whole page. Only the recovery reads that whole page, and it ends inside an instruction, so the
|
||||
// reader leaves it out.
|
||||
let (name, q) = ["Q", "Qa"]
|
||||
.iter()
|
||||
.map(|n| {
|
||||
let carried = long_instr(-1, &[b"LIST".as_slice(), &12u32.to_le_bytes(), b"pgls"].concat());
|
||||
(*n, [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), carried].concat())
|
||||
})
|
||||
.find(|(_, body)| body.len() % 2 == 0)
|
||||
.unwrap();
|
||||
let r = page(&[begin_page(None), begin_layer("R", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer(), vec![1, 0]]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(b"abcd");
|
||||
b.extend((q.len() as u32 - 4).to_le_bytes());
|
||||
b.extend(chunk(b"page", &q));
|
||||
b.extend(r);
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.extend(tables());
|
||||
children.push(b);
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
let names: Vec<&str> = d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.as_str()).collect();
|
||||
assert_eq!(names, [name]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_page_whose_check_stops_at_a_limit_is_not_replaced_by_a_page_inside_it() {
|
||||
// Stray bytes, then letters whose body holds the start of a page of one square. That page's last
|
||||
// instruction carries the page of thirty squares that follows the letters, and ends where it
|
||||
// ends. At a chunk limit that stops the check of the page of thirty squares while the check of
|
||||
// the page inside the letters fits, the page inside the letters never takes its place.
|
||||
let squares = (1..=30).map(|i| square(&attrs(Some(1), None, false), 0, 0, 100 * i));
|
||||
let p = page(&[begin_page(None), begin_layer("P", None)].into_iter().chain(squares).chain([end_layer()]).collect::<Vec<_>>());
|
||||
let carried = long_instr(-1, &p);
|
||||
let head = &carried[..carried.len() - p.len()];
|
||||
let q = ["Q", "Qa"]
|
||||
.iter()
|
||||
.map(|n| [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer(), head.to_vec()].concat())
|
||||
.find(|body| body.len() % 2 == 0)
|
||||
.unwrap();
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(b"abcd");
|
||||
b.extend((q.len() as u32 + 8).to_le_bytes());
|
||||
b.extend(b"page");
|
||||
b.extend(((q.len() + p.len()) as u32).to_le_bytes());
|
||||
b.extend(q);
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.extend(tables());
|
||||
children.push(b);
|
||||
let f = riff(&children);
|
||||
let names = |d: &Drawing| d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.clone()).collect::<Vec<_>>();
|
||||
assert_eq!(names(&read_checked(&f, Limits::default()).unwrap()), ["P"]);
|
||||
for chunks in 1..200 {
|
||||
if let Ok(d) = read_checked(&f, Limits { chunks, ..Limits::default() }) {
|
||||
assert_eq!(names(&d), ["P"], "{chunks}: {:?}", d.warnings);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A page that fills with color 1, then, inside a list, letters spelling `page` whose length runs
|
||||
/// past the list and that hold another page and a color table of one red entry, then `after`.
|
||||
fn page_and_recovered_red(after: &[Vec<u8>]) -> Vec<u8> {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let q = page(&[begin_page(None), begin_layer("M", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]);
|
||||
let mut b = b"page".to_vec();
|
||||
b.extend(0xFFFF_FF00u32.to_le_bytes());
|
||||
b.extend(q);
|
||||
b.extend(table(b"rclr", &[color(5, &[255, 0, 0])]));
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rclr")));
|
||||
children.push(p);
|
||||
children.push(list(b"pgls", &[b]));
|
||||
children.extend(after.iter().cloned());
|
||||
riff(&children)
|
||||
}
|
||||
|
||||
/// The fill of the first object of each page.
|
||||
fn fills(d: &Drawing) -> Vec<Option<Color>> {
|
||||
d.pages.iter().map(|p| shape(&p.layers[0].objects[0]).fill.clone()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_table_only_the_recovery_reads_colors_every_page() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)]);
|
||||
let red = fills(&read_checked(&file(&[p]), Limits::default()).unwrap())[0].clone();
|
||||
assert!(red.is_some());
|
||||
let d = read_kept(&page_and_recovered_red(&[]), Limits::default()).unwrap();
|
||||
assert_eq!(fills(&d), [red.clone(), red]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_table_read_without_the_recovery_wins_over_one_only_the_recovery_reads() {
|
||||
let green = table(b"rclr", &[color(5, &[0, 255, 0])]);
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)]));
|
||||
children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rclr")));
|
||||
children.push(green.clone());
|
||||
let green_fill = fills(&read_checked(&riff(&children), Limits::default()).unwrap())[0].clone();
|
||||
let d = read_checked(&page_and_recovered_red(&[green]), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 2);
|
||||
assert_eq!(fills(&d), [green_fill.clone(), green_fill]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_page_inside_a_chunk_with_more_after_it_is_not_read() {
|
||||
// Stray bytes, a chunk the reader passes over that holds a page followed by another chunk,
|
||||
// then the page: only the last page is read.
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(chunk(b"inf1", &[p.clone(), chunk(b"junk", &[0; 4])].concat()));
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_list_between_stray_bytes_is_read_as_a_list() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let b = [vec![1u8; 2], list(b"pgls", &[p.clone(), p]), vec![1u8; 2]].concat();
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_an_empty_page_header_inside_another_chunk_is_not_a_page() {
|
||||
// Stray bytes, a chunk the reader passes over that holds only an empty page header, then the
|
||||
// page: only the page is read.
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(chunk(b"inf1", &chunk(b"page", &[])));
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_an_empty_page_is_kept_before_the_next_page() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(chunk(b"page", &[]));
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 2);
|
||||
assert!(d.pages[0].layers.is_empty(), "{:?}", d.pages[0].layers);
|
||||
assert_eq!(d.pages[1].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_between_stray_bytes_is_preferred_to_letters_that_end_inside_it() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(b"abcd");
|
||||
b.extend(8u32.to_le_bytes());
|
||||
b.extend(p);
|
||||
b.extend([1u8; 2]);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_page_is_preferred_to_page_letters_that_end_inside_it() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(b"page");
|
||||
b.extend(8u32.to_le_bytes());
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_between_stray_bytes_is_kept() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let b = [vec![1u8; 2], p, vec![1u8; 2]].concat();
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_page_header_that_ends_inside_another_chunk_is_not_a_page() {
|
||||
// Stray bytes, a chunk the reader passes over whose body starts with a short page chunk, more
|
||||
// stray bytes, then the page: only the last page is read.
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut inner = b"page".to_vec();
|
||||
inner.extend(4u32.to_le_bytes());
|
||||
inner.extend([0; 10]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(chunk(b"inf1", &inner));
|
||||
b.extend([1u8; 2]);
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
// The chunk passed over is followed by more stray bytes, and the warning says so.
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_header_too_short_to_read_inside_another_chunk_is_passed_over() {
|
||||
// Stray bytes, then a chunk the reader passes over that holds a one-byte header, then the
|
||||
// header: the drawing opens with the header after it.
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let first = [vec![1u8; 2], chunk(b"inf1", &chunk(b"cont", &[0]))].concat();
|
||||
let mut children = vec![first, cont(b'4', 1e-7), p];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_letters_ending_on_a_layer_name_do_not_hide_the_page() {
|
||||
// Stray bytes, then letters whose length ends on the letters of a layer name inside the page
|
||||
// after them, then the page.
|
||||
let names = ["Background", "aBackground"];
|
||||
let (p, at) = names
|
||||
.iter()
|
||||
.map(|n| page(&[begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]))
|
||||
.find_map(|p| p.windows(4).position(|w| w == b"Back").filter(|at| at % 2 == 0).map(|at| (p, at)))
|
||||
.unwrap();
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(b"abcd");
|
||||
b.extend((at as u32).to_le_bytes());
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_page_followed_by_a_chunk_inside_another_chunk_is_not_read_before_more_stray_bytes() {
|
||||
// Stray bytes, a chunk the reader passes over that holds a page and another chunk, more stray
|
||||
// bytes, then the page: only the last page is read.
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(chunk(b"inf1", &[p.clone(), chunk(b"junk", &[0; 4])].concat()));
|
||||
b.extend([1u8; 2]);
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_header_without_a_coordinate_size_inside_another_chunk_is_passed_over() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let first = [vec![1u8; 2], chunk(b"inf1", &chunk(b"cont", &[0; 60]))].concat();
|
||||
let mut children = vec![first, cont(b'4', 1e-7), p];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_table_inside_another_chunk_that_ends_inside_the_next_page_is_passed_over() {
|
||||
// Stray bytes, a chunk the reader passes over that holds the start of a color table whose
|
||||
// length ends inside the page after more stray bytes: the page is read.
|
||||
let sq = square(&attrs(Some(1), None, false), 0, 0, 1000);
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), sq.clone(), sq.clone(), sq, end_layer()]);
|
||||
let mut inner = b"rclr".to_vec();
|
||||
inner.extend(14u32.to_le_bytes());
|
||||
inner.extend([0; 2]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(chunk(b"inf1", &inner));
|
||||
b.extend([1u8; 2]);
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_between_stray_bytes_is_kept_when_its_body_holds_chunk_letters() {
|
||||
// A layer name near the start of the page holds a color table chunk and another chunk id.
|
||||
let mut tail = b"rclr".to_vec();
|
||||
tail.extend([4, 0, 0, 0, 0, 0, 0, 0]);
|
||||
tail.extend(b"junk");
|
||||
tail.extend([0; 4]);
|
||||
let tail = String::from_utf8(tail).unwrap();
|
||||
let (p, at) = ["", "x"]
|
||||
.iter()
|
||||
.map(|pre| {
|
||||
page(&[begin_page(None), begin_layer(&format!("{pre}{tail}"), None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()])
|
||||
})
|
||||
.find_map(|p| p.windows(4).position(|w| w == b"rclr").filter(|at| at % 2 == 0).map(|at| (p, at)))
|
||||
.unwrap();
|
||||
assert!((8..=64).contains(&at), "{at}");
|
||||
let b = [vec![1u8; 2], p, vec![1u8; 2]].concat();
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_page_too_short_for_an_instruction_inside_another_chunk_is_not_a_page() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(chunk(b"inf1", &chunk(b"page", &[0; 2])));
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_short_page_is_not_hidden_by_a_table_inside_the_chunk_before_it() {
|
||||
// Stray bytes, a chunk the reader passes over that holds the start of a color table whose
|
||||
// length ends inside the short page after more stray bytes: the page is read.
|
||||
let p = page(&[begin_page(None)]);
|
||||
let mut inner = b"rclr".to_vec();
|
||||
inner.extend(10u32.to_le_bytes());
|
||||
inner.extend([0; 2]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(chunk(b"inf1", &inner));
|
||||
b.extend([1u8; 2]);
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_last_page_before_stray_bytes_at_the_end_of_the_file_is_preferred_to_letters_that_end_inside_it() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(b"abcd");
|
||||
b.extend(8u32.to_le_bytes());
|
||||
b.extend(p);
|
||||
b.extend([1u8; 2]);
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.extend(tables());
|
||||
children.push(b);
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_between_stray_bytes_is_kept_when_its_body_holds_a_table_that_reaches_its_end() {
|
||||
// Bytes the page's long instruction carries hold a color table whose length reaches the end
|
||||
// of the page.
|
||||
let sq = square(&attrs(Some(1), None, false), 0, 0, 1000);
|
||||
let mut table = b"rclr".to_vec();
|
||||
let rest = [begin_layer("L", None), sq, end_layer()].concat();
|
||||
// The table's body: the rest of the long instruction (2 bytes), then the instructions after it.
|
||||
table.extend(((2 + rest.len()) as u32).to_le_bytes());
|
||||
table.extend([0; 2]);
|
||||
let carried = long_instr(-1, &table);
|
||||
let p = page(&[begin_page(None), carried, rest]);
|
||||
let at = p.windows(4).position(|w| w == b"rclr").unwrap();
|
||||
assert!(at % 2 == 0 && (8..=64).contains(&at), "{at}");
|
||||
let b = [vec![1u8; 2], p, vec![1u8; 2]].concat();
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_page_whose_first_instruction_is_empty_inside_another_chunk_is_not_a_page() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(chunk(b"inf1", &chunk(b"page", &[0; 4])));
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_between_stray_bytes_is_kept_when_its_body_holds_a_table_that_reaches_its_end() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut c = cont(b'4', 1e-7);
|
||||
let inner = (c.len() - 24) as u32;
|
||||
c[16..20].copy_from_slice(b"rclr");
|
||||
c[20..24].copy_from_slice(&inner.to_le_bytes());
|
||||
let mut children = vec![[vec![1u8; 2], c, vec![1u8; 2]].concat(), p];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_table_whose_entries_do_not_fit_inside_another_chunk_is_passed_over() {
|
||||
// Stray bytes, then a chunk the reader passes over that holds a color table of one entry with
|
||||
// no bytes for it, then the real tables: the colors come from the real tables.
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let read = |junk: &[u8]| {
|
||||
let mut children = vec![cont(b'4', 1e-7), junk.to_vec()];
|
||||
children.extend(tables());
|
||||
children.push(p.clone());
|
||||
read_checked(&riff(&children), Limits::default()).unwrap()
|
||||
};
|
||||
let junk = [vec![1u8; 2], chunk(b"inf1", &chunk(b"rclr", &[1, 0]))].concat();
|
||||
let d = read(&junk);
|
||||
let clean = read(&[]);
|
||||
assert_eq!(format!("{:?}", d.pages), format!("{:?}", clean.pages));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_page_whose_second_instruction_is_empty_inside_another_chunk_is_not_a_page() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(chunk(b"inf1", &chunk(b"page", &[instr(-1, &[]), vec![0; 4]].concat())));
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_page_letters_with_a_length_past_the_list_do_not_hide_the_page() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(b"page");
|
||||
b.extend(0xFFFF_FF00u32.to_le_bytes());
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
@@ -444,7 +1152,7 @@ fn a_dash_pattern_of_zero_lengths_draws_a_solid_line() {
|
||||
children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rdot") && !t.starts_with(b"rotl")));
|
||||
children.push(table(b"rdot", &[dashes(&[0, 0])]));
|
||||
children.push(table(b"rotl", &[outline([3, 1, 2, 1, 1, 1])]));
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
let o = shape(&d.pages[0].layers[0].objects[0]).outline.clone().unwrap();
|
||||
assert!(o.dashes.is_empty(), "{:?}", o.dashes);
|
||||
@@ -462,7 +1170,7 @@ fn a_curve_field_that_lost_points_is_left_out() {
|
||||
g.extend(1_000_000i32.to_le_bytes());
|
||||
g.extend([0x40, 0x42]);
|
||||
let c = instr(67, &fields(&[field(1, &attrs(Some(1), None, false)), field(2, &g)]));
|
||||
let d = read_cmx(&file(&[page(&[begin_page(None), begin_layer("L", None), c])]), Limits::default()).unwrap();
|
||||
let d = read_checked(&file(&[page(&[begin_page(None), begin_layer("L", None), c])]), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
assert!(d.pages[0].layers.is_empty(), "{:?}", d.pages[0].layers);
|
||||
}
|
||||
@@ -476,7 +1184,7 @@ fn a_chunk_whose_id_has_a_digit_is_found_after_stray_bytes() {
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
@@ -493,7 +1201,7 @@ fn padding_and_ids_with_impossible_lengths_are_not_taken_for_chunks() {
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
@@ -513,7 +1221,7 @@ fn after_stray_bytes_a_chunk_the_reader_passes_over_keeps_what_it_holds() {
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
@@ -525,7 +1233,7 @@ fn a_canvas_or_a_container_is_reported() {
|
||||
let mut a = attrs(Some(1), None, false);
|
||||
a[0] |= bit;
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&a, 0, 0, 1000), end_layer()]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
|
||||
assert_eq!(d.warnings, vec![Warning::UnsupportedObjects], "{bit}");
|
||||
assert!(shape(&d.pages[0].layers[0].objects[0]).fill.is_some());
|
||||
}
|
||||
@@ -536,7 +1244,7 @@ fn a_library_color_with_its_name_reads_as_a_spot_color() {
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)]));
|
||||
children.push(table(b"rclr", &[color_record_named(5, [0, 0, 255, 0], Some("Brick 12"))]));
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
let d = read_checked(&riff(&children), Limits::default()).unwrap();
|
||||
match shape(&d.pages[0].layers[0].objects[0]).fill.clone() {
|
||||
Some(Color::Spot { name, tint, look }) => {
|
||||
assert_eq!((name.as_str(), tint), ("Brick 12", 1.0));
|
||||
@@ -553,7 +1261,7 @@ proptest! {
|
||||
fn never_panics_on_garbage(bytes in prop::collection::vec(any::<u8>(), 0..2048)) {
|
||||
let mut b = b"RIFF\0\0\0\0CMX1".to_vec();
|
||||
b.extend(bytes);
|
||||
let _ = read_cmx(&b, Limits::default());
|
||||
let _ = read_kept(&b, Limits::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -563,6 +1271,6 @@ proptest! {
|
||||
for (at, v) in edits {
|
||||
b[at % n] = v;
|
||||
}
|
||||
let _ = read_cmx(&b, Limits::default());
|
||||
let _ = read_kept(&b, Limits::default());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user