office_oxide 0.1.7

The fastest Office document processing library — DOCX, XLSX, PPTX, DOC, XLS, PPT
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use std::borrow::Cow;

use quick_xml::NsReader;
use quick_xml::events::BytesStart;
use quick_xml::name::{Namespace, ResolveResult};

use super::error::{Error, Result};

/// OOXML namespace URI constants. Match by URI, never by prefix.
pub mod ns {
    // OPC package namespaces
    /// `[Content_Types].xml` namespace.
    pub const CONTENT_TYPES: &[u8] =
        b"http://schemas.openxmlformats.org/package/2006/content-types";
    /// `.rels` relationships namespace.
    pub const RELATIONSHIPS: &[u8] =
        b"http://schemas.openxmlformats.org/package/2006/relationships";
    /// Core properties namespace.
    pub const CORE_PROPERTIES: &[u8] =
        b"http://schemas.openxmlformats.org/package/2006/metadata/core-properties";

    // Dublin Core
    /// Dublin Core elements namespace.
    pub const DC: &[u8] = b"http://purl.org/dc/elements/1.1/";
    /// Dublin Core terms namespace.
    pub const DC_TERMS: &[u8] = b"http://purl.org/dc/terms/";

    // DrawingML
    /// DrawingML main namespace (`a:` prefix).
    pub const DRAWING_ML: &[u8] = b"http://schemas.openxmlformats.org/drawingml/2006/main";

    // Format-specific
    /// WordprocessingML namespace (`w:` prefix).
    pub const WML: &[u8] = b"http://schemas.openxmlformats.org/wordprocessingml/2006/main";
    /// SpreadsheetML namespace (`x:` prefix).
    pub const SML: &[u8] = b"http://schemas.openxmlformats.org/spreadsheetml/2006/main";
    /// PresentationML namespace (`p:` prefix).
    pub const PML: &[u8] = b"http://schemas.openxmlformats.org/presentationml/2006/main";

    // Office document relationships (r: prefix in content XML)
    /// Relationships namespace used inline in content XML (`r:` prefix).
    pub const R: &[u8] = b"http://schemas.openxmlformats.org/officeDocument/2006/relationships";

    // Extended properties
    /// Extended (application) properties namespace.
    pub const EXTENDED_PROPERTIES: &[u8] =
        b"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties";

    // String variants for XML writing (same URIs as above, as &str)
    /// `WML` as a `&str` for use in XML writing.
    pub const WML_STR: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
    /// `SML` as a `&str` for use in XML writing.
    pub const SML_STR: &str = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
    /// `PML` as a `&str` for use in XML writing.
    pub const PML_STR: &str = "http://schemas.openxmlformats.org/presentationml/2006/main";
    /// `DRAWING_ML` as a `&str` for use in XML writing.
    pub const DRAWING_ML_STR: &str = "http://schemas.openxmlformats.org/drawingml/2006/main";
    /// `R` as a `&str` for use in XML writing.
    pub const R_STR: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";

    // Strict OOXML variants
    /// ISO 29500 Strict variant of `WML`.
    pub const STRICT_WML: &[u8] = b"http://purl.oclc.org/ooxml/wordprocessingml/main";
    /// ISO 29500 Strict variant of `SML`.
    pub const STRICT_SML: &[u8] = b"http://purl.oclc.org/ooxml/spreadsheetml/main";
    /// ISO 29500 Strict variant of `PML`.
    pub const STRICT_PML: &[u8] = b"http://purl.oclc.org/ooxml/presentationml/main";
    /// ISO 29500 Strict variant of `DRAWING_ML`.
    pub const STRICT_DRAWING: &[u8] = b"http://purl.oclc.org/ooxml/drawingml/main";
    /// ISO 29500 Strict variant of `R`.
    pub const STRICT_R: &[u8] = b"http://purl.oclc.org/ooxml/officeDocument/relationships";
}

/// Return the Strict namespace variant for a Transitional namespace, if one exists.
/// This enables transparent parsing of both ISO 29500 Strict and ECMA-376 Transitional documents.
fn strict_alternate(ns: &[u8]) -> Option<&'static [u8]> {
    match ns {
        x if x == ns::WML => Some(ns::STRICT_WML),
        x if x == ns::SML => Some(ns::STRICT_SML),
        x if x == ns::PML => Some(ns::STRICT_PML),
        x if x == ns::DRAWING_ML => Some(ns::STRICT_DRAWING),
        x if x == ns::R => Some(ns::STRICT_R),
        _ => None,
    }
}

