Skip to main content

jubarte_markdown/
legacy_doc.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5// Untrusted bytes reach this module: an out-of-range index or an integer
6// overflow is an abort in the Python and WASM consumers, so both are refused
7// here (test fixtures are exempt).
8#![cfg_attr(
9    not(test),
10    deny(clippy::indexing_slicing, clippy::arithmetic_side_effects)
11)]
12
13//! Word 97-2003 (`.doc`) to text, paragraphs, headings, lists and tables:
14//! the main story, no headers or footers.
15//!
16//! A `.doc` is an OLE compound file holding a `WordDocument` stream, whose
17//! File Information Block (FIB) points at the piece table (`Clx`) in the
18//! `0Table` or `1Table` stream ([MS-DOC] 2.5, 2.9.38). The piece table
19//! names where each run of characters lives and whether it is stored as
20//! UTF-16 or as Windows-1252. Paragraph properties come from the PAPX
21//! formatted disk pages (2.9.177): the style (`istd`, mapped through the
22//! style sheet to a heading level), the table marks (`sprmPFInTable`,
23//! `sprmPFTtp`) that turn cell and row ends into a table, and the list
24//! override and level (`sprmPIlfo`, `sprmPIlvl`) whose number format
25//! (`PlfLfo` to `PlfLst` to `LVLF.nfc`) makes a bullet or a number. Bold
26//! and italic come from the CHPX pages (`sprmCFBold`, `sprmCFItalic`),
27//! then from each piece's property modifier (a `Prm0`, or a `Prm1` naming
28//! one of the Clx's `Prc`s) per [MS-DOC] 2.4.6.2.
29//!
30//! Read: the main story text, its paragraphs (empty ones too),
31//! Heading 1-9 and Title styles, bulleted and numbered lists with their
32//! levels, bold and italic, one-level tables whose cell text is plain,
33//! the leading rows that repeat as a header (`sprmTTableHeader`), field
34//! results (codes dropped) and line breaks. Not read: other character
35//! formatting (font, size, colour, underline), list start numbers and
36//! custom number styles beyond `decimal`, headers and footers, notes,
37//! comments, tracked changes, pictures, page setup (the `.docx` is US
38//! Letter), Word 6/95 files (`nFib` below 193) and encrypted or
39//! obfuscated files — refused with `LEGACY_DOC`. `docs/adoption/plans.md`
40//! lists the steps past this minimum.
41//!
42//! The text becomes escaped Markdown, and
43//! [`crate::markdown::markdown_to_docx`] writes the package, so the `.docx`
44//! is the same Word-valid output that `jubarte convert draft.md` writes.
45//! What Markdown cannot say is put back afterwards: Title and Heading
46//! 7-9, empty paragraphs, and which rows repeat as a header.
47//!
48//! Entry points: [`is_compound_file`](crate::legacy_doc::is_compound_file) for
49//! the cheap check; [`read`](crate::legacy_doc::read) for
50//! the structured [`LegacyDocument`](crate::legacy_doc::LegacyDocument);
51//! [`doc_to_markdown`](crate::legacy_doc::doc_to_markdown) and
52//! [`doc_to_docx`](crate::legacy_doc::doc_to_docx) for the two written outputs.
53
54#[cfg(test)]
55use std::sync::atomic::{AtomicUsize, Ordering};
56
57/// Inspections of the legacy field-code stack. The scan must stay linear
58/// in the story length: an all-false stack is not walked per character.
59#[cfg(test)]
60static FIELD_CODE_STEPS: AtomicUsize = AtomicUsize::new(0);
61
62use std::fmt;
63
64/// The first bytes of an OLE compound file.
65const OLE_MAGIC: &[u8] = b"\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1";
66
67/// `wIdent` of a Word binary document.
68const WORD_IDENT: u16 = 0xA5EC;
69
70/// Lowest `nFib` of the Word 97 format; Word 6 and 95 files are older.
71const NFIB_WORD97: u16 = 0x00C1;
72
73/// End of a chain in the compound file's allocation table.
74const END_OF_CHAIN: u32 = 0xFFFF_FFFE;
75
76/// No sector, or no directory entry.
77const NO_STREAM: u32 = 0xFFFF_FFFF;
78
79/// Why a `.doc` could not be read, formatted as `LEGACY_DOC: …` on the wire.
80#[derive(Clone, Debug, PartialEq, Eq)]
81pub struct LegacyDocError {
82    message: String,
83}
84
85impl LegacyDocError {
86    fn new(message: impl Into<String>) -> Self {
87        Self {
88            message: message.into(),
89        }
90    }
91}
92
93impl fmt::Display for LegacyDocError {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        write!(f, "LEGACY_DOC: {}", self.message)
96    }
97}
98
99impl std::error::Error for LegacyDocError {}
100
101type Result<T> = std::result::Result<T, LegacyDocError>;
102
103/// One block of the main story, in document order.
104#[derive(Clone, Debug, PartialEq, Eq)]
105pub enum Block {
106    /// A paragraph.
107    Paragraph(Paragraph),
108    /// A table.
109    Table(Table),
110}
111
112/// A table of the main story.
113#[derive(Clone, Debug, Default, PartialEq, Eq)]
114pub struct Table {
115    /// Rows of cells; each cell's paragraphs are joined by a single space.
116    /// Cell text is plain (no bold/italic split, no nested tables).
117    pub rows: Vec<Vec<String>>,
118    /// Leading rows Word repeats as a header on each page
119    /// (`sprmTTableHeader`); 0 when the first row is data.
120    pub header_rows: usize,
121}
122
123/// A paragraph of the main story. One with no text (or only spaces) is an
124/// empty paragraph Word keeps, often to space the text out.
125#[derive(Clone, Debug, Default, PartialEq, Eq)]
126pub struct Paragraph {
127    /// `Some(1..=9)` for Heading 1-9, `Some(0)` for Title, `None` for a
128    /// non-heading paragraph.
129    pub heading: Option<u8>,
130    /// The list level, when the paragraph is numbered or bulleted.
131    pub list: Option<ListItem>,
132    /// Runs of text, one (bold, italic) pair each. A literal `\n` is a line
133    /// break (`w:br` / `0x0B`).
134    pub spans: Vec<Span>,
135}
136
137impl Paragraph {
138    /// The paragraph's text, without formatting: the spans concatenated in
139    /// order, including line breaks.
140    #[must_use]
141    pub fn text(&self) -> String {
142        self.spans.iter().map(|span| span.text.as_str()).collect()
143    }
144}
145
146/// A run of text with one bold and italic setting.
147#[derive(Clone, Debug, Default, PartialEq, Eq)]
148pub struct Span {
149    /// The text.
150    pub text: String,
151    /// Bold.
152    pub bold: bool,
153    /// Italic.
154    pub italic: bool,
155}
156
157/// A paragraph's place in a list.
158#[derive(Clone, Copy, Debug, PartialEq, Eq)]
159pub struct ListItem {
160    /// Numbered (any number format) rather than bulleted.
161    pub ordered: bool,
162    /// Level, 0 for the outermost.
163    pub level: u8,
164}
165
166/// The main story of a `.doc`, the only place this module reads from.
167#[derive(Clone, Debug, Default, PartialEq, Eq)]
168pub struct LegacyDocument {
169    /// Paragraphs and tables, in document order.
170    pub blocks: Vec<Block>,
171}
172
173/// Whether `bytes` start with the OLE compound-file magic (`.doc`, or an
174/// encrypted document of any Word version).
175#[must_use]
176pub fn is_compound_file(bytes: &[u8]) -> bool {
177    bytes.starts_with(OLE_MAGIC)
178}
179
180/// Read the main story of a Word 97-2003 document.
181///
182/// # Errors
183///
184/// [`LegacyDocError`] when the file exceeds the input byte budget
185/// ([`crate::admission::InputLimits::max_compressed_bytes`]), the bytes
186/// are not a compound file, hold no `WordDocument` stream (an encrypted
187/// `.docx`, a spreadsheet), predate Word 97, are encrypted, or whose
188/// tables point outside their streams (the piece table, the style sheet,
189/// the property bin tables and their pages, the list tables, the section
190/// table) or contradict themselves (pieces that do not cover the main
191/// story, or that run backwards).
192pub fn read(bytes: &[u8]) -> Result<LegacyDocument> {
193    let limit = crate::admission::InputLimits::default().max_compressed_bytes;
194    let size = bytes.len() as u64;
195    if size > limit {
196        return Err(LegacyDocError::new(format!(
197            "the file is {size} bytes; it exceeds the input byte budget of {limit}"
198        )));
199    }
200    let file = CompoundFile::open(bytes)?;
201    let word = file.stream("WordDocument").ok_or_else(|| {
202        LegacyDocError::new(
203            "no WordDocument stream: an encrypted document or not a Word file; open it in Word and save it as .docx without a password",
204        )
205    })?;
206    let fib = Fib::parse(&word)?;
207    let table = file
208        .stream(if fib.table_one { "1Table" } else { "0Table" })
209        .ok_or_else(|| LegacyDocError::new("the table stream the FIB names is missing"))?;
210    let pieces = pieces(&table, fib.fc_clx, fib.lcb_clx)?;
211    let chars = main_text(&word, &pieces, fib.ccp_text)?;
212    let styles = heading_styles(&table, fib.fc_stshf, fib.lcb_stshf)?;
213    let papx = FkpIndex::new(
214        &word,
215        &table,
216        (fib.fc_plcf_bte_papx, fib.lcb_plcf_bte_papx),
217        Fkp::Paragraph,
218    )?;
219    let chpx = FkpIndex::new(
220        &word,
221        &table,
222        (fib.fc_plcf_bte_chpx, fib.lcb_plcf_bte_chpx),
223        Fkp::Character,
224    )?;
225    let lists = Lists::new(&table, fib.plf_lst, fib.plf_lfo)?;
226    let story = Story {
227        papx: &papx,
228        chpx: &chpx,
229        styles: &styles,
230        lists: &lists,
231        section_marks: section_marks(&table, fib.plcf_sed)?,
232    };
233    Ok(LegacyDocument {
234        blocks: story.blocks(&chars),
235    })
236}
237
238/// A `.doc` as Markdown: headings, paragraphs and GitHub tables, every
239/// Markdown-significant character escaped.
240///
241/// # Errors
242///
243/// As [`read`].
244pub fn doc_to_markdown(bytes: &[u8]) -> Result<String> {
245    Ok(to_markdown(&read(bytes)?))
246}
247
248/// A `.doc` as a `.docx` package (US Letter, built-in styles).
249///
250/// # Errors
251///
252/// As [`read`], or when the rewritten package cannot be
253/// serialized to bytes.
254pub fn doc_to_docx(bytes: &[u8]) -> Result<Vec<u8>> {
255    document_to_docx(&read(bytes)?)
256}
257
258/// The blocks written as a `.docx` through the Markdown writer, then what
259/// Markdown cannot say put back: Title and Heading 7-9, empty paragraphs,
260/// and which table rows repeat as headers.
261fn document_to_docx(document: &LegacyDocument) -> Result<Vec<u8>> {
262    let placeholder = empty_placeholder(document);
263    let markdown = blocks_to_markdown(document, Some(&placeholder));
264    let options = crate::markdown::DocxOptions {
265        critic: false,
266        ..crate::markdown::DocxOptions::default()
267    };
268    let docx = crate::markdown::markdown_to_docx(&markdown, &options)
269        .map(|written| written.docx)
270        .map_err(|error| LegacyDocError::new(format!("writing the .docx: {error}")))?;
271    let styles: Vec<String> = document
272        .blocks
273        .iter()
274        .filter_map(|block| match block {
275            Block::Paragraph(paragraph) => paragraph.heading,
276            Block::Table(_) => None,
277        })
278        .map(|level| match level {
279            0 => "Title".to_string(),
280            level => format!("Heading{level}"),
281        })
282        .collect();
283    let restyle = styles
284        .iter()
285        .any(|id| matches!(id.as_str(), "Title" | "Heading7" | "Heading8" | "Heading9"));
286    let empties: usize = document
287        .blocks
288        .iter()
289        .filter_map(|block| match block {
290            Block::Paragraph(p) if p.text().trim().is_empty() => Some(placeholder_lines(p)),
291            _ => None,
292        })
293        .sum();
294    let header_rows: Vec<usize> = document
295        .blocks
296        .iter()
297        .filter_map(|block| match block {
298            Block::Table(table) => Some(table.header_rows),
299            Block::Paragraph(_) => None,
300        })
301        .collect();
302    if !restyle && empties == 0 && header_rows.iter().all(|&rows| rows == 1) {
303        return Ok(docx);
304    }
305
306    let mut package = crate::opc::PartFs::open(&docx).map_err(|e| docx_error(&e.to_string()))?;
307    let mut body = package
308        .part_string("word/document.xml")
309        .ok_or_else(|| docx_error("no document part"))?;
310    if restyle {
311        body = restyle_headings(&body, &styles)?;
312    }
313    if empties > 0 {
314        body = empty_placeholders(&body, &placeholder, empties)?;
315    }
316    body = repeat_header_rows(&body, &header_rows)?;
317    package.set_part("word/document.xml", body.into_bytes());
318    if restyle {
319        define_styles(&mut package, &styles)?;
320    }
321    package.to_zip().map_err(|e| docx_error(&e.to_string()))
322}
323
324fn docx_error(what: &str) -> LegacyDocError {
325    LegacyDocError::new(format!("writing the .docx: {what}"))
326}
327
328/// A word that stands in for an empty paragraph's text on its way through
329/// the Markdown writer: letters and digits only (nothing to escape, and the
330/// writer drops private-use characters), and in none of the document's text.
331/// The text is read once: every number that follows the stem in it is
332/// taken (`…123` takes words 1, 12 and 123; `…05` takes word 0 only), and
333/// the word is the stem with the smallest free number. Cells are read one
334/// by one: the Markdown puts a `|` between them, so a word split across two
335/// cells never reaches the writer whole.
336fn empty_placeholder(document: &LegacyDocument) -> String {
337    const STEM: &str = "jubarteemptyparagraph";
338    let mut taken = std::collections::HashSet::new();
339    let mut note = |text: &str| {
340        for (at, _) in text.match_indices(STEM) {
341            let after = text[at..].strip_prefix(STEM).unwrap_or_default();
342            let digits = after.chars().map_while(|c| c.to_digit(10));
343            let mut number = 0u32;
344            for (index, digit) in digits.enumerate() {
345                // A word's number has no leading zero.
346                if index == 1 && number == 0 {
347                    break;
348                }
349                let Some(next) = number.checked_mul(10).and_then(|n| n.checked_add(digit)) else {
350                    break;
351                };
352                number = next;
353                taken.insert(number);
354            }
355        }
356    };
357    for block in &document.blocks {
358        match block {
359            Block::Paragraph(paragraph) => note(&paragraph.text()),
360            Block::Table(table) => table.rows.iter().flatten().for_each(|cell| note(cell)),
361        }
362    }
363    let free = (0u32..).find(|n| !taken.contains(n)).unwrap_or_default();
364    format!("{STEM}{free}")
365}
366
367/// How many placeholders an empty paragraph is written with: one a line.
368fn placeholder_lines(paragraph: &Paragraph) -> usize {
369    paragraph.text().matches('\n').count().saturating_add(1)
370}
371
372/// `body` with each of the `count` runs holding `placeholder` taken out,
373/// leaving the empty paragraphs with their style and their line breaks.
374fn empty_placeholders(body: &str, placeholder: &str, count: usize) -> Result<String> {
375    let run = format!("<w:r><w:t xml:space=\"preserve\">{placeholder}</w:t></w:r>");
376    if body.matches(run.as_str()).count() != count {
377        return Err(docx_error("an empty paragraph the writer did not keep"));
378    }
379    let out = body.replace(run.as_str(), "");
380    if out.contains(placeholder) {
381        return Err(docx_error("an empty paragraph the writer did not keep"));
382    }
383    Ok(out)
384}
385
386/// `body` with each table's first `header_rows` rows (by table, in order)
387/// marked to repeat as a header and the rest not; the writer marks the
388/// first row of every table.
389fn repeat_header_rows(body: &str, header_rows: &[usize]) -> Result<String> {
390    const HEADER: &str = "<w:trPr><w:tblHeader/></w:trPr>";
391    let mut tables = body.split("<w:tbl>");
392    let mut out = tables.next().unwrap_or("").to_string();
393    let mut wanted = header_rows.iter();
394    for table in tables {
395        let &rows = wanted
396            .next()
397            .ok_or_else(|| docx_error("more tables than the document has"))?;
398        out.push_str("<w:tbl>");
399        let mut parts = table.split("<w:tr>");
400        out.push_str(parts.next().unwrap_or(""));
401        for (index, row) in parts.enumerate() {
402            out.push_str("<w:tr>");
403            if index < rows {
404                out.push_str(HEADER);
405            }
406            out.push_str(row.strip_prefix(HEADER).unwrap_or(row));
407        }
408    }
409    if wanted.next().is_some() {
410        return Err(docx_error("fewer tables than the document has"));
411    }
412    Ok(out)
413}
414
415/// `body` with its heading paragraphs, in order, given the styles `styles`
416/// names.
417fn restyle_headings(body: &str, styles: &[String]) -> Result<String> {
418    const OPEN: &str = "<w:pStyle w:val=\"Heading";
419    let mut out = String::with_capacity(body.len());
420    let mut rest = body;
421    let mut wanted = styles.iter();
422    while let Some((before, after)) = rest.split_once(OPEN) {
423        out.push_str(before);
424        let quote = after
425            .find('"')
426            .ok_or_else(|| docx_error("a broken heading style"))?;
427        let style = wanted
428            .next()
429            .ok_or_else(|| docx_error("more heading paragraphs than headings"))?;
430        out.push_str("<w:pStyle w:val=\"");
431        out.push_str(style);
432        rest = after
433            .get(quote..)
434            .ok_or_else(|| docx_error("a broken heading style"))?;
435    }
436    out.push_str(rest);
437    if wanted.next().is_some() {
438        return Err(docx_error("fewer heading paragraphs than headings"));
439    }
440    Ok(out)
441}
442
443/// Define in the package's style sheet each of `styles` it lacks.
444fn define_styles(package: &mut crate::opc::PartFs, styles: &[String]) -> Result<()> {
445    let mut sheet = package
446        .part_string("word/styles.xml")
447        .ok_or_else(|| docx_error("no styles part"))?;
448    let mut defined: Vec<&str> = Vec::new();
449    for style in styles {
450        if defined.contains(&style.as_str()) || sheet.contains(&format!("w:styleId=\"{style}\"")) {
451            continue;
452        }
453        let definition = crate::markdown::xml::style_definition(style)
454            .ok_or_else(|| docx_error("a heading style without a definition"))?;
455        let end = sheet
456            .rfind("</w:styles>")
457            .ok_or_else(|| docx_error("a styles part without its end"))?;
458        sheet.insert_str(end, &definition);
459        defined.push(style);
460    }
461    package.set_part("word/styles.xml", sheet.into_bytes());
462    Ok(())
463}
464
465/// The document's blocks as Markdown. Empty paragraphs are left out:
466/// Markdown has no way to hold one. A GitHub table always has a header
467/// row, so a table's first row is one here whatever
468/// [`Table::header_rows`] says.
469#[must_use]
470pub fn to_markdown(document: &LegacyDocument) -> String {
471    blocks_to_markdown(document, None)
472}
473
474/// The blocks as Markdown; an empty paragraph is left out, or with
475/// `empty`, written as that text (for the `.docx` writer to take out).
476fn blocks_to_markdown(document: &LegacyDocument, empty: Option<&str>) -> String {
477    let mut out = String::new();
478    for block in &document.blocks {
479        if let Block::Paragraph(paragraph) = block
480            && paragraph.text().trim().is_empty()
481        {
482            let Some(placeholder) = empty else {
483                continue;
484            };
485            // One placeholder a line, so the paragraph's line breaks
486            // survive as `w:br` runs between them.
487            let lines = vec![placeholder; placeholder_lines(paragraph)];
488            let placeholder = Paragraph {
489                spans: vec![Span {
490                    text: lines.join("\n"),
491                    ..Span::default()
492                }],
493                ..paragraph.clone()
494            };
495            push_block(&mut out, &Block::Paragraph(placeholder));
496            continue;
497        }
498        push_block(&mut out, block);
499    }
500    out
501}
502
503/// One block as Markdown, then a blank line.
504fn push_block(out: &mut String, block: &Block) {
505    {
506        match block {
507            Block::Paragraph(paragraph) => match (paragraph.heading, paragraph.list) {
508                (Some(level), _) => {
509                    out.push_str(&"#".repeat(usize::from(level.clamp(1, 6))));
510                    out.push(' ');
511                    // A heading's bold is its style's, and Markdown cannot
512                    // unbold a heading; a toggle that inverts the style
513                    // (`0x81`) would otherwise read as bold.
514                    // A heading is one Markdown line: its manual line breaks
515                    // go in as `<br>`, which the `.docx` writer turns back
516                    // into `w:br` (an empty heading's one placeholder a line
517                    // included).
518                    let mut lines: Vec<Vec<Span>> = vec![Vec::new()];
519                    for span in &paragraph.spans {
520                        for (index, text) in span.text.split('\n').enumerate() {
521                            if index > 0 {
522                                lines.push(Vec::new());
523                            }
524                            if let Some(line) = lines.last_mut() {
525                                line.push(Span {
526                                    text: text.to_string(),
527                                    bold: false,
528                                    ..span.clone()
529                                });
530                            }
531                        }
532                    }
533                    let rendered: Vec<String> =
534                        lines.iter().map(|line| render_spans(line)).collect();
535                    out.push_str(&rendered.join("<br>"));
536                }
537                (None, Some(item)) => {
538                    // Four spaces a level nests under a bullet ("- ", content
539                    // at 2) and under a number ("1. ", content at 3) alike.
540                    let (marker, indent) = if item.ordered {
541                        ("1. ", "    ")
542                    } else {
543                        ("- ", "    ")
544                    };
545                    out.push_str(&indent.repeat(usize::from(item.level)));
546                    out.push_str(marker);
547                    out.push_str(&render_spans(&paragraph.spans));
548                }
549                (None, None) => out.push_str(&render_spans(&paragraph.spans)),
550            },
551            Block::Table(Table { rows, .. }) => {
552                let width = rows.iter().map(Vec::len).max().unwrap_or(0).max(1);
553                for (index, row) in rows.iter().enumerate() {
554                    out.push('|');
555                    for column in 0..width {
556                        let cell = row.get(column).map_or("", String::as_str);
557                        out.push(' ');
558                        out.push_str(&escape_line(cell));
559                        out.push_str(" |");
560                    }
561                    out.push('\n');
562                    if index == 0 {
563                        out.push('|');
564                        out.push_str(&"---|".repeat(width));
565                        out.push('\n');
566                    }
567                }
568                // The loop above ended on a newline; the block separator
569                // below adds the blank line.
570                out.pop();
571            }
572        }
573        out.push_str("\n\n");
574    }
575}
576
577/// Spans as Markdown: `**bold**`, `*italic*`, `***both***`, the markers
578/// inside any spaces around the text (`** a**` is not emphasis), a line
579/// break as a backslash at the end of the line.
580fn render_spans(spans: &[Span]) -> String {
581    let mut merged: Vec<Span> = Vec::new();
582    for span in spans {
583        match merged.last_mut() {
584            Some(last) if last.bold == span.bold && last.italic == span.italic => {
585                last.text.push_str(&span.text);
586            }
587            _ => merged.push(span.clone()),
588        }
589    }
590    let mut out = String::new();
591    for span in &merged {
592        let core = span.text.trim();
593        if core.is_empty() {
594            out.push_str(&span.text.replace('\n', "\\\n"));
595            continue;
596        }
597        let lead = span.text.len().saturating_sub(span.text.trim_start().len());
598        let tail = span.text.trim_end().len();
599        let marker = match (span.bold, span.italic) {
600            (true, true) => "***",
601            (true, false) => "**",
602            (false, true) => "*",
603            (false, false) => "",
604        };
605        out.push_str(span.text.get(..lead).unwrap_or(""));
606        out.push_str(marker);
607        let lines: Vec<String> = core.split('\n').map(escape_line).collect();
608        out.push_str(&lines.join("\\\n"));
609        out.push_str(marker);
610        out.push_str(span.text.get(tail..).unwrap_or(""));
611    }
612    out.trim().to_string()
613}
614
615// Characters examined while deciding whether a `.` or `)` still has an
616// all-ASCII-digit prefix. Re-reading that prefix at every delimiter is
617// quadratic; one pass is one step per character. The tests reject the
618// rescan. The count is per thread, so tests running together do not
619// share it.
620#[cfg(test)]
621thread_local! {
622    pub(super) static LIST_PREFIX_STEPS: std::cell::Cell<usize> =
623        const { std::cell::Cell::new(0) };
624}
625
626/// Count `steps` characters of the prefix decision. Test-only; an empty
627/// inline function in production builds, so the runtime cost is zero.
628#[cfg(test)]
629#[cfg_attr(all(coverage_nightly, test), coverage(off))]
630#[inline]
631fn count_list_prefix_steps(steps: usize) {
632    LIST_PREFIX_STEPS.with(|total| total.set(total.get() + steps));
633}
634
635#[cfg(not(test))]
636#[cfg_attr(all(coverage_nightly, test), coverage(off))]
637#[inline]
638fn count_list_prefix_steps(_steps: usize) {}
639
640/// Escape one line of text so Markdown reads it back as the same text.
641fn escape_line(text: &str) -> String {
642    let text = text.trim();
643    let mut out = String::with_capacity(text.len());
644    // Whether every character before the current one is an ASCII digit.
645    // `1.` or `1)` opens a list only then. Carrying the answer decides each
646    // delimiter in constant time instead of re-reading the prefix (#1503).
647    let mut prefix_is_digits = true;
648    for (index, ch) in text.char_indices() {
649        let at_start = index == 0;
650        let escape = match ch {
651            '\\' | '`' | '*' | '_' | '[' | ']' | '<' | '>' | '|' | '#' | '~' | '$' | '&' | '{'
652            | '}' | '!' => true,
653            '-' | '+' | '=' => at_start,
654            '.' | ')' => {
655                // `1.` or `1)` at the start of a line opens a list.
656                prefix_is_digits && !at_start
657            }
658            _ => false,
659        };
660        if escape {
661            out.push('\\');
662        }
663        out.push(ch);
664        // One character of the pass: keep the all-digits answer current.
665        count_list_prefix_steps(1);
666        prefix_is_digits &= ch.is_ascii_digit();
667    }
668    out
669}
670
671// ---------------------------------------------------------------------------
672// Compound file (MS-CFB)
673// ---------------------------------------------------------------------------
674
675fn u16_at(bytes: &[u8], offset: usize) -> Option<u16> {
676    let end = offset.checked_add(2)?;
677    let slice = bytes.get(offset..end)?;
678    Some(u16::from_le_bytes(slice.try_into().ok()?))
679}
680
681fn u32_at(bytes: &[u8], offset: usize) -> Option<u32> {
682    let end = offset.checked_add(4)?;
683    let slice = bytes.get(offset..end)?;
684    Some(u32::from_le_bytes(slice.try_into().ok()?))
685}
686
687fn index(value: u32) -> Option<usize> {
688    usize::try_from(value).ok()
689}
690
691/// A table the FIB names in the table stream (`fc`, `lcb`): `None` when
692/// it is absent (`lcb` 0), an error when it does not fit the stream (a
693/// corrupt file would otherwise convert without its styles, lists or
694/// formatting).
695fn fib_table<'a>(table: &'a [u8], (fc, lcb): (u32, u32), what: &str) -> Result<Option<&'a [u8]>> {
696    if lcb == 0 {
697        return Ok(None);
698    }
699    index(fc)
700        .zip(index(lcb))
701        .and_then(|(from, len)| table.get(from..from.checked_add(len)?))
702        .map(Some)
703        .ok_or_else(|| LegacyDocError::new(format!("the {what} points outside the table stream")))
704}
705
706/// A directory entry: name, type, first sector and size.
707struct DirEntry {
708    name: String,
709    kind: u8,
710    left: u32,
711    right: u32,
712    child: u32,
713    start: u32,
714    size: u64,
715}
716
717struct CompoundFile<'a> {
718    bytes: &'a [u8],
719    sector_size: usize,
720    mini_sector_size: usize,
721    mini_cutoff: u64,
722    fat: Vec<u32>,
723    mini_fat: Vec<u32>,
724    entries: Vec<DirEntry>,
725    mini_stream: Vec<u8>,
726}
727
728impl<'a> CompoundFile<'a> {
729    fn open(bytes: &'a [u8]) -> Result<Self> {
730        let bad = || LegacyDocError::new("not a readable OLE compound file");
731        if !is_compound_file(bytes) {
732            return Err(LegacyDocError::new("not an OLE compound file (.doc)"));
733        }
734        let major = u16_at(bytes, 0x1A).ok_or_else(bad)?;
735        let sector_shift = u16_at(bytes, 0x1E).ok_or_else(bad)?;
736        let mini_shift = u16_at(bytes, 0x20).ok_or_else(bad)?;
737        // Version 3 has 512-byte sectors and version 4 4096-byte ones
738        // ([MS-CFB] 2.2); any other pairing is not a compound file.
739        if !matches!((major, sector_shift), (3, 9) | (4, 12)) || mini_shift != 6 {
740            return Err(bad());
741        }
742        let v4 = major == 4;
743        let sector_size = 1usize << sector_shift;
744        let mini_sector_size = 1usize << mini_shift;
745        let fat_sectors = u32_at(bytes, 0x2C).ok_or_else(bad)?;
746        let first_dir = u32_at(bytes, 0x30).ok_or_else(bad)?;
747        let mini_cutoff = u64::from(u32_at(bytes, 0x38).ok_or_else(bad)?);
748        let first_mini_fat = u32_at(bytes, 0x3C).ok_or_else(bad)?;
749        let first_difat = u32_at(bytes, 0x44).ok_or_else(bad)?;
750        let difat_sectors = u32_at(bytes, 0x48).ok_or_else(bad)?;
751
752        let max_sectors = bytes.len().checked_div(sector_size).unwrap_or(0);
753        let fat = Self::read_fat(
754            bytes,
755            sector_size,
756            fat_sectors,
757            first_difat,
758            difat_sectors,
759            max_sectors,
760        )?;
761
762        let mut file = Self {
763            bytes,
764            sector_size,
765            mini_sector_size,
766            mini_cutoff,
767            fat,
768            mini_fat: Vec::new(),
769            entries: Vec::new(),
770            mini_stream: Vec::new(),
771        };
772        file.load_directory(first_dir, max_sectors, v4)?;
773        file.load_mini_fat(first_mini_fat, max_sectors)?;
774        file.load_mini_stream(max_sectors)?;
775        Ok(file)
776    }
777
778    fn read_fat(
779        bytes: &[u8],
780        sector_size: usize,
781        fat_sectors: u32,
782        first_difat: u32,
783        difat_sectors: u32,
784        max_sectors: usize,
785    ) -> Result<Vec<u32>> {
786        let bad = || LegacyDocError::new("not a readable OLE compound file");
787        let mut fat_locations: Vec<u32> = (0..109)
788            .filter_map(|i: usize| u32_at(bytes, 0x4C_usize.checked_add(i.checked_mul(4)?)?))
789            .filter(|&s| s != NO_STREAM)
790            .collect();
791        // DIFAT sectors past the header: 127 (or 1023) entries and a link.
792        let per_difat = sector_size / 4;
793        let mut next = first_difat;
794        let mut seen = 0u32;
795        // A chain longer than the file has sectors is a cycle.
796        let difat_limit = difat_sectors.min(u32::try_from(max_sectors).unwrap_or(u32::MAX));
797        while next != END_OF_CHAIN && next != NO_STREAM && seen < difat_limit {
798            let sector = sector_slice(bytes, sector_size, next).ok_or_else(bad)?;
799            for i in 0..per_difat.saturating_sub(1) {
800                let entry = u32_at(sector, i.checked_mul(4).ok_or_else(bad)?).ok_or_else(bad)?;
801                // The file cannot hold more FAT sectors than sectors.
802                if entry != NO_STREAM && fat_locations.len() < max_sectors {
803                    fat_locations.push(entry);
804                }
805            }
806            next = u32_at(sector, per_difat.saturating_sub(1).saturating_mul(4)).ok_or_else(bad)?;
807            seen = seen.saturating_add(1);
808        }
809        fat_locations.truncate(index(fat_sectors).ok_or_else(bad)?.min(max_sectors));
810        // Each FAT sector is a different sector; a repeat is a corrupt
811        // (or looping) DIFAT.
812        let mut sorted = fat_locations.clone();
813        sorted.sort_unstable();
814        if sorted.array_windows().any(|[a, b]| a == b) {
815            return Err(LegacyDocError::new("a FAT sector is listed twice"));
816        }
817        let mut fat = Vec::with_capacity(fat_locations.len().saturating_mul(per_difat));
818        for location in fat_locations {
819            let sector = sector_slice(bytes, sector_size, location).ok_or_else(bad)?;
820            fat.extend(
821                sector
822                    .as_chunks::<4>()
823                    .0
824                    .iter()
825                    .map(|c| u32::from_le_bytes(*c)),
826            );
827        }
828        Ok(fat)
829    }
830
831    fn load_directory(&mut self, first_dir: u32, max_sectors: usize, v4: bool) -> Result<()> {
832        let bad = || LegacyDocError::new("not a readable OLE compound file");
833        let directory = self.chain(first_dir, None, max_sectors).ok_or_else(bad)?;
834        self.entries = directory
835            .as_chunks::<128>()
836            .0
837            .iter()
838            .filter_map(|raw| DirEntry::parse(raw, v4))
839            .collect();
840        Ok(())
841    }
842
843    fn load_mini_fat(&mut self, first_mini_fat: u32, max_sectors: usize) -> Result<()> {
844        let bad = || LegacyDocError::new("not a readable OLE compound file");
845        if first_mini_fat != END_OF_CHAIN && first_mini_fat != NO_STREAM {
846            let table = self
847                .chain(first_mini_fat, None, max_sectors)
848                .ok_or_else(bad)?;
849            self.mini_fat = table
850                .as_chunks::<4>()
851                .0
852                .iter()
853                .map(|c| u32::from_le_bytes(*c))
854                .collect();
855        }
856        Ok(())
857    }
858
859    fn load_mini_stream(&mut self, max_sectors: usize) -> Result<()> {
860        let bad = || LegacyDocError::new("not a readable OLE compound file");
861        let root = self.entries.first().ok_or_else(bad)?;
862        if root.kind != 5 {
863            return Err(bad());
864        }
865        let (root_start, root_size) = (root.start, root.size);
866        if root_start != END_OF_CHAIN && root_start != NO_STREAM {
867            self.mini_stream = self
868                .chain(root_start, Some(root_size), max_sectors)
869                .ok_or_else(bad)?;
870        }
871        Ok(())
872    }
873
874    /// Follow a regular-sector chain, stopping after `limit` sectors (a
875    /// cycle cannot loop forever).
876    fn chain(&self, start: u32, size: Option<u64>, limit: usize) -> Option<Vec<u8>> {
877        let mut out = Vec::new();
878        let mut sector = start;
879        let mut steps = 0usize;
880        while sector != END_OF_CHAIN {
881            if steps >= limit {
882                return None;
883            }
884            out.extend_from_slice(sector_slice(self.bytes, self.sector_size, sector)?);
885            sector = *self.fat.get(index(sector)?)?;
886            steps = steps.checked_add(1)?;
887        }
888        if let Some(size) = size {
889            out.truncate(usize::try_from(size).ok()?);
890        }
891        Some(out)
892    }
893
894    fn mini_chain(&self, start: u32, size: u64) -> Option<Vec<u8>> {
895        let mut out = Vec::new();
896        let mut sector = start;
897        let limit = self
898            .mini_stream
899            .len()
900            .checked_div(self.mini_sector_size)
901            .unwrap_or(0);
902        let mut steps = 0usize;
903        while sector != END_OF_CHAIN {
904            if steps >= limit {
905                return None;
906            }
907            let from = index(sector)?.checked_mul(self.mini_sector_size)?;
908            let to = from.checked_add(self.mini_sector_size)?;
909            out.extend_from_slice(self.mini_stream.get(from..to)?);
910            sector = *self.mini_fat.get(index(sector)?)?;
911            steps = steps.checked_add(1)?;
912        }
913        out.truncate(usize::try_from(size).ok()?);
914        Some(out)
915    }
916
917    /// A stream directly under the root storage, by name (case-insensitive,
918    /// as the format compares names). Streams inside sub-storages, such as
919    /// an embedded document's own `WordDocument`, are not found.
920    fn stream(&self, name: &str) -> Option<Vec<u8>> {
921        let root = self.entries.first()?;
922        let mut stack = vec![root.child];
923        let mut visited = 0usize;
924        while let Some(id) = stack.pop() {
925            if id == NO_STREAM {
926                continue;
927            }
928            visited = visited.checked_add(1)?;
929            if visited > self.entries.len() {
930                return None;
931            }
932            let entry = self.entries.get(index(id)?)?;
933            if entry.kind == 2 && entry.name.eq_ignore_ascii_case(name) {
934                let limit = self.bytes.len().checked_div(self.sector_size).unwrap_or(0);
935                return if entry.size < self.mini_cutoff {
936                    self.mini_chain(entry.start, entry.size)
937                } else {
938                    self.chain(entry.start, Some(entry.size), limit)
939                };
940            }
941            stack.push(entry.left);
942            stack.push(entry.right);
943        }
944        None
945    }
946}
947
948fn sector_slice(bytes: &[u8], sector_size: usize, sector: u32) -> Option<&[u8]> {
949    let from = index(sector)?.checked_add(1)?.checked_mul(sector_size)?;
950    bytes.get(from..from.checked_add(sector_size)?)
951}
952
953impl DirEntry {
954    fn parse(raw: &[u8], v4: bool) -> Option<Self> {
955        let name_len = usize::from(u16_at(raw, 64)?);
956        let units: Vec<u16> = raw
957            .get(..name_len.saturating_sub(2).min(64))?
958            .as_chunks::<2>()
959            .0
960            .iter()
961            .map(|c| u16::from_le_bytes(*c))
962            .collect();
963        Some(Self {
964            name: String::from_utf16_lossy(&units),
965            kind: *raw.get(66)?,
966            left: u32_at(raw, 68)?,
967            right: u32_at(raw, 72)?,
968            child: u32_at(raw, 76)?,
969            start: u32_at(raw, 116)?,
970            // Version 4 sizes are 64-bit; version 3 leaves the high half
971            // undefined ([MS-CFB] 2.6.1).
972            size: if v4 {
973                u64::from(u32_at(raw, 120)?) | (u64::from(u32_at(raw, 124)?) << 32)
974            } else {
975                u64::from(u32_at(raw, 120)?)
976            },
977        })
978    }
979}
980
981// ---------------------------------------------------------------------------
982// File Information Block (MS-DOC 2.5.1)
983// ---------------------------------------------------------------------------
984
985struct Fib {
986    table_one: bool,
987    ccp_text: u32,
988    fc_stshf: u32,
989    lcb_stshf: u32,
990    fc_plcf_bte_papx: u32,
991    lcb_plcf_bte_papx: u32,
992    fc_plcf_bte_chpx: u32,
993    lcb_plcf_bte_chpx: u32,
994    fc_clx: u32,
995    lcb_clx: u32,
996    /// List definitions and overrides; `(0, 0)` when the FIB is too short.
997    plf_lst: (u32, u32),
998    plf_lfo: (u32, u32),
999    /// The section table: where each section ends.
1000    plcf_sed: (u32, u32),
1001}
1002
1003impl Fib {
1004    fn parse(word: &[u8]) -> Result<Self> {
1005        let bad = || LegacyDocError::new("the WordDocument stream's FIB is truncated");
1006        if u16_at(word, 0).ok_or_else(bad)? != WORD_IDENT {
1007            return Err(LegacyDocError::new("not a Word document (wIdent)"));
1008        }
1009        let n_fib = u16_at(word, 2).ok_or_else(bad)?;
1010        if n_fib < NFIB_WORD97 {
1011            return Err(LegacyDocError::new(
1012                "a Word 6 or Word 95 document; open it in Word and save it as .docx",
1013            ));
1014        }
1015        let flags = u16_at(word, 0x0A).ok_or_else(bad)?;
1016        if flags & 0x0100 != 0 || flags & 0x8000 != 0 {
1017            return Err(LegacyDocError::new(
1018                "an encrypted Word 97-2003 document; open it in Word and save it as .docx without a password",
1019            ));
1020        }
1021        let csw = usize::from(u16_at(word, 32).ok_or_else(bad)?);
1022        let cslw_at = csw
1023            .checked_mul(2)
1024            .and_then(|n| n.checked_add(34))
1025            .ok_or_else(bad)?;
1026        let cslw = usize::from(u16_at(word, cslw_at).ok_or_else(bad)?);
1027        let lw = cslw_at.checked_add(2).ok_or_else(bad)?;
1028        let ccp_text = u32_at(word, lw.checked_add(12).ok_or_else(bad)?).ok_or_else(bad)?;
1029        let blob = cslw
1030            .checked_mul(4)
1031            .and_then(|n| n.checked_add(lw))
1032            .and_then(|n| n.checked_add(2))
1033            .ok_or_else(bad)?;
1034        let pair = |i: usize| -> Result<(u32, u32)> {
1035            let at = i
1036                .checked_mul(8)
1037                .and_then(|n| n.checked_add(blob))
1038                .ok_or_else(bad)?;
1039            Ok((
1040                u32_at(word, at).ok_or_else(bad)?,
1041                u32_at(word, at.checked_add(4).ok_or_else(bad)?).ok_or_else(bad)?,
1042            ))
1043        };
1044        let (fc_stshf, lcb_stshf) = pair(1)?;
1045        let (fc_plcf_bte_chpx, lcb_plcf_bte_chpx) = pair(12)?;
1046        let (fc_plcf_bte_papx, lcb_plcf_bte_papx) = pair(13)?;
1047        let (fc_clx, lcb_clx) = pair(33)?;
1048        Ok(Self {
1049            table_one: flags & 0x0200 != 0,
1050            ccp_text,
1051            fc_stshf,
1052            lcb_stshf,
1053            fc_plcf_bte_papx,
1054            lcb_plcf_bte_papx,
1055            fc_plcf_bte_chpx,
1056            lcb_plcf_bte_chpx,
1057            fc_clx,
1058            lcb_clx,
1059            plf_lst: pair(73).unwrap_or((0, 0)),
1060            plcf_sed: pair(6)?,
1061            plf_lfo: pair(74).unwrap_or((0, 0)),
1062        })
1063    }
1064}
1065
1066// ---------------------------------------------------------------------------
1067// Piece table (MS-DOC 2.9.38 Clx, 2.9.177 Pcd)
1068// ---------------------------------------------------------------------------
1069
1070#[derive(Clone, Copy, Debug)]
1071#[doc(hidden)]
1072pub struct Piece {
1073    cp_start: u32,
1074    cp_end: u32,
1075    /// Byte offset in the WordDocument stream.
1076    fc: u32,
1077    compressed: bool,
1078    /// The bold and italic the piece's `Prm` sets over its CHPX.
1079    modifier: CharModifier,
1080}
1081
1082/// Bold and italic a piece's property modifier sets (`None`: left as the
1083/// CHPX has it).
1084#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1085struct CharModifier {
1086    bold: Option<bool>,
1087    italic: Option<bool>,
1088}
1089
1090impl CharModifier {
1091    /// Read a character sprm: sprmCFBold or sprmCFItalic with a toggle
1092    /// operand. A `0x81` (invert the style's) reads as on, as in the CHPX.
1093    ///
1094    /// # Errors
1095    ///
1096    /// A bold or italic sprm whose operand is missing (a truncated grpprl)
1097    /// or is none of the four ToggleOperand values ([MS-DOC] 2.9.327).
1098    fn apply(&mut self, sprm: u16, operand: &[u8]) -> Result<()> {
1099        let slot = match sprm {
1100            0x0835 => &mut self.bold,
1101            0x0836 => &mut self.italic,
1102            _ => return Ok(()),
1103        };
1104        *slot = Some(match operand {
1105            [0x01 | 0x81] => true,
1106            [0x00 | 0x80] => false,
1107            _ => {
1108                return Err(LegacyDocError::new(
1109                    "a text piece's property modifier has a bold or italic toggle that is missing or invalid",
1110                ));
1111            }
1112        });
1113        Ok(())
1114    }
1115
1116    /// `props` with this modifier applied ([MS-DOC] 2.4.6.2: the Pcd's
1117    /// `Prm` comes after the CHPX's grpprl).
1118    fn over(self, props: Props) -> Props {
1119        Props {
1120            bold: self.bold.unwrap_or(props.bold),
1121            italic: self.italic.unwrap_or(props.italic),
1122            ..props
1123        }
1124    }
1125}
1126
1127/// The modifier a Pcd's `Prm` names ([MS-DOC] 2.9.214-216): bit 0 set, a
1128/// Prm1 whose bits 1-15 index the Clx's Prcs; clear, a Prm0 whose bits
1129/// 1-7 name one sprm (isprm `0x55` sprmCFBold, `0x56` sprmCFItalic) and
1130/// bits 8-15 hold its operand.
1131///
1132/// # Errors
1133///
1134/// A Prm1 past the Clx's Prcs, or a bold or italic toggle that
1135/// [`CharModifier::apply`] refuses.
1136fn piece_modifier(prm: u16, prcs: &[&[u8]]) -> Result<CharModifier> {
1137    let mut modifier = CharModifier::default();
1138    if prm & 1 == 1 {
1139        let grpprl = prcs.get(usize::from(prm >> 1)).ok_or_else(|| {
1140            LegacyDocError::new("a text piece names a property modifier the Clx lacks")
1141        })?;
1142        let mut result = Ok(());
1143        for_each_sprm(grpprl, |sprm, operand| {
1144            if result.is_ok() {
1145                result = modifier.apply(sprm, operand);
1146            }
1147        });
1148        result?;
1149    } else {
1150        let sprm = match (prm >> 1) & 0x7F {
1151            0x55 => 0x0835,
1152            0x56 => 0x0836,
1153            _ => return Ok(modifier),
1154        };
1155        let [_, val] = prm.to_le_bytes();
1156        modifier.apply(sprm, &[val])?;
1157    }
1158    Ok(modifier)
1159}
1160
1161/// Most bytes a Prc's grpprl may hold ([MS-DOC] 2.9.210 PrcData).
1162const MAX_PRC_GRPPRL: usize = 0x3FA2;
1163
1164fn pieces(table: &[u8], fc_clx: u32, lcb_clx: u32) -> Result<Vec<Piece>> {
1165    let bad = || LegacyDocError::new("the piece table (Clx) is unreadable");
1166    let start = index(fc_clx).ok_or_else(bad)?;
1167    let end = start
1168        .checked_add(index(lcb_clx).ok_or_else(bad)?)
1169        .ok_or_else(bad)?;
1170    let clx = table.get(start..end).ok_or_else(bad)?;
1171    let mut at = 0usize;
1172    // The Prcs (property modifiers a Pcd's Prm1 names by index) before
1173    // the Pcdt.
1174    let mut prcs: Vec<&[u8]> = Vec::new();
1175    while clx.get(at) == Some(&0x01) {
1176        let size = usize::from(u16_at(clx, at.checked_add(1).ok_or_else(bad)?).ok_or_else(bad)?);
1177        if size > MAX_PRC_GRPPRL {
1178            return Err(bad());
1179        }
1180        let from = at.checked_add(3).ok_or_else(bad)?;
1181        let next = from.checked_add(size).ok_or_else(bad)?;
1182        prcs.push(clx.get(from..next).ok_or_else(bad)?);
1183        at = next;
1184    }
1185    if clx.get(at) != Some(&0x02) {
1186        return Err(bad());
1187    }
1188    let lcb =
1189        index(u32_at(clx, at.checked_add(1).ok_or_else(bad)?).ok_or_else(bad)?).ok_or_else(bad)?;
1190    let plc_start = at.checked_add(5).ok_or_else(bad)?;
1191    let plc = clx
1192        .get(plc_start..plc_start.checked_add(lcb).ok_or_else(bad)?)
1193        .ok_or_else(bad)?;
1194    // (n + 1) CPs of 4 bytes, then n PCDs of 8 bytes.
1195    let count = lcb.checked_sub(4).ok_or_else(bad)? / 12;
1196    let pcd_base = count
1197        .checked_add(1)
1198        .and_then(|n| n.checked_mul(4))
1199        .ok_or_else(bad)?;
1200    let mut out = Vec::with_capacity(count);
1201    for i in 0..count {
1202        let cp_at = i.checked_mul(4).ok_or_else(bad)?;
1203        let cp_start = u32_at(plc, cp_at).ok_or_else(bad)?;
1204        let cp_end = u32_at(plc, cp_at.checked_add(4).ok_or_else(bad)?).ok_or_else(bad)?;
1205        let pcd = i
1206            .checked_mul(8)
1207            .and_then(|n| n.checked_add(pcd_base))
1208            .ok_or_else(bad)?;
1209        let raw = u32_at(plc, pcd.checked_add(2).ok_or_else(bad)?).ok_or_else(bad)?;
1210        let compressed = raw & 0x4000_0000 != 0;
1211        let fc = raw & 0x3FFF_FFFF;
1212        let prm = u16_at(plc, pcd.checked_add(6).ok_or_else(bad)?).ok_or_else(bad)?;
1213        let modifier = piece_modifier(prm, &prcs)?;
1214        out.push(Piece {
1215            cp_start,
1216            cp_end,
1217            fc: if compressed { fc / 2 } else { fc },
1218            compressed,
1219            modifier,
1220        });
1221    }
1222    Ok(out)
1223}
1224
1225/// Windows-1252 bytes 0x80-0x9F as the spec's compressed-text table maps
1226/// them (MS-DOC 2.4.1); every other byte is its own code point.
1227fn cp1252(byte: u8) -> char {
1228    const HIGH: [u16; 32] = [
1229        0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160,
1230        0x2039, 0x0152, 0x008D, 0x017D, 0x008F, 0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022,
1231        0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178,
1232    ];
1233    match byte {
1234        0x80..=0x9F => HIGH
1235            .get(usize::from(byte.wrapping_sub(0x80)))
1236            .and_then(|&unit| char::from_u32(u32::from(unit)))
1237            .unwrap_or('\u{FFFD}'),
1238        _ => char::from(byte),
1239    }
1240}
1241
1242/// A character of the main story and the stream offset it was read from.
1243#[derive(Clone, Copy, Debug)]
1244struct StoryChar {
1245    ch: char,
1246    cp: u32,
1247    fc: u32,
1248    /// The piece's property modifier.
1249    modifier: CharModifier,
1250}
1251
1252/// The main story's characters, CP 0 to `ccp_text`.
1253///
1254/// # Errors
1255///
1256/// A piece that points past the `WordDocument` stream: a truncated or
1257/// corrupt file, refused rather than converted short.
1258fn main_text(word: &[u8], pieces: &[Piece], ccp_text: u32) -> Result<Vec<StoryChar>> {
1259    // The same ceiling `read` uses for a story (`InputLimits::max_story_units`).
1260    // Aliased pieces can describe billions of logical characters from one
1261    // physical range; refuse that before allocating one record per character.
1262    if u64::from(ccp_text) > crate::admission::InputLimits::default().max_story_units {
1263        return Err(LegacyDocError::new(
1264            "the main story exceeds the logical character budget",
1265        ));
1266    }
1267    let past = || LegacyDocError::new("a text piece points past the WordDocument stream");
1268    // The pieces run from CP 0 through the main story without a gap, or
1269    // the document would come out quietly shorter than it is.
1270    // The CPs only ever increase ([MS-DOC] 2.8.35): a piece that runs
1271    // backwards is corruption, wherever it sits.
1272    if pieces.iter().any(|piece| piece.cp_end < piece.cp_start) {
1273        return Err(LegacyDocError::new("the piece table's CPs are decreasing"));
1274    }
1275    let mut covered = 0u32;
1276    for piece in pieces {
1277        if covered >= ccp_text {
1278            break;
1279        }
1280        // An empty piece (fast-saved files carry them) covers nothing.
1281        if piece.cp_end == piece.cp_start {
1282            continue;
1283        }
1284        if piece.cp_start != covered {
1285            break;
1286        }
1287        covered = piece.cp_end;
1288    }
1289    if covered < ccp_text {
1290        return Err(LegacyDocError::new(
1291            "the piece table does not cover the main story",
1292        ));
1293    }
1294    let mut out = Vec::new();
1295    // A high surrogate waiting for its low half, which may open the next
1296    // Unicode piece (a supplementary character split between two pieces).
1297    // Without one it is a replacement mark at its own position.
1298    let mut pending_high: Option<(u16, StoryChar)> = None;
1299    for piece in pieces {
1300        if piece.cp_start >= ccp_text {
1301            break;
1302        }
1303        let end = piece.cp_end.min(ccp_text);
1304        let width: u32 = if piece.compressed { 1 } else { 2 };
1305        for cp in piece.cp_start..end {
1306            let fc = cp
1307                .checked_sub(piece.cp_start)
1308                .and_then(|n| n.checked_mul(width))
1309                .and_then(|n| n.checked_add(piece.fc))
1310                .ok_or_else(past)?;
1311            let offset = index(fc).ok_or_else(past)?;
1312            let here = StoryChar {
1313                ch: '\u{FFFD}',
1314                cp,
1315                fc,
1316                modifier: piece.modifier,
1317            };
1318            let ch = if piece.compressed {
1319                out.extend(pending_high.take().map(|(_, lone)| lone));
1320                cp1252(*word.get(offset).ok_or_else(past)?)
1321            } else {
1322                let unit = u16_at(word, offset).ok_or_else(past)?;
1323                match (pending_high.take(), unit) {
1324                    (Some(high), 0xDC00..=0xDFFF) => char::decode_utf16([high.0, unit])
1325                        .next()
1326                        .and_then(std::result::Result::ok)
1327                        .unwrap_or('\u{FFFD}'),
1328                    (lone, 0xD800..=0xDBFF) => {
1329                        out.extend(lone.map(|(_, lone)| lone));
1330                        pending_high = Some((unit, here));
1331                        continue;
1332                    }
1333                    (lone, unit) => {
1334                        out.extend(lone.map(|(_, lone)| lone));
1335                        char::from_u32(u32::from(unit)).unwrap_or('\u{FFFD}')
1336                    }
1337                }
1338            };
1339            out.push(StoryChar { ch, ..here });
1340        }
1341    }
1342    out.extend(pending_high.map(|(_, lone)| lone));
1343    Ok(out)
1344}
1345
1346// ---------------------------------------------------------------------------
1347// Style sheet (MS-DOC 2.9.271 STSH): which istd is a heading
1348// ---------------------------------------------------------------------------
1349
1350/// Heading level by `istd`: `sti` 1-9 are Heading 1-9 and 62 is Title.
1351fn heading_styles(table: &[u8], fc: u32, lcb: u32) -> Result<Vec<Option<u8>>> {
1352    let Some(stsh) = fib_table(table, (fc, lcb), "style sheet (STSH)")? else {
1353        return Ok(Vec::new());
1354    };
1355    let Some(cb_stshi) = u16_at(stsh, 0).map(usize::from) else {
1356        return Ok(Vec::new());
1357    };
1358    let Some(cstd) = u16_at(stsh, 2).map(usize::from) else {
1359        return Ok(Vec::new());
1360    };
1361    let mut out = Vec::with_capacity(cstd);
1362    let mut at = cb_stshi.saturating_add(2);
1363    for _ in 0..cstd {
1364        let Some(cb_std) = u16_at(stsh, at).map(usize::from) else {
1365            break;
1366        };
1367        let level = if cb_std == 0 {
1368            None
1369        } else {
1370            match u16_at(stsh, at.saturating_add(2)).map(|word| word & 0x0FFF) {
1371                Some(sti @ 1..=9) => u8::try_from(sti).ok(),
1372                Some(62) => Some(0),
1373                _ => None,
1374            }
1375        };
1376        out.push(level);
1377        at = at.saturating_add(2).saturating_add(cb_std);
1378    }
1379    Ok(out)
1380}
1381
1382// ---------------------------------------------------------------------------
1383// Paragraph and character properties (MS-DOC 2.9.177 PapxFkp, 2.9.33 ChpxFkp)
1384// ---------------------------------------------------------------------------
1385
1386/// The properties read from a PAPX or a CHPX; each kind fills its own.
1387#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1388struct Props {
1389    istd: u16,
1390    in_table: bool,
1391    row_end: bool,
1392    /// List override, 1-based; 0 is none.
1393    ilfo: u16,
1394    /// The row a table-row mark ends repeats as a header.
1395    table_header: bool,
1396    ilvl: u8,
1397    bold: bool,
1398    italic: bool,
1399}
1400
1401#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1402enum Fkp {
1403    Paragraph,
1404    Character,
1405}
1406
1407/// Formatted disk pages of one kind, read once.
1408struct FkpIndex {
1409    /// `(fc_start, fc_end, props)` runs, in stream order.
1410    runs: Vec<(u32, u32, Props)>,
1411}
1412
1413impl FkpIndex {
1414    fn new(word: &[u8], table: &[u8], (fc, lcb): (u32, u32), kind: Fkp) -> Result<Self> {
1415        let mut runs = Vec::new();
1416        let what = match kind {
1417            Fkp::Paragraph => "paragraph property bin table (PlcBtePapx)",
1418            Fkp::Character => "character property bin table (PlcBteChpx)",
1419        };
1420        let Some(plc) = fib_table(table, (fc, lcb), what)? else {
1421            return Ok(Self { runs });
1422        };
1423        let count = plc.len().saturating_sub(4) / 8;
1424        let pn_base = count.saturating_add(1).saturating_mul(4);
1425        for i in 0..count {
1426            let Some(pn) = u32_at(plc, pn_base.saturating_add(i.saturating_mul(4))) else {
1427                break;
1428            };
1429            let page = index(pn & 0x003F_FFFF)
1430                .and_then(|pn| pn.checked_mul(512))
1431                .and_then(|from| word.get(from..from.checked_add(512)?))
1432                .ok_or_else(|| {
1433                    LegacyDocError::new(
1434                        "a formatted disk page (FKP) points past the WordDocument stream",
1435                    )
1436                })?;
1437            read_fkp(page, kind, &mut runs);
1438        }
1439        runs.sort_by_key(|run| run.0);
1440        Ok(Self { runs })
1441    }
1442
1443    fn at(&self, fc: u32) -> Props {
1444        let after = self.runs.partition_point(|run| run.0 <= fc);
1445        after
1446            .checked_sub(1)
1447            .and_then(|i| self.runs.get(i))
1448            .filter(|run| fc < run.1)
1449            .map(|run| run.2)
1450            .unwrap_or_default()
1451    }
1452}
1453
1454fn read_fkp(page: &[u8], kind: Fkp, runs: &mut Vec<(u32, u32, Props)>) {
1455    let Some(&crun) = page.get(511) else { return };
1456    let crun = usize::from(crun);
1457    let bx_base = crun.saturating_add(1).saturating_mul(4);
1458    // A PAPX entry is a word offset and a 12-byte PHE; a CHPX entry is the
1459    // word offset alone.
1460    let entry = match kind {
1461        Fkp::Paragraph => 13,
1462        Fkp::Character => 1,
1463    };
1464    for i in 0..crun {
1465        let (Some(start), Some(end)) = (
1466            u32_at(page, i.saturating_mul(4)),
1467            u32_at(page, i.saturating_add(1).saturating_mul(4)),
1468        ) else {
1469            return;
1470        };
1471        let props = page
1472            .get(bx_base.saturating_add(i.saturating_mul(entry)))
1473            .and_then(|&offset| {
1474                let at = usize::from(offset).saturating_mul(2);
1475                match kind {
1476                    Fkp::Paragraph => papx_props(page, at),
1477                    Fkp::Character => chpx_props(page, at),
1478                }
1479            })
1480            .unwrap_or_default();
1481        runs.push((start, end, props));
1482    }
1483}
1484
1485/// Call `each` with every sprm in `grpprl` and its operand bytes.
1486fn for_each_sprm(grpprl: &[u8], mut each: impl FnMut(u16, &[u8])) {
1487    let mut at = 0usize;
1488    while let Some(sprm) = u16_at(grpprl, at) {
1489        let Some(operand) = at.checked_add(2) else {
1490            return;
1491        };
1492        let size = match sprm >> 13 {
1493            0 | 1 => Some(1),
1494            2 | 4 | 5 => Some(2),
1495            3 => Some(4),
1496            7 => Some(3),
1497            _ if sprm == 0xD608 || sprm == 0xD606 => {
1498                u16_at(grpprl, operand).and_then(|n| usize::from(n).checked_add(1))
1499            }
1500            _ => match grpprl.get(operand) {
1501                // sprmPChgTabs's long form (a count of 255) sizes itself
1502                // ([MS-DOC] 2.9.188). Any other 255 is a count.
1503                Some(255) if sprm == 0xC615 => chg_tabs_long_size(grpprl, operand),
1504                None => None,
1505                Some(&n) => usize::from(n).checked_add(1),
1506            },
1507        };
1508        let Some(next) = size.and_then(|size| operand.checked_add(size)) else {
1509            return;
1510        };
1511        each(sprm, grpprl.get(operand..next).unwrap_or(&[]));
1512        at = next;
1513    }
1514}
1515
1516/// The bytes of a long-form sprmPChgTabs operand at `operand`, its 255
1517/// included: `cb = cTabsDel * 4 + cTabsAdd * 3 + 2` bytes follow it
1518/// ([MS-DOC] 2.9.188 PChgTabsOperand). `None` when the operand is cut short.
1519fn chg_tabs_long_size(grpprl: &[u8], operand: usize) -> Option<usize> {
1520    let deleted = usize::from(*grpprl.get(operand.checked_add(1)?)?);
1521    let added_at = operand
1522        .checked_add(2)?
1523        .checked_add(deleted.checked_mul(4)?)?;
1524    let added = usize::from(*grpprl.get(added_at)?);
1525    let size = deleted
1526        .checked_mul(4)?
1527        .checked_add(added.checked_mul(3)?)?
1528        .checked_add(3)?;
1529    (operand.checked_add(size)? <= grpprl.len()).then_some(size)
1530}
1531
1532fn papx_props(page: &[u8], at: usize) -> Option<Props> {
1533    if at == 0 {
1534        return None;
1535    }
1536    let cb = usize::from(*page.get(at)?);
1537    let (from, len) = if cb == 0 {
1538        let cb2 = usize::from(*page.get(at.checked_add(1)?)?);
1539        (at.checked_add(2)?, cb2.checked_mul(2)?)
1540    } else {
1541        (at.checked_add(1)?, cb.checked_mul(2)?.checked_sub(1)?)
1542    };
1543    let grpprl = page.get(from..from.checked_add(len)?)?;
1544    let mut props = Props {
1545        istd: u16_at(grpprl, 0)?,
1546        ..Props::default()
1547    };
1548    for_each_sprm(grpprl.get(2..).unwrap_or(&[]), |sprm, operand| {
1549        let value = operand.first().copied().unwrap_or(0);
1550        match sprm {
1551            // sprmPFInTable, sprmPFInnerTableCell
1552            0x2416 | 0x244B => props.in_table |= value != 0,
1553            // sprmPFTtp, sprmPFInnerTtp
1554            0x2417 | 0x244C => props.row_end |= value != 0,
1555            // sprmPItap: a table depth above zero
1556            0x6649 => props.in_table |= u32_at(operand, 0).is_some_and(|depth| depth > 0),
1557            // sprmPIlfo, sprmPIlvl
1558            0x460B => props.ilfo = u16_at(operand, 0).unwrap_or(0),
1559            // sprmTTableHeader, in the row-end paragraph's PAPX
1560            0x3404 => props.table_header = value != 0,
1561            0x260A => props.ilvl = value,
1562            _ => {}
1563        }
1564    });
1565    Some(props)
1566}
1567
1568fn chpx_props(page: &[u8], at: usize) -> Option<Props> {
1569    if at == 0 {
1570        return None;
1571    }
1572    let cb = usize::from(*page.get(at)?);
1573    let from = at.checked_add(1)?;
1574    let grpprl = page.get(from..from.checked_add(cb)?)?;
1575    let mut props = Props::default();
1576    // 1 sets the toggle and 0x81 inverts the style's (a plain style has it
1577    // off); 0 clears it and 0x80 keeps the style's.
1578    let on = |operand: &[u8]| matches!(operand.first(), Some(0x01 | 0x81));
1579    for_each_sprm(grpprl, |sprm, operand| match sprm {
1580        // sprmCFBold, sprmCFItalic
1581        0x0835 => props.bold = on(operand),
1582        0x0836 => props.italic = on(operand),
1583        _ => {}
1584    });
1585    Some(props)
1586}
1587
1588// ---------------------------------------------------------------------------
1589// Lists (MS-DOC 2.9.150 PlfLst, 2.9.131 PlfLfo, 2.9.149 LVLF)
1590// ---------------------------------------------------------------------------
1591
1592/// Number format of each list level, by list id, and the list id of each
1593/// list override.
1594#[derive(Default)]
1595struct Lists {
1596    /// `lsid` of each LFO; a paragraph's `ilfo` is 1-based into it.
1597    overrides: Vec<i32>,
1598    /// `nfc` of each level, by `lsid`.
1599    formats: Vec<(i32, Vec<u8>)>,
1600}
1601
1602/// `nfc` of a bullet, and of a level that shows no number.
1603const NFC_BULLET: u8 = 23;
1604const NFC_NONE: u8 = 0xFF;
1605
1606impl Lists {
1607    fn new(
1608        table: &[u8],
1609        (fc_lst, lcb_lst): (u32, u32),
1610        (fc_lfo, lcb_lfo): (u32, u32),
1611    ) -> Result<Self> {
1612        let mut lists = Self::default();
1613        let lst_table = fib_table(table, (fc_lst, lcb_lst), "list table (PlfLst)")?;
1614        let lfo_table = fib_table(table, (fc_lfo, lcb_lfo), "list override table (PlfLfo)")?;
1615        let (Some(lst_table), Some(lfo_table), Some(lst)) = (lst_table, lfo_table, index(fc_lst))
1616        else {
1617            return Ok(lists);
1618        };
1619        let short = |what: &str| LegacyDocError::new(format!("the {what} is cut short"));
1620        // cLst and the LSTFs lie within the PlfLst's lcb.
1621        let count = usize::from(u16_at(lst_table, 0).ok_or_else(|| short("list table (PlfLst)"))?);
1622        // The LVLs follow the PlfLst, outside its lcb ([MS-DOC] 2.5.6),
1623        // nine per list (one for a simple list), in list order.
1624        let mut lvl = count
1625            .saturating_mul(28)
1626            .saturating_add(lst)
1627            .saturating_add(2);
1628        let lvl_short = || LegacyDocError::new("a list level (LVL) runs past the table stream");
1629        for i in 0..count {
1630            let lstf = i.saturating_mul(28).saturating_add(2);
1631            let (Some(lsid), Some(&flags)) = (
1632                u32_at(lst_table, lstf),
1633                lst_table
1634                    .get(lstf.saturating_add(27))
1635                    .and(lst_table.get(lstf.saturating_add(26))),
1636            ) else {
1637                return Err(short("list table (PlfLst)"));
1638            };
1639            let levels = if flags & 0x01 != 0 { 1 } else { 9 };
1640            let mut formats = Vec::with_capacity(levels);
1641            for _ in 0..levels {
1642                let (Some(&nfc), Some(&chpx), Some(&papx)) = (
1643                    table.get(lvl.saturating_add(4)),
1644                    table.get(lvl.saturating_add(24)),
1645                    table.get(lvl.saturating_add(25)),
1646                ) else {
1647                    return Err(lvl_short());
1648                };
1649                formats.push(nfc);
1650                let xst = lvl
1651                    .saturating_add(28)
1652                    .saturating_add(usize::from(papx))
1653                    .saturating_add(usize::from(chpx));
1654                let cch = u16_at(table, xst).ok_or_else(lvl_short)?;
1655                lvl = xst
1656                    .saturating_add(2)
1657                    .saturating_add(usize::from(cch).saturating_mul(2));
1658                if lvl > table.len() {
1659                    return Err(lvl_short());
1660                }
1661            }
1662            lists.formats.push((lsid.cast_signed(), formats));
1663        }
1664        // lfoMac and the LFOs lie within the PlfLfo's lcb.
1665        let overrides = u32_at(lfo_table, 0)
1666            .and_then(index)
1667            .ok_or_else(|| short("list override table (PlfLfo)"))?;
1668        for i in 0..overrides {
1669            let lsid = u32_at(lfo_table, i.saturating_mul(16).saturating_add(4))
1670                .filter(|_| {
1671                    lfo_table.len() >= i.saturating_add(1).saturating_mul(16).saturating_add(4)
1672                })
1673                .ok_or_else(|| short("list override table (PlfLfo)"))?;
1674            lists.overrides.push(lsid.cast_signed());
1675        }
1676        Ok(lists)
1677    }
1678
1679    fn item(&self, ilfo: u16, ilvl: u8) -> Option<ListItem> {
1680        let lsid = *self.overrides.get(usize::from(ilfo).checked_sub(1)?)?;
1681        let formats = &self.formats.iter().find(|(id, _)| *id == lsid)?.1;
1682        let nfc = *formats.get(usize::from(ilvl)).or_else(|| formats.first())?;
1683        (nfc != NFC_NONE).then_some(ListItem {
1684            ordered: nfc != NFC_BULLET,
1685            level: ilvl.min(8),
1686        })
1687    }
1688}
1689
1690// ---------------------------------------------------------------------------
1691// Blocks
1692// ---------------------------------------------------------------------------
1693
1694/// What the main story's characters are read against.
1695struct Story<'a> {
1696    papx: &'a FkpIndex,
1697    chpx: &'a FkpIndex,
1698    styles: &'a [Option<u8>],
1699    lists: &'a Lists,
1700    /// CPs of the section marks (`\x0C` ending a section, which ends its
1701    /// paragraph too); any other `\x0C` is a page break inside a paragraph.
1702    section_marks: Vec<u32>,
1703}
1704
1705impl Story<'_> {
1706    /// Split the story into paragraphs at each paragraph mark (`\r`), cell
1707    /// or row mark (`\x07`) and section or page break (`\x0C`), and group
1708    /// table paragraphs into rows and cells.
1709    fn blocks(&self, chars: &[StoryChar]) -> Vec<Block> {
1710        let mut out = Vec::new();
1711        let mut spans: Vec<Span> = Vec::new();
1712        // Field nesting: true while inside a field's code (before its
1713        // separator). `code_frames` is how many of those are still code,
1714        // so the check below does not walk the stack per character.
1715        let mut fields: Vec<bool> = Vec::new();
1716        let mut code_frames: u32 = 0;
1717        // Each finished row and whether it is marked as a header.
1718        let mut rows: Vec<(Vec<String>, bool)> = Vec::new();
1719        let mut row: Vec<String> = Vec::new();
1720        let mut cell: Vec<String> = Vec::new();
1721
1722        for story in chars {
1723            // Inside any field's code, even a nested field's result is code.
1724            let in_code = code_frames != 0;
1725            let text = match story.ch {
1726                '\u{13}' => {
1727                    fields.push(true);
1728                    code_frames = code_frames.saturating_add(1);
1729                    continue;
1730                }
1731                '\u{14}' => {
1732                    if let Some(top) = fields.last_mut()
1733                        && *top
1734                    {
1735                        *top = false;
1736                        code_frames = code_frames.saturating_sub(1);
1737                    }
1738                    continue;
1739                }
1740                '\u{15}' => {
1741                    if fields.pop() == Some(true) {
1742                        code_frames = code_frames.saturating_sub(1);
1743                    }
1744                    continue;
1745                }
1746                _ if in_code => continue,
1747                '\u{0C}' if self.section_marks.binary_search(&story.cp).is_err() => {
1748                    // A page break: Markdown has no pages, so a line break.
1749                    '\n'
1750                }
1751                '\r' | '\u{07}' | '\u{0C}' => {
1752                    let props = self.papx.at(story.fc);
1753                    let taken = std::mem::take(&mut spans);
1754                    if props.in_table || story.ch == '\u{07}' {
1755                        let text: String = taken.iter().map(|span| span.text.as_str()).collect();
1756                        if props.row_end {
1757                            if !cell.is_empty() {
1758                                row.push(cell.join(" "));
1759                                cell.clear();
1760                            }
1761                            rows.push((std::mem::take(&mut row), props.table_header));
1762                        } else if story.ch == '\u{07}' {
1763                            cell.push(text.replace('\n', " "));
1764                            row.push(cell.join(" ").trim().to_string());
1765                            cell.clear();
1766                        } else {
1767                            cell.push(text.replace('\n', " "));
1768                        }
1769                        continue;
1770                    }
1771                    flush_table(&mut out, &mut rows, &mut row);
1772                    self.push_paragraph(&mut out, props, taken);
1773                    continue;
1774                }
1775                '\u{0B}' => '\n',
1776                '\u{1E}' => '\u{2011}',
1777                // A tab would open a code block at a line's start.
1778                '\t' => ' ',
1779                // Optional hyphen, picture and object anchors, note and
1780                // annotation references: nothing in the text.
1781                '\u{1F}' | '\u{01}' | '\u{02}' | '\u{05}' | '\u{08}' => continue,
1782                ch if ch.is_control() => continue,
1783                ch => ch,
1784            };
1785            let format = story.modifier.over(self.chpx.at(story.fc));
1786            match spans.last_mut() {
1787                Some(last) if last.bold == format.bold && last.italic == format.italic => {
1788                    last.text.push(text);
1789                }
1790                _ => spans.push(Span {
1791                    text: text.to_string(),
1792                    bold: format.bold,
1793                    italic: format.italic,
1794                }),
1795            }
1796        }
1797        if !spans.is_empty() {
1798            self.push_paragraph(&mut out, Props::default(), spans);
1799        }
1800        flush_table(&mut out, &mut rows, &mut row);
1801        out
1802    }
1803
1804    fn push_paragraph(&self, out: &mut Vec<Block>, props: Props, spans: Vec<Span>) {
1805        let heading = self.styles.get(usize::from(props.istd)).copied().flatten();
1806        let list = heading
1807            .is_none()
1808            .then(|| self.lists.item(props.ilfo, props.ilvl))
1809            .flatten();
1810        out.push(Block::Paragraph(Paragraph {
1811            heading,
1812            list,
1813            spans,
1814        }));
1815    }
1816}
1817
1818/// The CP of each section's last character, the mark that ends it, from
1819/// `PlcfSed` ([MS-DOC] 2.8.26): `n + 1` CPs, then `n` 12-byte SEDs.
1820fn section_marks(table: &[u8], (fc, lcb): (u32, u32)) -> Result<Vec<u32>> {
1821    let Some(plc) = fib_table(table, (fc, lcb), "section table (PlcfSed)")? else {
1822        return Ok(Vec::new());
1823    };
1824    let count = plc.len().saturating_sub(4) / 16;
1825    let mut marks: Vec<u32> = (1..=count)
1826        .filter_map(|i| u32_at(plc, i.saturating_mul(4))?.checked_sub(1))
1827        .collect();
1828    marks.sort_unstable();
1829    Ok(marks)
1830}
1831
1832/// End a table: a row whose end mark is missing still belongs to it.
1833fn flush_table(out: &mut Vec<Block>, rows: &mut Vec<(Vec<String>, bool)>, row: &mut Vec<String>) {
1834    if !row.is_empty() {
1835        rows.push((std::mem::take(row), false));
1836    }
1837    if !rows.is_empty() {
1838        let rows = std::mem::take(rows);
1839        // Only leading rows repeat: a header mark after a data row is
1840        // ignored ([MS-DOC] 2.6.3 sprmTTableHeader).
1841        let header_rows = rows.iter().take_while(|(_, header)| *header).count();
1842        out.push(Block::Table(Table {
1843            rows: rows.into_iter().map(|(cells, _)| cells).collect(),
1844            header_rows,
1845        }));
1846    }
1847}
1848
1849#[cfg(test)]
1850#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1851mod tests {
1852    use super::*;
1853
1854    #[test]
1855    fn is_compound_file_returns_true_for_ole_magic() {
1856        // The OLE signature, spelled out apart from `OLE_MAGIC`.
1857        let mut bytes = vec![0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
1858        assert_eq!(bytes, OLE_MAGIC);
1859        bytes.push(0x42);
1860        assert!(is_compound_file(&bytes));
1861    }
1862
1863    #[test]
1864    fn is_compound_file_returns_false_for_invalid_magic() {
1865        let bytes = b"PK\x03\x04\x14\x00\x06\x00";
1866        assert!(!is_compound_file(bytes));
1867    }
1868
1869    #[test]
1870    fn is_compound_file_handles_short_input() {
1871        let bytes = b"\xD0\xCF\x11";
1872        assert!(!is_compound_file(bytes));
1873    }
1874
1875    #[test]
1876    fn escapes_markdown_significant_text() {
1877        assert_eq!(escape_line("1. not a list"), "1\\. not a list");
1878        assert_eq!(escape_line("- not a bullet"), "\\- not a bullet");
1879        assert_eq!(
1880            escape_line("a_b * c [x] #2 $5"),
1881            "a\\_b \\* c \\[x\\] \\#2 \\$5"
1882        );
1883        assert_eq!(escape_line("  well-known  "), "well-known");
1884    }
1885
1886    #[test]
1887    fn escapes_list_delimiters_only_after_sole_digit_runs() {
1888        // `1.` or `1)` opens a list only when nothing but digits precedes
1889        // it; a delimiter after that first one is literal text.
1890        assert_eq!(escape_line("12) not a list"), "12\\) not a list");
1891        assert_eq!(escape_line("1.2."), "1\\.2.");
1892        assert_eq!(escape_line("3.14)"), "3\\.14)");
1893        assert_eq!(escape_line("."), ".");
1894        assert_eq!(escape_line(")."), ").");
1895        // Only ASCII digits count: `٣` does not open a list.
1896        assert_eq!(escape_line("٣."), "٣.");
1897    }
1898
1899    #[test]
1900    fn list_prefix_scan_stays_linear() {
1901        // 8_000 digits, then 4_000 `1.` pairs. Re-reading the digit prefix
1902        // at every delimiter examines tens of millions of characters; one
1903        // pass examines each character a constant number of times.
1904        let digits = 8_000;
1905        let pairs = 4_000;
1906        let mut text = "7".repeat(digits);
1907        text.push('.');
1908        text.push_str(&"1.".repeat(pairs - 1));
1909        let chars = text.chars().count();
1910        let delimiters = text.chars().filter(|&c| matches!(c, '.' | ')')).count();
1911        assert_eq!(delimiters, pairs);
1912        LIST_PREFIX_STEPS.with(|steps| steps.set(0));
1913        let escaped = escape_line(&text);
1914        let steps = LIST_PREFIX_STEPS.with(std::cell::Cell::get);
1915        const C: usize = 4;
1916        let bound = C * chars;
1917        assert!(
1918            steps <= bound,
1919            "escaping {delimiters} delimiters examined {steps} characters; \
1920             a single pass examines at most {bound}"
1921        );
1922        // Only the first delimiter follows a pure digit run.
1923        let expected = format!("{}\\.{}", "7".repeat(digits), "1.".repeat(pairs - 1));
1924        assert_eq!(escaped, expected);
1925    }
1926
1927    #[test]
1928    fn compressed_text_maps_windows_1252() {
1929        assert_eq!(cp1252(0x93), '\u{201C}');
1930        assert_eq!(cp1252(0x80), '\u{20AC}');
1931        assert_eq!(cp1252(b'A'), 'A');
1932        assert_eq!(cp1252(0xE9), 'é');
1933    }
1934
1935    #[test]
1936    fn read_rejects_missing_word_document() {
1937        let mut bytes = include_bytes!("../../../tests/fixtures/legacy/services.doc").to_vec();
1938        // Modify the "WordDocument" directory entry to "NordDocument"
1939        let word_doc_utf16: Vec<u8> = "WordDocument"
1940            .encode_utf16()
1941            .flat_map(|c| c.to_le_bytes())
1942            .collect();
1943        for i in 0..(bytes.len() - word_doc_utf16.len()) {
1944            if &bytes[i..i + word_doc_utf16.len()] == word_doc_utf16.as_slice() {
1945                bytes[i] = b'N';
1946            }
1947        }
1948        let error = read(&bytes).unwrap_err();
1949        assert_eq!(
1950            error.to_string(),
1951            "LEGACY_DOC: no WordDocument stream: an encrypted document or not a Word file; open it in Word and save it as .docx without a password"
1952        );
1953    }
1954
1955    #[test]
1956    fn refuses_what_is_not_a_compound_file() {
1957        let error = read(b"PK\x03\x04 not ole").unwrap_err();
1958        assert!(
1959            error.to_string().starts_with("LEGACY_DOC: not an OLE"),
1960            "{error}"
1961        );
1962        assert!(read(OLE_MAGIC).is_err());
1963    }
1964
1965    fn plain(text: &str) -> Paragraph {
1966        Paragraph {
1967            spans: vec![Span {
1968                text: text.into(),
1969                ..Span::default()
1970            }],
1971            ..Paragraph::default()
1972        }
1973    }
1974
1975    #[test]
1976    fn tables_become_github_tables() {
1977        let document = LegacyDocument {
1978            blocks: vec![
1979                Block::Paragraph(Paragraph {
1980                    heading: Some(1),
1981                    ..plain("Fees")
1982                }),
1983                Block::Table(Table {
1984                    rows: vec![
1985                        vec!["Item".into(), "Price".into()],
1986                        vec!["Setup | once".into()],
1987                    ],
1988                    header_rows: 0,
1989                }),
1990            ],
1991        };
1992        assert_eq!(
1993            to_markdown(&document),
1994            "# Fees\n\n| Item | Price |\n|---|---|\n| Setup \\| once |  |\n\n"
1995        );
1996    }
1997
1998    #[test]
1999    fn line_breaks_become_hard_breaks() {
2000        let document = LegacyDocument {
2001            blocks: vec![Block::Paragraph(plain("one\ntwo"))],
2002        };
2003        assert_eq!(to_markdown(&document), "one\\\ntwo\n\n");
2004    }
2005
2006    #[test]
2007    fn emphasis_markers_hug_the_text_and_lists_get_markers() {
2008        let spans = vec![
2009            Span {
2010                text: "Made by ".into(),
2011                ..Span::default()
2012            },
2013            Span {
2014                text: "Acme Corp ".into(),
2015                bold: true,
2016                italic: false,
2017            },
2018            Span {
2019                text: "and".into(),
2020                ..Span::default()
2021            },
2022            Span {
2023                text: " Beta*".into(),
2024                bold: true,
2025                italic: true,
2026            },
2027        ];
2028        assert_eq!(
2029            render_spans(&spans),
2030            "Made by **Acme Corp** and ***Beta\\****"
2031        );
2032        let document = LegacyDocument {
2033            blocks: vec![
2034                Block::Paragraph(Paragraph {
2035                    list: Some(ListItem {
2036                        ordered: false,
2037                        level: 0,
2038                    }),
2039                    ..plain("First")
2040                }),
2041                Block::Paragraph(Paragraph {
2042                    list: Some(ListItem {
2043                        ordered: true,
2044                        level: 1,
2045                    }),
2046                    ..plain("Nested")
2047                }),
2048            ],
2049        };
2050        assert_eq!(to_markdown(&document), "- First\n\n    1. Nested\n\n");
2051    }
2052
2053    #[test]
2054    fn a_piece_past_the_stream_is_refused_not_truncated() {
2055        let word = b"Hello".to_vec();
2056        let piece = Piece {
2057            cp_start: 0,
2058            cp_end: 10,
2059            fc: 0,
2060            compressed: true,
2061            modifier: CharModifier::default(),
2062        };
2063        let error = main_text(&word, &[piece], 10).unwrap_err().to_string();
2064        assert!(error.starts_with("LEGACY_DOC: "), "{error}");
2065        assert_eq!(main_text(&word, &[piece], 5).unwrap().len(), 5);
2066    }
2067
2068    #[test]
2069    fn a_self_linked_difat_sector_is_bounded_by_the_file() {
2070        // Header: 512-byte sectors, one FAT sector, a DIFAT chain that
2071        // starts at sector 0 and claims four billion sectors; sector 0
2072        // links back to itself and lists sector 0 as a FAT sector.
2073        let mut bytes = vec![0u8; 1024];
2074        bytes[..8].copy_from_slice(OLE_MAGIC);
2075        bytes[0x1A] = 3;
2076        bytes[0x1E] = 9;
2077        bytes[0x20] = 6;
2078        bytes[0x2C..0x30].copy_from_slice(&1u32.to_le_bytes());
2079        bytes[0x30..0x34].copy_from_slice(&END_OF_CHAIN.to_le_bytes());
2080        bytes[0x44..0x48].copy_from_slice(&0u32.to_le_bytes());
2081        bytes[0x48..0x4C].copy_from_slice(&u32::MAX.to_le_bytes());
2082        for slot in bytes[0x4C..512].as_chunks_mut::<4>().0 {
2083            *slot = NO_STREAM.to_le_bytes();
2084        }
2085        // Sector 0 (bytes 512..1024): 127 entries of 0, then the link to 0.
2086        bytes[1020..1024].copy_from_slice(&0u32.to_le_bytes());
2087        let started = std::time::Instant::now();
2088        let _ = CompoundFile::open(&bytes);
2089        assert!(started.elapsed() < std::time::Duration::from_secs(2));
2090    }
2091
2092    #[test]
2093    fn a_heading_keeps_its_italic_span() {
2094        let document = LegacyDocument {
2095            blocks: vec![Block::Paragraph(Paragraph {
2096                heading: Some(2),
2097                list: None,
2098                spans: vec![
2099                    Span {
2100                        text: "Fees ".into(),
2101                        ..Span::default()
2102                    },
2103                    Span {
2104                        text: "due".into(),
2105                        bold: false,
2106                        italic: true,
2107                    },
2108                ],
2109            })],
2110        };
2111        assert_eq!(to_markdown(&document), "## Fees *due*\n\n");
2112    }
2113
2114    fn story_chars(text: &str) -> Vec<StoryChar> {
2115        text.chars()
2116            .zip(0u32..)
2117            .map(|(ch, cp)| StoryChar {
2118                ch,
2119                cp,
2120                fc: cp,
2121                modifier: CharModifier::default(),
2122            })
2123            .collect()
2124    }
2125
2126    #[test]
2127    fn a_page_break_stays_inside_its_paragraph_and_a_section_mark_ends_it() {
2128        let (papx, chpx) = (FkpIndex { runs: Vec::new() }, FkpIndex { runs: Vec::new() });
2129        let lists = Lists::default();
2130        let chars = story_chars("ab\u{0C}cd\u{0C}ef\r");
2131        let story = |section_marks: Vec<u32>| Story {
2132            papx: &papx,
2133            chpx: &chpx,
2134            styles: &[],
2135            lists: &lists,
2136            section_marks,
2137        };
2138        let texts = |blocks: Vec<Block>| -> Vec<String> {
2139            blocks
2140                .iter()
2141                .map(|b| match b {
2142                    Block::Paragraph(p) => p.text(),
2143                    Block::Table(_) => "table".into(),
2144                })
2145                .collect()
2146        };
2147        // Neither \x0C ends a section: page breaks, one paragraph.
2148        assert_eq!(texts(story(Vec::new()).blocks(&chars)), ["ab\ncd\nef"]);
2149        // The second \x0C (CP 5) is a section mark: two paragraphs.
2150        assert_eq!(texts(story(vec![5]).blocks(&chars)), ["ab\ncd", "ef"]);
2151    }
2152
2153    #[test]
2154    fn a_field_nested_in_a_field_code_shows_only_the_outer_result() {
2155        let (papx, chpx) = (FkpIndex { runs: Vec::new() }, FkpIndex { runs: Vec::new() });
2156        let lists = Lists::default();
2157        // { IF { PAGE } = 1 "one" } displaying "one": the PAGE result "1"
2158        // sits in the outer field's code and is not shown.
2159        let chars = story_chars("a\u{13}IF \u{13}PAGE\u{14}1\u{15} = 1 \"one\"\u{14}one\u{15}b\r");
2160        let story = Story {
2161            papx: &papx,
2162            chpx: &chpx,
2163            styles: &[],
2164            lists: &lists,
2165            section_marks: Vec::new(),
2166        };
2167        let texts: Vec<String> = story
2168            .blocks(&chars)
2169            .iter()
2170            .map(|b| match b {
2171                Block::Paragraph(p) => p.text(),
2172                Block::Table(_) => "table".into(),
2173            })
2174            .collect();
2175        assert_eq!(texts, ["aoneb"]);
2176    }
2177
2178    #[test]
2179    fn an_all_false_field_stack_is_not_walked_per_character() {
2180        let (papx, chpx) = (FkpIndex { runs: Vec::new() }, FkpIndex { runs: Vec::new() });
2181        let lists = Lists::default();
2182        let depth = 40u32;
2183        let mut text = String::new();
2184        for _ in 0..depth {
2185            text.push('\u{13}');
2186            text.push('\u{14}');
2187        }
2188        text.push_str(&"x".repeat(depth as usize));
2189        text.push('\r');
2190        let chars = story_chars(&text);
2191        let story = Story {
2192            papx: &papx,
2193            chpx: &chpx,
2194            styles: &[],
2195            lists: &lists,
2196            section_marks: Vec::new(),
2197        };
2198        FIELD_CODE_STEPS.store(0, Ordering::Relaxed);
2199        let blocks = story.blocks(&chars);
2200        let steps = FIELD_CODE_STEPS.load(Ordering::Relaxed);
2201        assert!(
2202            steps <= chars.len(),
2203            "field-code check inspected {steps} stack entries for {} characters",
2204            chars.len()
2205        );
2206        let rendered: Vec<String> = blocks
2207            .iter()
2208            .map(|b| match b {
2209                Block::Paragraph(p) => p.text(),
2210                Block::Table(_) => "table".into(),
2211            })
2212            .collect();
2213        assert_eq!(rendered, ["x".repeat(depth as usize)]);
2214    }
2215
2216    #[test]
2217    fn a_main_story_past_the_logical_budget_is_refused() {
2218        let budget = crate::admission::InputLimits::default().max_story_units;
2219        let n = u32::try_from(budget).unwrap().saturating_add(1);
2220        let word = vec![b'A'; usize::try_from(n).unwrap()];
2221        let pieces = [Piece {
2222            cp_start: 0,
2223            cp_end: n,
2224            fc: 0,
2225            compressed: true,
2226            modifier: CharModifier::default(),
2227        }];
2228        match main_text(&word, &pieces, n) {
2229            Ok(chars) => panic!(
2230                "materialized {} logical characters past the budget",
2231                chars.len()
2232            ),
2233            Err(err) => assert!(
2234                err.to_string().contains("logical character budget"),
2235                "{err}"
2236            ),
2237        }
2238    }
2239
2240    #[test]
2241    fn a_doc_past_the_input_byte_budget_is_refused() {
2242        let budget = crate::admission::InputLimits::default().max_compressed_bytes;
2243        let mut bytes = vec![0u8; usize::try_from(budget).unwrap().saturating_add(1)];
2244        bytes[..OLE_MAGIC.len()].copy_from_slice(OLE_MAGIC);
2245        match read(&bytes) {
2246            Ok(_) => panic!("read a document past the input byte budget"),
2247            Err(err) => {
2248                let text = err.to_string();
2249                assert!(text.contains("input byte budget"), "{text}");
2250                assert!(text.contains(&(budget + 1).to_string()), "{text}");
2251                assert!(text.contains(&budget.to_string()), "{text}");
2252            }
2253        }
2254    }
2255
2256    /// A supplementary character split across two Unicode pieces is one
2257    /// character, as Word reads it; a lone high surrogate is a replacement
2258    /// mark, never dropped.
2259    #[test]
2260    fn a_surrogate_pair_spans_pieces_and_a_lone_half_is_marked() {
2261        // "a😀b" in UTF-16LE, its pair split between the pieces, which sit
2262        // apart in the stream (4 filler bytes between them).
2263        let mut word = Vec::new();
2264        for unit in [0x0061u16, 0xD83D] {
2265            word.extend_from_slice(&unit.to_le_bytes());
2266        }
2267        word.extend_from_slice(&[0xEE; 4]);
2268        for unit in [0xDE00u16, 0x0062, 0xD83D] {
2269            word.extend_from_slice(&unit.to_le_bytes());
2270        }
2271        let piece = |cp_start, cp_end, fc| Piece {
2272            cp_start,
2273            cp_end,
2274            fc,
2275            compressed: false,
2276            modifier: CharModifier::default(),
2277        };
2278        let text = |ccp| {
2279            main_text(&word, &[piece(0, 2, 0), piece(2, 5, 8)], ccp)
2280                .unwrap()
2281                .iter()
2282                .map(|c| c.ch)
2283                .collect::<String>()
2284        };
2285        assert_eq!(text(4), "a😀b");
2286        // The story ends on a high surrogate: Word shows a replacement mark.
2287        assert_eq!(text(5), "a😀b\u{FFFD}");
2288        // A high surrogate before a letter is a mark, and the letter stays.
2289        let lone: Vec<u8> = [0xD83Du16, 0x0063]
2290            .iter()
2291            .flat_map(|u| u.to_le_bytes())
2292            .collect();
2293        let chars: String = main_text(&lone, &[piece(0, 2, 0)], 2)
2294            .unwrap()
2295            .iter()
2296            .map(|c| c.ch)
2297            .collect();
2298        assert_eq!(chars, "\u{FFFD}c");
2299    }
2300
2301    #[test]
2302    fn a_piece_table_that_does_not_cover_the_story_is_refused() {
2303        let word = b"HelloWorld".to_vec();
2304        let piece = |cp_start, cp_end, fc| Piece {
2305            cp_start,
2306            cp_end,
2307            fc,
2308            compressed: true,
2309            modifier: CharModifier::default(),
2310        };
2311        for (pieces, case) in [
2312            (vec![piece(0, 5, 0), piece(7, 10, 7)], "a gap"),
2313            (vec![piece(2, 10, 2)], "starts after CP 0"),
2314            (vec![piece(0, 5, 0)], "ends before the story does"),
2315            (vec![piece(5, 10, 5), piece(0, 5, 0)], "out of order"),
2316        ] {
2317            let error = main_text(&word, &pieces, 10).map(|c| c.len());
2318            assert!(
2319                error
2320                    .as_ref()
2321                    .is_err_and(|e| e.to_string().contains("does not cover")),
2322                "{case}: {error:?}"
2323            );
2324        }
2325        let whole = main_text(&word, &[piece(0, 5, 0), piece(5, 10, 5)], 10).unwrap();
2326        assert_eq!(whole.len(), 10);
2327        // An empty piece (fast-saved files carry them) is no gap.
2328        let empty = [
2329            piece(0, 0, 0),
2330            piece(0, 5, 0),
2331            piece(5, 5, 9),
2332            piece(5, 10, 5),
2333        ];
2334        assert_eq!(main_text(&word, &empty, 10).unwrap().len(), 10);
2335    }
2336
2337    #[test]
2338    fn a_property_table_outside_its_stream_is_refused_not_dropped() {
2339        let table = vec![0u8; 64];
2340        let word = vec![0u8; 1024];
2341        let legacy = |error: &LegacyDocError| error.to_string().starts_with("LEGACY_DOC: ");
2342        // An absent table (no bytes) is fine wherever its offset points.
2343        assert!(FkpIndex::new(&word, &table, (9999, 0), Fkp::Paragraph).is_ok());
2344        assert!(heading_styles(&table, 9999, 0).is_ok_and(|styles| styles.is_empty()));
2345        assert!(section_marks(&table, (9999, 0)).is_ok_and(|marks| marks.is_empty()));
2346        assert!(Lists::new(&table, (9999, 0), (9999, 0)).is_ok());
2347        for (fc, lcb) in [(60, 12), (9999, 12), (u32::MAX, 12)] {
2348            for kind in [Fkp::Paragraph, Fkp::Character] {
2349                let result = FkpIndex::new(&word, &table, (fc, lcb), kind).map(|i| i.runs.len());
2350                assert!(
2351                    result.as_ref().is_err_and(legacy),
2352                    "{kind:?} {fc}: {result:?}"
2353                );
2354            }
2355            let styles = heading_styles(&table, fc, lcb);
2356            assert!(styles.as_ref().is_err_and(legacy), "STSH {fc}: {styles:?}");
2357            let marks = section_marks(&table, (fc, lcb));
2358            assert!(marks.as_ref().is_err_and(legacy), "PlcfSed {fc}: {marks:?}");
2359            for (lst, lfo) in [((fc, lcb), (0, 4)), ((0, 4), (fc, lcb))] {
2360                let lists = Lists::new(&table, lst, lfo).map(|_| ());
2361                assert!(lists.as_ref().is_err_and(legacy), "lists {fc}: {lists:?}");
2362            }
2363        }
2364        // A bin table whose one entry names FKP page 5 (bytes 2560..3072)
2365        // of a 1024-byte WordDocument stream.
2366        let mut plc = vec![0u8; 12];
2367        plc[4..8].copy_from_slice(&512u32.to_le_bytes());
2368        plc[8..12].copy_from_slice(&5u32.to_le_bytes());
2369        for kind in [Fkp::Paragraph, Fkp::Character] {
2370            let result = FkpIndex::new(&word, &plc, (0, 12), kind).map(|i| i.runs.len());
2371            assert!(result.as_ref().is_err_and(legacy), "{kind:?}: {result:?}");
2372        }
2373    }
2374
2375    #[test]
2376    fn empty_paragraphs_are_kept_in_the_docx_and_left_out_of_markdown() {
2377        let (papx, chpx) = (FkpIndex { runs: Vec::new() }, FkpIndex { runs: Vec::new() });
2378        let lists = Lists::default();
2379        let story = Story {
2380            papx: &papx,
2381            chpx: &chpx,
2382            styles: &[],
2383            lists: &lists,
2384            section_marks: Vec::new(),
2385        };
2386        // An empty and a blank (a tab) spacer between two paragraphs.
2387        let blocks = story.blocks(&story_chars("Before\r\r\t\rAfter\r"));
2388        let texts: Vec<String> = blocks
2389            .iter()
2390            .map(|b| match b {
2391                Block::Paragraph(p) => p.text(),
2392                Block::Table(_) => "table".into(),
2393            })
2394            .collect();
2395        assert_eq!(texts, ["Before", "", " ", "After"]);
2396        let mut document = LegacyDocument { blocks };
2397        assert_eq!(to_markdown(&document), "Before\n\nAfter\n\n");
2398        // An empty heading keeps its style too.
2399        document.blocks.insert(
2400            1,
2401            Block::Paragraph(Paragraph {
2402                heading: Some(8),
2403                ..plain("")
2404            }),
2405        );
2406        let docx = document_to_docx(&document).unwrap();
2407        let package = crate::opc::PartFs::open(&docx).unwrap();
2408        let body = package.part_string("word/document.xml").unwrap();
2409        let paragraphs: Vec<&str> = body
2410            .split("<w:p>")
2411            .skip(1)
2412            .map(|p| p.split("</w:p>").next().unwrap_or(""))
2413            .collect();
2414        assert_eq!(
2415            paragraphs,
2416            [
2417                "<w:r><w:t xml:space=\"preserve\">Before</w:t></w:r>",
2418                "<w:pPr><w:pStyle w:val=\"Heading8\"/></w:pPr>",
2419                "",
2420                "",
2421                "<w:r><w:t xml:space=\"preserve\">After</w:t></w:r>",
2422            ],
2423            "{body}"
2424        );
2425        assert!(crate::validate::ring1(&package).is_empty());
2426    }
2427
2428    #[test]
2429    fn the_empty_placeholder_is_in_no_paragraph_and_no_cell() {
2430        let table = |rows: &[&[&str]]| {
2431            Block::Table(Table {
2432                rows: rows
2433                    .iter()
2434                    .map(|row| row.iter().map(|cell| (*cell).to_string()).collect())
2435                    .collect(),
2436                header_rows: 1,
2437            })
2438        };
2439        let document = LegacyDocument {
2440            blocks: vec![
2441                Block::Paragraph(plain("see jubarteemptyparagraph0")),
2442                table(&[&["a", "jubarteemptyparagraph1 b"]]),
2443                Block::Paragraph(plain("")),
2444            ],
2445        };
2446        assert_eq!(empty_placeholder(&document), "jubarteemptyparagraph2");
2447
2448        // Cells never touch in the Markdown (a `|` stands between them), so
2449        // a word split across two cells is no collision.
2450        let split = LegacyDocument {
2451            blocks: vec![
2452                table(&[&["jubarteempty", "paragraph0"]]),
2453                Block::Paragraph(plain("")),
2454            ],
2455        };
2456        assert_eq!(empty_placeholder(&split), "jubarteemptyparagraph0");
2457        let docx = document_to_docx(&split).unwrap();
2458        let package = crate::opc::PartFs::open(&docx).unwrap();
2459        assert!(crate::validate::ring1(&package).is_empty());
2460        let body = package.part_string("word/document.xml").unwrap();
2461        for text in [">jubarteempty<", ">paragraph0<"] {
2462            assert!(body.contains(text), "{text}: {body}");
2463        }
2464        assert!(!body.contains("jubarteemptyparagraph0"), "{body}");
2465        let after_table = body.split("</w:tbl>").nth(1).unwrap_or("");
2466        assert!(after_table.contains("<w:p></w:p>"), "{body}");
2467    }
2468
2469    #[test]
2470    fn the_empty_placeholder_is_the_first_word_no_text_holds() {
2471        // The definition, tried word by word: what the one pass must equal.
2472        let reference = |texts: &[&str]| {
2473            (0u32..)
2474                .map(|n| format!("jubarteemptyparagraph{n}"))
2475                .find(|word| texts.iter().all(|text| !text.contains(word.as_str())))
2476                .unwrap_or_default()
2477        };
2478        for texts in [
2479            &["plain text"][..],
2480            &["jubarteemptyparagraph0"],
2481            // "05" holds word 0 but not word 5.
2482            &["jubarteemptyparagraph05", "jubarteemptyparagraph1"],
2483            // "123" holds words 1, 12 and 123.
2484            &["jubarteemptyparagraph123", "jubarteemptyparagraph0"],
2485            &["xjubarteemptyparagraphjubarteemptyparagraph0y"],
2486            &["jubarteemptyparagraph", "jubarteemptyparagraphx0"],
2487            &["jubarteemptyparagraph99999999999", "jubarteemptyparagraph0"],
2488            &[
2489                "jubarteemptyparagraph0 jubarteemptyparagraph2",
2490                "jubarteemptyparagraph1",
2491            ],
2492            &["Ünïcödé jubarteemptyparagraph0é jubarteemptyparagraph1"],
2493        ] {
2494            let document = LegacyDocument {
2495                blocks: texts
2496                    .iter()
2497                    .map(|text| Block::Paragraph(plain(text)))
2498                    .collect(),
2499            };
2500            assert_eq!(empty_placeholder(&document), reference(texts), "{texts:?}");
2501        }
2502    }
2503
2504    #[test]
2505    fn the_empty_placeholder_reads_the_text_once() {
2506        // A .doc can hold the words themselves; trying them one by one
2507        // against all of its text is quadratic.
2508        let words: Vec<String> = (0..20_000)
2509            .map(|n| format!("jubarteemptyparagraph{n}"))
2510            .collect();
2511        let document = LegacyDocument {
2512            blocks: vec![Block::Paragraph(plain(&words.join(" ")))],
2513        };
2514        assert_eq!(empty_placeholder(&document), "jubarteemptyparagraph20000");
2515    }
2516
2517    /// Story characters for one table: `|` ends a cell, `/` ends a row
2518    /// that `header` (by row) marks or not, `\r` a paragraph after it.
2519    fn table_story(cells: &str, header: &[bool]) -> Vec<Block> {
2520        let text: String = cells
2521            .chars()
2522            .map(|c| match c {
2523                '|' | '/' => '\u{07}',
2524                c => c,
2525            })
2526            .collect();
2527        let chars = story_chars(&text);
2528        let in_table = Props {
2529            in_table: true,
2530            ..Props::default()
2531        };
2532        let mut row = 0usize;
2533        let runs = cells
2534            .chars()
2535            .zip(0u32..)
2536            .map(|(c, fc)| {
2537                let props = match c {
2538                    '/' => {
2539                        row += 1;
2540                        Props {
2541                            row_end: true,
2542                            table_header: header.get(row - 1).copied().unwrap_or(false),
2543                            ..in_table
2544                        }
2545                    }
2546                    '\r' => Props::default(),
2547                    _ => in_table,
2548                };
2549                (fc, fc + 1, props)
2550            })
2551            .collect();
2552        let (papx, chpx) = (FkpIndex { runs }, FkpIndex { runs: Vec::new() });
2553        let lists = Lists::default();
2554        Story {
2555            papx: &papx,
2556            chpx: &chpx,
2557            styles: &[],
2558            lists: &lists,
2559            section_marks: Vec::new(),
2560        }
2561        .blocks(&chars)
2562    }
2563
2564    #[test]
2565    fn a_row_end_papx_reads_sprm_t_table_header() {
2566        // A PAPX at byte 2: cb 6 (11 grpprl bytes), istd 0, then
2567        // sprmPFInTable 1, sprmPFTtp 1 and sprmTTableHeader as given.
2568        let papx = |header: u8| {
2569            let mut page = vec![0u8; 512];
2570            page[2] = 6;
2571            page[3..14].copy_from_slice(&[
2572                0x00, 0x00, 0x16, 0x24, 0x01, 0x17, 0x24, 0x01, 0x04, 0x34, header,
2573            ]);
2574            papx_props(&page, 2).unwrap()
2575        };
2576        let row = papx(1);
2577        assert!(row.in_table && row.row_end && row.table_header, "{row:?}");
2578        assert!(!papx(0).table_header);
2579    }
2580
2581    #[test]
2582    fn only_rows_marked_as_headers_repeat_as_headers() {
2583        let cells = "a|b|/c|d|/e|f|/\r";
2584        let header_rows = |header: &[bool]| match table_story(cells, header).first() {
2585            Some(Block::Table(table)) => table.header_rows,
2586            other => panic!("{other:?}"),
2587        };
2588        assert_eq!(header_rows(&[false, false, false]), 0);
2589        assert_eq!(header_rows(&[true, true, false]), 2);
2590        // A header row after a data row is ignored ([MS-DOC] 2.6.3).
2591        assert_eq!(header_rows(&[false, true, false]), 0);
2592        let Some(Block::Table(table)) = table_story(cells, &[]).into_iter().next() else {
2593            panic!("no table");
2594        };
2595        assert_eq!(table.rows, [["a", "b"], ["c", "d"], ["e", "f"]]);
2596
2597        let repeated = |header_rows: usize| {
2598            let document = LegacyDocument {
2599                blocks: vec![Block::Table(Table {
2600                    header_rows,
2601                    ..table.clone()
2602                })],
2603            };
2604            let docx = document_to_docx(&document).unwrap();
2605            let package = crate::opc::PartFs::open(&docx).unwrap();
2606            assert!(crate::validate::ring1(&package).is_empty());
2607            let body = package.part_string("word/document.xml").unwrap();
2608            body.split("<w:tr>")
2609                .skip(1)
2610                .map(|row| row.starts_with("<w:trPr><w:tblHeader/></w:trPr>"))
2611                .collect::<Vec<bool>>()
2612        };
2613        assert_eq!(repeated(0), [false, false, false]);
2614        assert_eq!(repeated(1), [true, false, false]);
2615        assert_eq!(repeated(2), [true, true, false]);
2616    }
2617
2618    /// A Clx: one Prc per grpprl, then a Pcdt of compressed pieces, each
2619    /// `(cp_start, cp_end, word_offset, prm)`.
2620    fn clx(prcs: &[&[u8]], pieces: &[(u32, u32, u32, u16)]) -> Vec<u8> {
2621        let mut out = Vec::new();
2622        for grpprl in prcs {
2623            out.push(0x01);
2624            out.extend(u16::try_from(grpprl.len()).unwrap().to_le_bytes());
2625            out.extend(*grpprl);
2626        }
2627        let mut plc = Vec::new();
2628        for &(cp_start, ..) in pieces {
2629            plc.extend(cp_start.to_le_bytes());
2630        }
2631        plc.extend(pieces.last().map_or(0, |p| p.1).to_le_bytes());
2632        for &(_, _, offset, prm) in pieces {
2633            plc.extend([0, 0]);
2634            plc.extend((0x4000_0000 | (offset * 2)).to_le_bytes());
2635            plc.extend(prm.to_le_bytes());
2636        }
2637        out.push(0x02);
2638        out.extend(u32::try_from(plc.len()).unwrap().to_le_bytes());
2639        out.extend(plc);
2640        out
2641    }
2642
2643    #[test]
2644    fn a_piece_property_modifier_sets_bold_and_italic_over_the_chpx() {
2645        // The CHPX makes all ten characters bold. "Hello" carries a Prm1
2646        // naming Prc 0 (sprmCFItalic on); "World" a Prm0 with isprm 0x55
2647        // (sprmCFBold) and operand 0 (off).
2648        let italic: &[u8] = &[0x36, 0x08, 0x01];
2649        let prm1 = 1;
2650        let prm0_bold_off = 0x55 << 1;
2651        let table = clx(&[italic], &[(0, 5, 0, prm1), (5, 10, 5, prm0_bold_off)]);
2652        let len = u32::try_from(table.len()).unwrap();
2653        let pieces = pieces(&table, 0, len).unwrap();
2654        let chars = main_text(b"HelloWorld\r", &pieces, 10).unwrap();
2655        let mut chars = chars;
2656        chars.push(StoryChar {
2657            ch: '\r',
2658            cp: 10,
2659            fc: 10,
2660            modifier: CharModifier::default(),
2661        });
2662        let bold = Props {
2663            bold: true,
2664            ..Props::default()
2665        };
2666        let (papx, chpx) = (
2667            FkpIndex { runs: Vec::new() },
2668            FkpIndex {
2669                runs: vec![(0, 11, bold)],
2670            },
2671        );
2672        let lists = Lists::default();
2673        let story = Story {
2674            papx: &papx,
2675            chpx: &chpx,
2676            styles: &[],
2677            lists: &lists,
2678            section_marks: Vec::new(),
2679        };
2680        let blocks = story.blocks(&chars);
2681        let Some(Block::Paragraph(paragraph)) = blocks.first() else {
2682            panic!("{blocks:?}");
2683        };
2684        let spans: Vec<(&str, bool, bool)> = paragraph
2685            .spans
2686            .iter()
2687            .map(|s| (s.text.as_str(), s.bold, s.italic))
2688            .collect();
2689        assert_eq!(spans, [("Hello", true, true), ("World", false, false)]);
2690    }
2691
2692    #[test]
2693    fn a_property_modifier_the_clx_lacks_is_refused() {
2694        // A Prm1 naming Prc 3 of a Clx with none; a Prc longer than the
2695        // spec's 0x3FA2 bytes.
2696        let table = clx(&[], &[(0, 5, 0, (3 << 1) | 1)]);
2697        let len = u32::try_from(table.len()).unwrap();
2698        let error = pieces(&table, 0, len).map(|p| p.len()).unwrap_err();
2699        assert!(error.to_string().contains("property modifier"), "{error}");
2700        let long = vec![0u8; MAX_PRC_GRPPRL + 1];
2701        let table = clx(&[&long], &[(0, 5, 0, 0)]);
2702        let len = u32::try_from(table.len()).unwrap();
2703        assert!(pieces(&table, 0, len).is_err());
2704        // A Prm of 0 (Prm0, isprm 0, val 0) changes nothing.
2705        let table = clx(&[], &[(0, 5, 0, 0)]);
2706        let len = u32::try_from(table.len()).unwrap();
2707        let piece = pieces(&table, 0, len).unwrap();
2708        assert_eq!(
2709            piece.first().map(|p| p.modifier),
2710            Some(CharModifier::default())
2711        );
2712    }
2713
2714    #[test]
2715    fn a_property_modifier_with_a_missing_or_invalid_toggle_is_refused() {
2716        // A Prc whose grpprl ends after sprmCFBold's two bytes, one whose
2717        // operand is outside the four ToggleOperand values, and a Prm0
2718        // sprmCFBold with val 0x05.
2719        for (prcs, prm, case) in [
2720            (vec![vec![0x35u8, 0x08]], 1u16, "truncated"),
2721            (vec![vec![0x35, 0x08, 0x05]], 1, "invalid Prc operand"),
2722            (vec![], (0x05 << 8) | (0x55 << 1), "invalid Prm0 val"),
2723        ] {
2724            let prcs: Vec<&[u8]> = prcs.iter().map(Vec::as_slice).collect();
2725            let table = clx(&prcs, &[(0, 5, 0, prm)]);
2726            let len = u32::try_from(table.len()).unwrap();
2727            let error = pieces(&table, 0, len).map(|p| p.len());
2728            assert!(
2729                error
2730                    .as_ref()
2731                    .is_err_and(|e| e.to_string().contains("toggle")),
2732                "{case}: {error:?}"
2733            );
2734        }
2735        // 0x80 ("as the style") is valid and, as in the CHPX, reads as off.
2736        let table = clx(&[&[0x35, 0x08, 0x80]], &[(0, 5, 0, 1)]);
2737        let len = u32::try_from(table.len()).unwrap();
2738        let piece = pieces(&table, 0, len).unwrap();
2739        assert_eq!(piece.first().and_then(|p| p.modifier.bold), Some(false));
2740    }
2741
2742    #[test]
2743    fn a_blank_paragraph_keeps_its_line_breaks_in_the_docx() {
2744        // A paragraph holding only two line breaks (`\x0B`, or page breaks
2745        // read as line breaks) is three lines tall in Word.
2746        let document = LegacyDocument {
2747            blocks: vec![
2748                Block::Paragraph(plain("Before")),
2749                Block::Paragraph(plain("\n\n")),
2750                Block::Paragraph(plain("After")),
2751            ],
2752        };
2753        assert_eq!(to_markdown(&document), "Before\n\nAfter\n\n");
2754        let docx = document_to_docx(&document).unwrap();
2755        let package = crate::opc::PartFs::open(&docx).unwrap();
2756        let body = package.part_string("word/document.xml").unwrap();
2757        let paragraphs: Vec<&str> = body
2758            .split("<w:p>")
2759            .skip(1)
2760            .map(|p| p.split("</w:p>").next().unwrap_or(""))
2761            .collect();
2762        assert_eq!(
2763            paragraphs.get(1).copied(),
2764            Some("<w:r><w:br/></w:r><w:r><w:br/></w:r>"),
2765            "{body}"
2766        );
2767        assert!(crate::validate::ring1(&package).is_empty());
2768    }
2769
2770    /// A heading's manual line breaks stay breaks in the `.docx`, as Word
2771    /// draws them, and a heading holding only breaks converts like any
2772    /// blank paragraph instead of being refused.
2773    #[test]
2774    fn a_heading_keeps_its_line_breaks_in_the_docx() {
2775        let heading = |text: &str| Paragraph {
2776            heading: Some(1),
2777            ..plain(text)
2778        };
2779        let document = LegacyDocument {
2780            blocks: vec![
2781                Block::Paragraph(heading("Part one\nThe parties")),
2782                Block::Paragraph(heading("\n\n")),
2783                Block::Paragraph(plain("After")),
2784            ],
2785        };
2786        let docx = document_to_docx(&document).unwrap();
2787        let package = crate::opc::PartFs::open(&docx).unwrap();
2788        let body = package.part_string("word/document.xml").unwrap();
2789        let paragraphs: Vec<&str> = body
2790            .split("<w:p>")
2791            .skip(1)
2792            .map(|p| p.split("</w:p>").next().unwrap_or(""))
2793            .collect();
2794        assert!(
2795            paragraphs[0].contains("Part one</w:t></w:r><w:r><w:br/></w:r>"),
2796            "{body}"
2797        );
2798        assert!(
2799            paragraphs[1].ends_with("<w:r><w:br/></w:r><w:r><w:br/></w:r>"),
2800            "{body}"
2801        );
2802        assert!(paragraphs[1].contains("Heading1"), "{body}");
2803        assert!(crate::validate::ring1(&package).is_empty());
2804    }
2805
2806    /// A table stream holding a PlfLfo (one override, naming list 7) at 0,
2807    /// then a PlfLst (one simple list, lsid 7) at 20, then, outside the
2808    /// PlfLst's `lcb` as [MS-DOC] 2.5.6 puts it, the list's one LVL
2809    /// (decimal) unless `lvl` is false.
2810    fn lists_table(lvl: bool) -> Vec<u8> {
2811        let mut table = Vec::new();
2812        table.extend(1u32.to_le_bytes());
2813        let mut lfo = vec![0u8; 16];
2814        lfo[..4].copy_from_slice(&7u32.to_le_bytes());
2815        table.extend(lfo);
2816        table.extend(1u16.to_le_bytes());
2817        let mut lstf = vec![0u8; 28];
2818        lstf[..4].copy_from_slice(&7u32.to_le_bytes());
2819        lstf[26] = 0x01;
2820        table.extend(lstf);
2821        if lvl {
2822            table.extend([0u8; 28]);
2823            table.extend(0u16.to_le_bytes());
2824        }
2825        table
2826    }
2827
2828    #[test]
2829    fn list_tables_are_read_within_their_fib_ranges() {
2830        let (lfo, lst) = ((0, 20), (20, 30));
2831        let lists = Lists::new(&lists_table(true), lst, lfo).unwrap();
2832        assert_eq!(
2833            lists.item(1, 0),
2834            Some(ListItem {
2835                ordered: true,
2836                level: 0
2837            })
2838        );
2839        let legacy = |result: Result<Lists>| {
2840            result
2841                .map(|_| ())
2842                .is_err_and(|e| e.to_string().starts_with("LEGACY_DOC: "))
2843        };
2844        // A PlfLst whose cLst claims a list its lcb has no room for, a
2845        // PlfLfo whose lfoMac claims an override its lcb has no room for,
2846        // and an LVL past the end of the stream.
2847        assert!(legacy(Lists::new(&lists_table(true), (20, 2), lfo)));
2848        assert!(legacy(Lists::new(&lists_table(true), lst, (0, 4))));
2849        assert!(legacy(Lists::new(&lists_table(false), lst, lfo)));
2850    }
2851
2852    #[test]
2853    fn a_reversed_piece_is_refused_not_read_as_empty() {
2854        // CPs [100, 0, 5, 10]: the first piece runs backwards. Taken as
2855        // empty, the rest covers 0..10 and the decoder stopped at CP 100,
2856        // returning no text at all.
2857        let word = b"HelloWorld".to_vec();
2858        let piece = |cp_start, cp_end, fc| Piece {
2859            cp_start,
2860            cp_end,
2861            fc,
2862            compressed: true,
2863            modifier: CharModifier::default(),
2864        };
2865        let reversed = [piece(100, 0, 0), piece(0, 5, 0), piece(5, 10, 5)];
2866        let error = main_text(&word, &reversed, 10).map(|c| c.len());
2867        assert!(
2868            error
2869                .as_ref()
2870                .is_err_and(|e| e.to_string().contains("decreasing")),
2871            "{error:?}"
2872        );
2873        // A reversed piece past the main story is refused too: the CPs of
2874        // a piece table only ever increase.
2875        let late = [piece(0, 10, 0), piece(10, 4, 0)];
2876        assert!(main_text(&word, &late, 10).is_err());
2877    }
2878
2879    #[test]
2880    fn a_fat_sector_listed_twice_is_refused() {
2881        // 512-byte sectors, two FAT sectors both at sector 1.
2882        let mut bytes = vec![0u8; 512 * 3];
2883        bytes[..8].copy_from_slice(OLE_MAGIC);
2884        bytes[0x1A] = 3;
2885        bytes[0x1E] = 9;
2886        bytes[0x20] = 6;
2887        bytes[0x2C..0x30].copy_from_slice(&2u32.to_le_bytes());
2888        bytes[0x30..0x34].copy_from_slice(&END_OF_CHAIN.to_le_bytes());
2889        bytes[0x44..0x48].copy_from_slice(&END_OF_CHAIN.to_le_bytes());
2890        for slot in bytes[0x4C..512].as_chunks_mut::<4>().0 {
2891            *slot = NO_STREAM.to_le_bytes();
2892        }
2893        bytes[0x4C..0x50].copy_from_slice(&1u32.to_le_bytes());
2894        bytes[0x50..0x54].copy_from_slice(&1u32.to_le_bytes());
2895        let error = CompoundFile::open(&bytes)
2896            .map(|_| ())
2897            .unwrap_err()
2898            .to_string();
2899        assert!(error.contains("listed twice"), "{error}");
2900    }
2901
2902    #[test]
2903    fn title_and_headings_7_to_9_keep_their_word_styles() {
2904        let heading = |level, text: &str| {
2905            Block::Paragraph(Paragraph {
2906                heading: Some(level),
2907                list: None,
2908                spans: vec![Span {
2909                    text: text.into(),
2910                    ..Span::default()
2911                }],
2912            })
2913        };
2914        let document = LegacyDocument {
2915            blocks: vec![
2916                heading(0, "Agreement"),
2917                heading(8, "Deep"),
2918                heading(2, "Fees"),
2919                heading(9, "Deeper"),
2920            ],
2921        };
2922        let docx = document_to_docx(&document).unwrap();
2923        let package = crate::opc::PartFs::open(&docx).unwrap();
2924        let body = package.part_string("word/document.xml").unwrap();
2925        let used: Vec<&str> = body
2926            .split("<w:pStyle w:val=\"")
2927            .skip(1)
2928            .filter_map(|rest| rest.split('"').next())
2929            .collect();
2930        assert_eq!(used, ["Title", "Heading8", "Heading2", "Heading9"]);
2931        let styles = package.part_string("word/styles.xml").unwrap();
2932        for id in ["Title", "Heading8", "Heading9", "Heading2"] {
2933            assert!(
2934                styles.contains(&format!("w:styleId=\"{id}\"")),
2935                "{id}: {styles}"
2936            );
2937        }
2938        assert!(crate::validate::ring1(&package).is_empty());
2939    }
2940
2941    #[test]
2942    fn a_bullet_under_a_number_nests() {
2943        let document = LegacyDocument {
2944            blocks: vec![
2945                Block::Paragraph(Paragraph {
2946                    list: Some(ListItem {
2947                        ordered: true,
2948                        level: 0,
2949                    }),
2950                    ..plain("A")
2951                }),
2952                Block::Paragraph(Paragraph {
2953                    list: Some(ListItem {
2954                        ordered: false,
2955                        level: 1,
2956                    }),
2957                    ..plain("B")
2958                }),
2959            ],
2960        };
2961        // "1. " puts content at column 3; the child needs at least that.
2962        assert_eq!(to_markdown(&document), "1. A\n\n    - B\n\n");
2963    }
2964
2965    #[test]
2966    fn a_count_of_255_is_a_count_except_for_sprm_p_chg_tabs() {
2967        // A variable-length sprm (spra 6) with 255 operand bytes, then
2968        // sprmPFInTable.
2969        let mut grpprl = vec![0x00, 0xC6, 255];
2970        grpprl.extend(std::iter::repeat_n(0u8, 255));
2971        grpprl.extend([0x16, 0x24, 0x01]);
2972        let mut seen = Vec::new();
2973        for_each_sprm(&grpprl, |sprm, _| seen.push(sprm));
2974        assert_eq!(seen, [0xC600, 0x2416]);
2975        // sprmPChgTabs's long form sizes itself ([MS-DOC] 2.9.188): 255,
2976        // then cTabs deleted (4 bytes each), then cTabs added (3 bytes
2977        // each). The group goes on after it: here sprmCFBold.
2978        let mut seen = Vec::new();
2979        for_each_sprm(&[0x15, 0xC6, 255, 0, 0], |sprm, operand| {
2980            seen.push((sprm, operand.len()));
2981        });
2982        assert_eq!(seen, [(0xC615, 3)]);
2983        let long = [
2984            0x15, 0xC6, 255, 1, 0x10, 0x00, 0x20, 0x00, 1, 0x30, 0x00, 0x00, 0x35, 0x08, 0x01,
2985        ];
2986        let mut seen = Vec::new();
2987        for_each_sprm(&long, |sprm, operand| seen.push((sprm, operand.to_vec())));
2988        assert_eq!(seen.len(), 2, "{seen:?}");
2989        assert_eq!(seen[0].1.len(), 10);
2990        assert_eq!(seen[1], (0x0835, vec![0x01]));
2991        // A long form cut short stops the group, as any short operand does.
2992        let mut seen = Vec::new();
2993        for_each_sprm(&[0x15, 0xC6, 255, 2, 0, 0], |sprm, _| seen.push(sprm));
2994        assert!(seen.is_empty(), "{seen:?}");
2995    }
2996
2997    #[test]
2998    fn a_heading_does_not_read_its_style_bold_as_markup() {
2999        let document = LegacyDocument {
3000            blocks: vec![Block::Paragraph(Paragraph {
3001                heading: Some(1),
3002                list: None,
3003                spans: vec![Span {
3004                    text: "Term".into(),
3005                    bold: true,
3006                    italic: false,
3007                }],
3008            })],
3009        };
3010        assert_eq!(to_markdown(&document), "# Term\n\n");
3011    }
3012
3013    #[test]
3014    fn a_version_and_sector_size_mismatch_is_refused() {
3015        let mut bytes = vec![0u8; 1024];
3016        bytes[..8].copy_from_slice(OLE_MAGIC);
3017        bytes[0x1A] = 4; // version 4 ...
3018        bytes[0x1E] = 9; // ... with 512-byte sectors
3019        bytes[0x20] = 6;
3020        assert!(CompoundFile::open(&bytes).is_err());
3021    }
3022
3023    #[test]
3024    fn fat_sectors_are_capped_by_the_sectors_in_the_file() {
3025        // 1 MB, a self-linked DIFAT sector whose 127 slots all name sector
3026        // 0, a DIFAT count of 2^32-1 and a FAT count of 2^32-1: without a
3027        // cap the FAT grew to 127 entries per sector per pass (~130 MB).
3028        let mut bytes = vec![0u8; 1 << 20];
3029        bytes[..8].copy_from_slice(OLE_MAGIC);
3030        bytes[0x1A] = 3;
3031        bytes[0x1E] = 9;
3032        bytes[0x20] = 6;
3033        bytes[0x2C..0x30].copy_from_slice(&u32::MAX.to_le_bytes());
3034        bytes[0x30..0x34].copy_from_slice(&END_OF_CHAIN.to_le_bytes());
3035        bytes[0x44..0x48].copy_from_slice(&0u32.to_le_bytes());
3036        bytes[0x48..0x4C].copy_from_slice(&u32::MAX.to_le_bytes());
3037        for slot in bytes[0x4C..512].as_chunks_mut::<4>().0 {
3038            *slot = NO_STREAM.to_le_bytes();
3039        }
3040        bytes[1020..1024].copy_from_slice(&0u32.to_le_bytes());
3041        let started = std::time::Instant::now();
3042        let _ = CompoundFile::open(&bytes);
3043        assert!(started.elapsed() < std::time::Duration::from_secs(2));
3044    }
3045}
3046#[cfg(test)]
3047#[cfg_attr(all(coverage_nightly, test), coverage(off))]
3048mod legacy_byte_source_boundary_tests {
3049    use super::*;
3050    const FIXTURE: &[u8] = include_bytes!("../../../tests/fixtures/legacy/services.doc");
3051
3052    #[test]
3053    fn fib_classification_refuses_old_identifiers_and_both_password_flags() {
3054        let file = CompoundFile::open(FIXTURE).unwrap();
3055        let word = file.stream("WordDocument").unwrap();
3056        let frozen = word.clone();
3057        let baseline = Fib::parse(&word).unwrap();
3058        for (at, value, expected) in [
3059            (0, 0u16, "LEGACY_DOC: not a Word document (wIdent)"),
3060            (
3061                2,
3062                NFIB_WORD97 - 1,
3063                "LEGACY_DOC: a Word 6 or Word 95 document; open it in Word and save it as .docx",
3064            ),
3065            (
3066                0x0A,
3067                u16_at(&word, 0x0A).unwrap() | 0x0100,
3068                "LEGACY_DOC: an encrypted Word 97-2003 document; open it in Word and save it as .docx without a password",
3069            ),
3070            (
3071                0x0A,
3072                (u16_at(&word, 0x0A).unwrap() & !0x0100) | 0x8000,
3073                "LEGACY_DOC: an encrypted Word 97-2003 document; open it in Word and save it as .docx without a password",
3074            ),
3075        ] {
3076            let mut variant = word.clone();
3077            variant[at..at + 2].copy_from_slice(&value.to_le_bytes());
3078            assert_eq!(Fib::parse(&variant).err().unwrap().to_string(), expected);
3079            assert_eq!(word, frozen);
3080        }
3081        let mut alternate = word.clone();
3082        alternate[0x0A..0x0C]
3083            .copy_from_slice(&(u16_at(&word, 0x0A).unwrap() ^ 0x0200).to_le_bytes());
3084        let changed = Fib::parse(&alternate).unwrap();
3085        assert_eq!(changed.table_one, !baseline.table_one);
3086        assert_eq!(
3087            (
3088                changed.ccp_text,
3089                changed.fc_clx,
3090                changed.lcb_clx,
3091                changed.fc_stshf,
3092                changed.lcb_stshf,
3093                changed.plcf_sed
3094            ),
3095            (
3096                baseline.ccp_text,
3097                baseline.fc_clx,
3098                baseline.lcb_clx,
3099                baseline.fc_stshf,
3100                baseline.lcb_stshf,
3101                baseline.plcf_sed
3102            )
3103        );
3104        assert_eq!(word, frozen);
3105    }
3106
3107    #[test]
3108    fn corrupt_compound_header_and_directory_cycles_are_bounded_without_touching_fixture_bytes() {
3109        let frozen = FIXTURE.to_vec();
3110        for shift in [0u16, 5, 7, 15] {
3111            let mut bytes = frozen.clone();
3112            bytes[0x20..0x22].copy_from_slice(&shift.to_le_bytes());
3113            assert_eq!(
3114                CompoundFile::open(&bytes).err().unwrap().to_string(),
3115                "LEGACY_DOC: not a readable OLE compound file"
3116            );
3117        }
3118        let sector_size = 1usize << u16_at(FIXTURE, 0x1E).unwrap();
3119        let root_at = (u32_at(FIXTURE, 0x30).unwrap() as usize + 1) * sector_size;
3120        let mut wrong_root = frozen.clone();
3121        wrong_root[root_at + 66] = 2;
3122        assert_eq!(
3123            CompoundFile::open(&wrong_root).err().unwrap().to_string(),
3124            "LEGACY_DOC: not a readable OLE compound file"
3125        );
3126        let mut cycle = frozen.clone();
3127        cycle[root_at + 68..root_at + 72].copy_from_slice(&0u32.to_le_bytes());
3128        cycle[root_at + 76..root_at + 80].copy_from_slice(&0u32.to_le_bytes());
3129        let file = CompoundFile::open(&cycle).unwrap();
3130        assert!(file.stream("WordDocument").is_none());
3131        assert!(file.stream("absent").is_none());
3132        assert_eq!(FIXTURE, frozen.as_slice());
3133        assert!(read(FIXTURE).is_ok());
3134    }
3135
3136    #[test]
3137    fn main_story_stops_at_its_own_cp_boundary_before_unicode_later_story_pieces() {
3138        let word = [b'A', 0xb2, 0x03];
3139        let pieces = [
3140            Piece {
3141                cp_start: 0,
3142                cp_end: 0,
3143                fc: 0,
3144                compressed: true,
3145                modifier: CharModifier::default(),
3146            },
3147            Piece {
3148                cp_start: 0,
3149                cp_end: 1,
3150                fc: 0,
3151                compressed: true,
3152                modifier: CharModifier {
3153                    bold: Some(true),
3154                    italic: Some(false),
3155                },
3156            },
3157            Piece {
3158                cp_start: 1,
3159                cp_end: 2,
3160                fc: 1,
3161                compressed: false,
3162                modifier: CharModifier::default(),
3163            },
3164        ];
3165        for length in [0, 1] {
3166            let chars = main_text(&word, &pieces, length).unwrap();
3167            assert_eq!(chars.len(), length as usize);
3168            if length == 1 {
3169                assert_eq!((chars[0].ch, chars[0].cp, chars[0].fc), ('A', 0, 0));
3170                assert_eq!(
3171                    chars[0].modifier,
3172                    CharModifier {
3173                        bold: Some(true),
3174                        italic: Some(false)
3175                    }
3176                );
3177            }
3178        }
3179        let chars = main_text(&word, &pieces, 2).unwrap();
3180        assert_eq!(chars.iter().map(|s| s.ch).collect::<String>(), "Aβ");
3181        assert_eq!(
3182            chars.iter().map(|s| (s.cp, s.fc)).collect::<Vec<_>>(),
3183            vec![(0, 0), (1, 1)]
3184        );
3185        let error = piece_modifier(1, &[&[0x35, 0x08, 0x03, 0x36, 0x08, 0x01]])
3186            .err()
3187            .unwrap();
3188        assert_eq!(
3189            error.to_string(),
3190            "LEGACY_DOC: a text piece's property modifier has a bold or italic toggle that is missing or invalid"
3191        );
3192        assert_eq!(word, [b'A', 0xb2, 0x03]);
3193    }
3194
3195    #[test]
3196    fn unterminated_story_tail_and_whitespace_spans_keep_all_authored_characters() {
3197        let papx = FkpIndex { runs: Vec::new() };
3198        let chpx = FkpIndex { runs: Vec::new() };
3199        let lists = Lists::default();
3200        let story = Story {
3201            papx: &papx,
3202            chpx: &chpx,
3203            styles: &[],
3204            lists: &lists,
3205            section_marks: Vec::new(),
3206        };
3207        let chars = "owned tail"
3208            .chars()
3209            .enumerate()
3210            .map(|(i, ch)| StoryChar {
3211                ch,
3212                cp: i as u32,
3213                fc: i as u32,
3214                modifier: CharModifier::default(),
3215            })
3216            .collect::<Vec<_>>();
3217        let expected = vec![Block::Paragraph(Paragraph {
3218            spans: vec![Span {
3219                text: "owned tail".to_string(),
3220                ..Span::default()
3221            }],
3222            ..Paragraph::default()
3223        })];
3224        assert_eq!(story.blocks(&chars), expected);
3225        let spans = vec![
3226            Span {
3227                text: "owned".to_string(),
3228                bold: true,
3229                italic: false,
3230            },
3231            Span {
3232                text: " \n ".to_string(),
3233                ..Span::default()
3234            },
3235            Span {
3236                text: "tail".to_string(),
3237                bold: false,
3238                italic: true,
3239            },
3240        ];
3241        let frozen = spans.clone();
3242        assert_eq!(render_spans(&spans), "**owned** \\\n *tail*");
3243        assert_eq!(spans, frozen);
3244    }
3245}
3246
3247#[cfg(test)]
3248#[cfg_attr(all(coverage_nightly, test), coverage(off))]
3249mod legacy_regular_sector_source_owners {
3250    use super::*;
3251    const SOURCE: &[u8] = include_bytes!("../../../tests/fixtures/legacy/services.doc");
3252
3253    // Repackage actual source streams under the two MS-CFB sector formats.
3254    // Both streams exceed the 4096-byte mini-stream cutoff, so the root owns
3255    // no mini stream and there is no mini FAT. All stream bytes stay literal.
3256    fn regular_stream_package(word: &[u8], table: &[u8], version: u16, table_one: bool) -> Vec<u8> {
3257        assert!(word.len() >= 4096 && table.len() >= 4096);
3258        let sector_size = if version == 4 { 4096usize } else { 512usize };
3259        let per_fat = sector_size / 4;
3260        let word_count = word.len().div_ceil(sector_size);
3261        let table_count = table.len().div_ceil(sector_size);
3262        let data_count = 1 + word_count + table_count;
3263        let mut fat_count = 1;
3264        while (data_count + fat_count).div_ceil(per_fat) != fat_count {
3265            fat_count = (data_count + fat_count).div_ceil(per_fat);
3266        }
3267        assert!(fat_count <= 109);
3268        let mut bytes = vec![0u8; (1 + data_count + fat_count) * sector_size];
3269        let put16 = |bytes: &mut [u8], at: usize, value: u16| {
3270            bytes[at..at + 2].copy_from_slice(&value.to_le_bytes());
3271        };
3272        let put32 = |bytes: &mut [u8], at: usize, value: u32| {
3273            bytes[at..at + 4].copy_from_slice(&value.to_le_bytes());
3274        };
3275        bytes[..8].copy_from_slice(OLE_MAGIC);
3276        put16(&mut bytes, 0x18, 0x003e);
3277        put16(&mut bytes, 0x1a, version);
3278        put16(&mut bytes, 0x1c, 0xfffe);
3279        put16(&mut bytes, 0x1e, if version == 4 { 12 } else { 9 });
3280        put16(&mut bytes, 0x20, 6);
3281        put32(&mut bytes, 0x28, u32::from(version == 4));
3282        put32(&mut bytes, 0x2c, u32::try_from(fat_count).unwrap());
3283        put32(&mut bytes, 0x30, 0);
3284        put32(&mut bytes, 0x38, 4096);
3285        put32(&mut bytes, 0x3c, END_OF_CHAIN);
3286        put32(&mut bytes, 0x44, END_OF_CHAIN);
3287        for index in 0..109 {
3288            put32(
3289                &mut bytes,
3290                0x4c + index * 4,
3291                if index < fat_count {
3292                    u32::try_from(data_count + index).unwrap()
3293                } else {
3294                    NO_STREAM
3295                },
3296            );
3297        }
3298        let entries = [
3299            (
3300                "Root Entry",
3301                5u8,
3302                1u8,
3303                NO_STREAM,
3304                NO_STREAM,
3305                1u32,
3306                END_OF_CHAIN,
3307                0usize,
3308            ),
3309            ("WordDocument", 2, 1, 2, NO_STREAM, NO_STREAM, 1, word.len()),
3310            (
3311                if table_one { "1Table" } else { "0Table" },
3312                2,
3313                0,
3314                NO_STREAM,
3315                NO_STREAM,
3316                NO_STREAM,
3317                u32::try_from(1 + word_count).unwrap(),
3318                table.len(),
3319            ),
3320        ];
3321        for (index, (name, kind, color, left, right, child, start, size)) in
3322            entries.into_iter().enumerate()
3323        {
3324            let base = sector_size + index * 128;
3325            let name: Vec<u16> = name.encode_utf16().chain(std::iter::once(0)).collect();
3326            for (offset, character) in name.iter().enumerate() {
3327                put16(&mut bytes, base + offset * 2, *character);
3328            }
3329            put16(
3330                &mut bytes,
3331                base + 64,
3332                u16::try_from(name.len() * 2).unwrap(),
3333            );
3334            bytes[base + 66] = kind;
3335            bytes[base + 67] = color;
3336            put32(&mut bytes, base + 68, left);
3337            put32(&mut bytes, base + 72, right);
3338            put32(&mut bytes, base + 76, child);
3339            put32(&mut bytes, base + 116, start);
3340            put32(&mut bytes, base + 120, u32::try_from(size).unwrap());
3341        }
3342        bytes[sector_size * 2..sector_size * 2 + word.len()].copy_from_slice(word);
3343        let table_at = sector_size * (2 + word_count);
3344        bytes[table_at..table_at + table.len()].copy_from_slice(table);
3345        let mut fat = vec![NO_STREAM; fat_count * per_fat];
3346        fat[0] = END_OF_CHAIN;
3347        for (start, count) in [(1usize, word_count), (1 + word_count, table_count)] {
3348            for (index, sector) in fat.iter_mut().enumerate().skip(start).take(count) {
3349                *sector = if index + 1 == start + count {
3350                    END_OF_CHAIN
3351                } else {
3352                    u32::try_from(index + 1).unwrap()
3353                };
3354            }
3355        }
3356        for sector in fat.iter_mut().skip(data_count).take(fat_count) {
3357            *sector = 0xffff_fffd;
3358        }
3359        let fat_at = sector_size * (1 + data_count);
3360        for (index, sector) in fat.into_iter().enumerate() {
3361            put32(&mut bytes, fat_at + index * 4, sector);
3362        }
3363        bytes
3364    }
3365
3366    #[test]
3367    fn version_three_and_four_regular_streams_preserve_complete_legacy_source_blocks() {
3368        let original = SOURCE.to_vec();
3369        let file = CompoundFile::open(SOURCE).unwrap();
3370        let word = file.stream("WordDocument").unwrap();
3371        let original_word = word.clone();
3372        let fib = Fib::parse(&word).unwrap();
3373        let table = file
3374            .stream(if fib.table_one { "1Table" } else { "0Table" })
3375            .unwrap();
3376        let original_table = table.clone();
3377        let expected = read(SOURCE).unwrap();
3378        assert!(!expected.blocks.is_empty());
3379        let expected_markdown = doc_to_markdown(SOURCE).unwrap();
3380        let expected_docx = doc_to_docx(SOURCE).unwrap();
3381        for version in [3u16, 4] {
3382            for table_one in [false, true] {
3383                let mut word = original_word.clone();
3384                let flags = u16_at(&word, 0x0a).unwrap();
3385                word[0x0a..0x0c].copy_from_slice(
3386                    &(if table_one {
3387                        flags | 0x0200
3388                    } else {
3389                        flags & !0x0200
3390                    })
3391                    .to_le_bytes(),
3392                );
3393                let bytes = regular_stream_package(&word, &table, version, table_one);
3394                let before = bytes.clone();
3395                let repackaged = CompoundFile::open(&bytes).unwrap();
3396                assert_eq!(
3397                    repackaged.sector_size,
3398                    if version == 4 { 4096 } else { 512 }
3399                );
3400                assert!(repackaged.mini_fat.is_empty());
3401                assert!(repackaged.mini_stream.is_empty());
3402                assert_eq!(
3403                    repackaged.stream("WordDocument").as_deref(),
3404                    Some(word.as_slice())
3405                );
3406                assert_eq!(
3407                    repackaged
3408                        .stream(if table_one { "1Table" } else { "0Table" })
3409                        .as_deref(),
3410                    Some(table.as_slice())
3411                );
3412                assert_eq!(
3413                    read(&bytes).unwrap(),
3414                    expected,
3415                    "version{version}/table{table_one}"
3416                );
3417                assert_eq!(doc_to_markdown(&bytes).unwrap(), expected_markdown);
3418                assert_eq!(doc_to_docx(&bytes).unwrap(), expected_docx);
3419                assert_eq!(bytes, before);
3420            }
3421        }
3422        assert_eq!(word, original_word);
3423        assert_eq!(table, original_table);
3424        assert_eq!(SOURCE, original.as_slice());
3425    }
3426}
3427
3428#[cfg(test)]
3429#[cfg_attr(all(coverage_nightly, test), coverage(off))]
3430mod damaged_file_tests {
3431    use super::*;
3432
3433    fn fixtures() -> Vec<(String, Vec<u8>)> {
3434        let dir =
3435            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/legacy");
3436        ["services.doc", "styles.doc", "breaks.doc"]
3437            .into_iter()
3438            .map(|n| (n.to_string(), std::fs::read(dir.join(n)).unwrap()))
3439            .collect()
3440    }
3441
3442    /// A compound file cut short or with a byte changed anywhere is read or
3443    /// refused with an error: never a panic, and whatever reads converts.
3444    #[test]
3445    fn damaged_compound_files_are_read_or_refused() {
3446        for (name, bytes) in fixtures() {
3447            let whole = doc_to_markdown(&bytes).unwrap_or_else(|e| panic!("{name}: {e}"));
3448            assert!(!whole.trim().is_empty(), "{name}");
3449            let step = (bytes.len() / 97).max(1);
3450            let mut opened = 0;
3451            let mut refused = 0;
3452            for at in (0..bytes.len()).step_by(step) {
3453                let mut cut = bytes[..at].to_vec();
3454                let mut flipped = bytes.clone();
3455                flipped[at] ^= 0xFF;
3456                for damaged in [std::mem::take(&mut cut), flipped] {
3457                    match read(&damaged) {
3458                        Ok(document) => {
3459                            opened += 1;
3460                            let _ = to_markdown(&document);
3461                            let _ = doc_to_docx(&damaged);
3462                        }
3463                        Err(_) => refused += 1,
3464                    }
3465                }
3466            }
3467            assert!(
3468                refused > 0 && opened > 0,
3469                "{name}: read {opened}, refused {refused}"
3470            );
3471        }
3472    }
3473}