/// Check if a resolved namespace + local name matches expected values.
/// Also matches the Strict (ISO 29500) variant of the namespace.
pub fn matches_start(resolve: &ResolveResult, start: &BytesStart, ns: &[u8], local: &[u8]) -> bool {
    start.local_name().as_ref() == local
        && match resolve {
            ResolveResult::Bound(Namespace(n)) => {
                *n == ns || strict_alternate(ns).is_some_and(|s| *n == s)
            },
            _ => false,
        }
}

/// Check if a resolved namespace matches, ignoring local name.
/// Also matches the Strict (ISO 29500) variant of the namespace.
pub fn matches_ns(resolve: &ResolveResult, ns: &[u8]) -> bool {
    match resolve {
        ResolveResult::Bound(Namespace(n)) => {
            *n == ns || strict_alternate(ns).is_some_and(|s| *n == s)
        },
        _ => false,
    }
}

/// Get a required attribute value, returning Error::MissingAttribute if absent.
pub fn required_attr<'a>(event: &'a BytesStart, key: &[u8]) -> Result<Cow<'a, [u8]>> {
    match event.try_get_attribute(key)? {
        Some(attr) => Ok(attr.value),
        None => Err(Error::MissingAttribute {
            element: String::from_utf8_lossy(event.local_name().as_ref()).into_owned(),
            attr: String::from_utf8_lossy(key).into_owned(),
        }),
    }
}

/// Get a required attribute as a UTF-8 string.
pub fn required_attr_str<'a>(event: &'a BytesStart, key: &[u8]) -> Result<Cow<'a, str>> {
    let value = required_attr(event, key)?;
    match value {
        Cow::Borrowed(b) => Ok(Cow::Borrowed(std::str::from_utf8(b)?)),
        Cow::Owned(v) => Ok(Cow::Owned(String::from_utf8(v).map_err(|e| e.utf8_error())?)),
    }
}

/// Get an optional attribute value.
pub fn optional_attr<'a>(event: &'a BytesStart, key: &[u8]) -> Result<Option<Cow<'a, [u8]>>> {
    Ok(event.try_get_attribute(key)?.map(|a| a.value))
}

/// Get an optional attribute as a UTF-8 string.
pub fn optional_attr_str<'a>(event: &'a BytesStart, key: &[u8]) -> Result<Option<Cow<'a, str>>> {
    match optional_attr(event, key)? {
        Some(Cow::Borrowed(b)) => Ok(Some(Cow::Borrowed(std::str::from_utf8(b)?))),
        Some(Cow::Owned(v)) => {
            Ok(Some(Cow::Owned(String::from_utf8(v).map_err(|e| e.utf8_error())?)))
        },
        None => Ok(None),
    }
}

/// Get an optional prefixed attribute by local name, trying all namespace prefixes.
/// For example, `optional_prefixed_attr_str(e, b"id")` matches `r:id`, `d3p1:id`, etc.
/// Falls back to unprefixed `id` if no prefixed match is found.
pub fn optional_prefixed_attr_str<'a>(
    event: &'a BytesStart,
    local_name: &[u8],
) -> Result<Option<Cow<'a, str>>> {
    for attr in event.attributes().flatten() {
        let key = attr.key.as_ref();
        // Check prefixed: look for `:localname` at the end
        if let Some(pos) = key.iter().position(|&b| b == b':') {
            if &key[pos + 1..] == local_name {
                return Ok(Some(Cow::Owned(unescape_attr_value(&attr)?)));
            }
        } else if key == local_name {
            return Ok(Some(Cow::Owned(unescape_attr_value(&attr)?)));
        }
    }
    Ok(None)
}

/// Parse an OOXML boolean toggle element.
///
/// Bare element (`<b/>`) = true, `val="0"` / `val="false"` / `val="off"` = false.
/// The `attr_name` is typically `b"w:val"` (WML) or `b"val"` (SML/DrawingML).
pub fn parse_toggle(e: &BytesStart, attr_name: &[u8]) -> bool {
    match optional_attr_str(e, attr_name) {
        Ok(Some(ref val)) => !matches!(val.as_ref(), "0" | "false" | "off"),
        _ => true,
    }
}

/// Read text content between start and end tags, consuming through the matching end tag.
pub fn read_text_content(reader: &mut NsReader<&[u8]>) -> Result<String> {
    use quick_xml::events::Event;
    let mut text = String::new();
    let mut depth = 1u32;
    loop {
        match reader.read_event()? {
            Event::Text(e) => {
                text.push_str(&unescape_text(&e)?);
            },
            Event::CData(e) => {
                text.push_str(std::str::from_utf8(&e)?);
            },
            Event::Start(_) => depth += 1,
            Event::End(_) => {
                depth -= 1;
                if depth == 0 {
                    break;
                }
            },
            Event::Eof => break,
            _ => {},
        }
    }
    Ok(text)
}

/// Skip over the current element and all its children (consumes through matching end tag).
pub fn skip_element(reader: &mut NsReader<&[u8]>) -> Result<()> {
    use quick_xml::events::Event;
    let mut depth = 1u32;
    loop {
        match reader.read_event()? {
            Event::Start(_) => depth += 1,
            Event::End(_) => {
                depth -= 1;
                if depth == 0 {
                    break;
                }
            },
            Event::Eof => break,
            _ => {},
        }
    }
    Ok(())
}

/// Create an NsReader configured for OOXML parsing.
pub fn make_reader(xml: &[u8]) -> NsReader<&[u8]> {
    let mut reader = NsReader::from_reader(xml);
    let config = reader.config_mut();
    config.trim_text(true);
    config.check_end_names = false;
    config.check_comments = false;
    reader
}

// ===========================================================================
// Fast Reader utilities (no namespace resolution — for hot-path parsing)
// ===========================================================================

/// Decode and unescape a `BytesText` event into an owned string.
///
/// quick-xml 0.40 removed `BytesText::unescape()` in favor of explicit
/// `decode()` followed by `escape::unescape()`. This helper preserves
/// the old single-call ergonomics so the parsers don't have to repeat
/// the two-step dance. `EncodingError` and `EscapeError` go through
/// `quick_xml::Error` to reach our `core::Error`.
pub fn unescape_text(e: &quick_xml::events::BytesText<'_>) -> Result<String> {
    let decoded = e.decode().map_err(quick_xml::Error::from)?;
    let unescaped = quick_xml::escape::unescape(&decoded).map_err(quick_xml::Error::from)?;
    Ok(unescaped.into_owned())
}

/// Decode and unescape an `Attribute` value into an owned string.
///
/// quick-xml 0.40 deprecated `Attribute::unescape_value()`, and under the
/// `encoding` feature the method is `cfg`-compiled out entirely (only
/// `decode_and_unescape_value(decoder)` remains). Feature unification can
/// turn `encoding` on transitively (e.g. via `calamine`), so relying on
/// `unescape_value()` makes the build fragile — it fails to compile the
/// moment any crate in the tree enables quick-xml's `encoding` feature.
///
/// OOXML documents are always UTF-8, so we decode the raw attribute bytes
/// as UTF-8 and unescape XML entities (`&amp;`, `&lt;`, …) explicitly. This
/// mirrors `unescape_text` above and is independent of the `encoding` feature.
///
/// One deliberate difference from `unescape_value()`: that method additionally
/// applied XML attribute-value whitespace normalization (a *literal* tab/CR/LF
/// inside a value collapses to a space), which `escape::unescape` does not do.
/// This never affects real OOXML — attribute values do not contain literal
/// control whitespace, and character references (`&#9;`, `&#10;`) are unescaped
/// identically either way.
pub fn unescape_attr_value(attr: &quick_xml::events::attributes::Attribute<'_>) -> Result<String> {
    let decoded = std::str::from_utf8(&attr.value)?;
    let unescaped = quick_xml::escape::unescape(decoded).map_err(quick_xml::Error::from)?;
    Ok(unescaped.into_owned())
}

/// Create a plain Reader (no namespace resolution) configured for OOXML parsing.
/// Use this for format-specific hot paths (worksheets, slides, document body)
/// where all elements are in a single known namespace.
pub fn make_fast_reader(xml: &[u8]) -> quick_xml::Reader<&[u8]> {
    let mut reader = quick_xml::Reader::from_reader(xml);
    let config = reader.config_mut();
    config.trim_text(true);
    config.check_end_names = false;
    config.check_comments = false;
    reader
}

/// Read text content between start and end tags using fast Reader.
pub fn read_text_content_fast(reader: &mut quick_xml::Reader<&[u8]>) -> Result<String> {
    use quick_xml::events::Event;
    let mut text = String::new();
    let mut depth = 1u32;
    loop {
        match reader.read_event()? {
            Event::Text(e) => {
                text.push_str(&unescape_text(&e)?);
            },
            Event::CData(e) => {
                text.push_str(&String::from_utf8_lossy(&e));
            },
            Event::Start(_) => depth += 1,
            Event::End(_) => {
                depth -= 1;
                if depth == 0 {
                    break;
                }
            },
            Event::Eof => break,
            _ => {},
        }
    }
    Ok(text)
}

/// Skip over the current element and all its children using fast Reader.
pub fn skip_element_fast(reader: &mut quick_xml::Reader<&[u8]>) -> Result<()> {
    use quick_xml::events::Event;
    let mut depth = 1u32;
    loop {
        match reader.read_event()? {
            Event::Start(_) => depth += 1,
            Event::End(_) => {
                depth -= 1;
                if depth == 0 {
                    break;
                }
            },
            Event::Eof => break,
            _ => {},
        }
    }
    Ok(())
}

/// Transcode XML bytes to UTF-8 if the XML declaration specifies a non-UTF-8 encoding.
/// Returns `None` if the data is already UTF-8 (the common case), or `Some(transcoded)`
/// if transcoding was needed. Callers should use the returned buffer for parsing.
pub fn ensure_utf8(data: &[u8]) -> Option<Vec<u8>> {
    // Quick check: if it's valid UTF-8 already, skip everything
    if std::str::from_utf8(data).is_ok() {
        return None;
    }

    // Look for encoding="..." in the first 200 bytes of the XML declaration
    let header = &data[..data.len().min(200)];
    let header_str = String::from_utf8_lossy(header);

    let encoding_name = if let Some(pos) = header_str.find("encoding=") {
        let rest = &header_str[pos + 9..];
        let quote = rest.as_bytes().first().copied().unwrap_or(b'"');
        if quote == b'"' || quote == b'\'' {
            let inner = &rest[1..];
            inner.split(quote as char).next().unwrap_or("utf-8")
        } else {
            return None;
        }
    } else {
        // No encoding declaration, try ISO-8859-1 as fallback for non-UTF-8
        "iso-8859-1"
    };

    let encoding = encoding_rs::Encoding::for_label(encoding_name.as_bytes())?;
    if encoding == encoding_rs::UTF_8 {
        return None;
    }

    let (result, _, had_errors) = encoding.decode(data);
    if had_errors {
        return None;
    }

    // Replace the encoding declaration with utf-8 so the XML parser doesn't complain
    let mut utf8 = result.into_owned().into_bytes();
    if let Some(pos) = utf8
        .windows(9)
        .position(|w| w.eq_ignore_ascii_case(b"encoding="))
    {
        let rest = &utf8[pos + 9..];
        if let Some(&quote) = rest.first() {
            if quote == b'"' || quote == b'\'' {
                if let Some(end) = rest[1..].iter().position(|&b| b == quote) {
                    let start = pos + 10;
                    let end = start + end;
                    utf8.splice(start..end, b"utf-8".iter().copied());
                }
            }
        }
    }

    Some(utf8)
}

#[cfg(test)]
mod attr_tests {
    use super::unescape_attr_value;
    use quick_xml::events::BytesStart;

    /// Parse `<e {attrs}>` and unescape the value of attribute `key`.
    fn attr_value(attrs: &str, key: &str) -> String {
        let start = BytesStart::from_content(format!("e {attrs}"), 1);
        let attr = start
            .attributes()
            .map(|a| a.unwrap())
            .find(|a| a.key.as_ref() == key.as_bytes())
            .expect("attribute present");
        unescape_attr_value(&attr).unwrap()
    }

    #[test]
    fn unescapes_predefined_and_numeric_entities() {
        assert_eq!(attr_value(r#"v="a &amp; b &lt;x&gt; &#65;""#, "v"), "a & b <x> A");
    }

    #[test]
    fn passes_plain_value_through_unchanged() {
        assert_eq!(attr_value(r#"r:id="rId7""#, "r:id"), "rId7");
    }

    #[test]
    fn unescapes_ampersand_in_hyperlink_target() {
        assert_eq!(
            attr_value(r#"Target="https://x/?a=1&amp;b=2""#, "Target"),
            "https://x/?a=1&b=2"
        );
    }
}