office_oxide 0.1.1

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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
// SPDX-License-Identifier: MIT OR Apache-2.0
#![warn(missing_docs)]
//! # office_oxide
//!
//! The fastest Office document processing library for Rust.
//!
//! Reads, writes, and edits **DOCX, XLSX, PPTX, DOC, XLS, PPT** — all six
//! Microsoft Office formats — with a single unified API and zero C/C++
//! dependencies.
//!
//! ## Quick start
//!
//! ```rust,no_run
//! use office_oxide::Document;
//!
//! let doc = Document::open("report.docx")?;
//! println!("{}", doc.plain_text());
//! # Ok::<(), office_oxide::OfficeError>(())
//! ```
//!
//! ## Feature flags
//!
//! | Flag | What it enables |
//! |------|-----------------|
//! | `python` | PyO3 Python bindings |
//! | `wasm` | wasm-bindgen WASM bindings |
//! | `mmap` | Memory-mapped file I/O |
//! | `parallel` | Rayon-based parallel processing |

// Sub-modules (previously separate crates)
/// Library version (matches the Cargo package version).
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Compound Binary File (OLE2/CFB) container reader, used by legacy formats.
pub mod cfb;
/// Shared OOXML primitives: OPC, XML utilities, relationships, theme, units.
pub mod core;
/// Legacy Word Binary (.doc) document reader.
pub mod doc;
/// Word document (.docx) reader, writer, and editor.
pub mod docx;
/// Legacy PowerPoint Binary (.ppt) presentation reader.
pub mod ppt;
/// PowerPoint presentation (.pptx) reader, writer, and editor.
pub mod pptx;
/// Legacy Excel Binary (.xls) workbook reader.
pub mod xls;
/// Excel spreadsheet (.xlsx) reader, writer, and editor.
pub mod xlsx;

// Top-level modules
mod convert_doc;
mod convert_docx;
mod convert_ppt;
mod convert_pptx;
mod convert_xls;
mod convert_xlsx;
/// Document creation API: write new DOCX/XLSX/PPTX from scratch or from IR.
pub mod create;
/// Document editing API: modify existing DOCX/XLSX/PPTX files in-place.
pub mod edit;
/// Top-level error type wrapping all format-specific errors.
pub mod error;
/// `DocumentFormat` enum and format detection utilities.
pub mod format;
/// Format-agnostic intermediate representation (IR) of a document.
pub mod ir;
mod ir_from_markdown;
mod ir_render;

#[cfg(not(target_family = "wasm"))]
pub mod ffi;

#[cfg(feature = "python")]
mod python;
#[cfg(feature = "wasm")]
mod wasm;

pub use core::OfficeDocument;
pub use error::{OfficeError, Result};
pub use format::DocumentFormat;
pub use ir::DocumentIR;

use std::io::{Read, Seek};
use std::path::Path;

use log::info;

/// Stack size for parsing threads (16 MB).
const PARSE_STACK_SIZE: usize = 16 * 1024 * 1024;

/// Minimum stack size to run inline without spawning a thread (12 MB).
/// Below this, we spawn a thread with PARSE_STACK_SIZE.
#[cfg(unix)]
const MIN_STACK_INLINE: usize = 12 * 1024 * 1024;

/// Check once whether the current environment has a large enough stack.
/// Caches the result for subsequent calls.
fn needs_stack_thread() -> bool {
    use std::sync::OnceLock;
    static NEEDS_THREAD: OnceLock<bool> = OnceLock::new();
    *NEEDS_THREAD.get_or_init(|| {
        // Check RLIMIT_STACK on Unix
        #[cfg(unix)]
        {
            let mut rlim = libc::rlimit {
                rlim_cur: 0,
                rlim_max: 0,
            };
            let ret = unsafe { libc::getrlimit(libc::RLIMIT_STACK, &mut rlim) };
            if ret == 0 && rlim.rlim_cur != libc::RLIM_INFINITY {
                return (rlim.rlim_cur as usize) < MIN_STACK_INLINE;
            }
            false // unlimited or error → assume enough
        }
        #[cfg(not(unix))]
        {
            false // On Windows/WASM, default is usually enough or handled differently
        }
    })
}

/// Run a parsing closure, spawning a thread with large stack only when needed.
/// On environments with sufficient stack (Rust programs, large-stack threads),
/// runs inline with zero overhead. On Python/constrained environments, spawns
/// a thread once and detects this via RLIMIT_STACK check (cached, O(1) after first call).
fn with_parse_stack<F, T>(f: F) -> Result<T>
where
    F: FnOnce() -> Result<T> + Send + 'static,
    T: Send + 'static,
{
    if needs_stack_thread() {
        std::thread::Builder::new()
            .stack_size(PARSE_STACK_SIZE)
            .spawn(f)
            .map_err(|e| OfficeError::UnsupportedFormat(format!("thread spawn failed: {e}")))?
            .join()
            .unwrap_or_else(|_| Err(OfficeError::UnsupportedFormat("parsing panicked".into())))
    } else {
        f()
    }
}

/// Dispatch a method call to the inner document type across all variants.
macro_rules! dispatch_inner {
    ($self:expr, $method:ident) => {
        match &$self.inner {
            DocumentInner::Docx(doc) => doc.$method(),
            DocumentInner::Xlsx(doc) => doc.$method(),
            DocumentInner::Pptx(doc) => doc.$method(),
            DocumentInner::Doc(doc) => doc.$method(),
            DocumentInner::Xls(doc) => doc.$method(),
            DocumentInner::Ppt(doc) => doc.$method(),
        }
    };
}

/// A unified document handle supporting DOCX, XLSX, PPTX, DOC, XLS, and PPT formats.
pub struct Document {
    inner: DocumentInner,
}

enum DocumentInner {
    Docx(Box<docx::DocxDocument>),
    Xlsx(Box<xlsx::XlsxDocument>),
    Pptx(Box<pptx::PptxDocument>),
    Doc(Box<doc::DocDocument>),
    Xls(Box<xls::XlsDocument>),
    Ppt(Box<ppt::PptDocument>),
}

impl Document {
    /// Open a document from a file path. Format is detected from the extension.
    #[must_use = "opening a document allocates — use the returned handle or drop it"]
    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref().to_owned();
        with_parse_stack(move || Self::open_inner(&path))
    }

    fn open_inner(path: &Path) -> Result<Self> {
        let format = DocumentFormat::from_path(path);
        info!("Document::open: {:?} format, path '{}'", format, path.display());
        let format = format.ok_or_else(|| {
            OfficeError::UnsupportedFormat(
                path.extension()
                    .and_then(|e| e.to_str())
                    .unwrap_or("(none)")
                    .to_string(),
            )
        })?;
        let format = sniff_format(path, format);

        match format {
            DocumentFormat::Docx => {
                let doc = docx::DocxDocument::open(path)?;
                Ok(Self {
                    inner: DocumentInner::Docx(Box::new(doc)),
                })
            },
            DocumentFormat::Xlsx => {
                let doc = xlsx::XlsxDocument::open(path)?;
                Ok(Self {
                    inner: DocumentInner::Xlsx(Box::new(doc)),
                })
            },
            DocumentFormat::Pptx => {
                let doc = pptx::PptxDocument::open(path)?;
                Ok(Self {
                    inner: DocumentInner::Pptx(Box::new(doc)),
                })
            },
            DocumentFormat::Doc => {
                let doc = doc::DocDocument::open(path)?;
                Ok(Self {
                    inner: DocumentInner::Doc(Box::new(doc)),
                })
            },
            DocumentFormat::Xls => {
                let doc = xls::XlsDocument::open(path)?;
                Ok(Self {
                    inner: DocumentInner::Xls(Box::new(doc)),
                })
            },
            DocumentFormat::Ppt => {
                let doc = ppt::PptDocument::open(path)?;
                Ok(Self {
                    inner: DocumentInner::Ppt(Box::new(doc)),
                })
            },
        }
    }

    /// Open a document from a file path using memory-mapped I/O.
    #[cfg(feature = "mmap")]
    pub fn open_mmap(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        let format = DocumentFormat::from_path(path).ok_or_else(|| {
            OfficeError::UnsupportedFormat(
                path.extension()
                    .and_then(|e| e.to_str())
                    .unwrap_or("(none)")
                    .to_string(),
            )
        })?;
        info!("Document::open_mmap: {:?} format, path '{}'", format, path.display());
        match format {
            DocumentFormat::Docx => {
                let doc = docx::DocxDocument::open_mmap(path)?;
                Ok(Self {
                    inner: DocumentInner::Docx(Box::new(doc)),
                })
            },
            DocumentFormat::Xlsx => {
                let doc = xlsx::XlsxDocument::open_mmap(path)?;
                Ok(Self {
                    inner: DocumentInner::Xlsx(Box::new(doc)),
                })
            },
            DocumentFormat::Pptx => {
                let doc = pptx::PptxDocument::open_mmap(path)?;
                Ok(Self {
                    inner: DocumentInner::Pptx(Box::new(doc)),
                })
            },
            _ => Err(OfficeError::UnsupportedFormat(format!("{format:?}"))),
        }
    }

    /// Open a document from any `Read + Seek` source with an explicit format.
    #[must_use = "opening a document allocates — use the returned handle or drop it"]
    pub fn from_reader<R: Read + Seek + Send + 'static>(
        reader: R,
        format: DocumentFormat,
    ) -> Result<Self> {
        with_parse_stack(move || Self::from_reader_inner(reader, format))
    }

    fn from_reader_inner<R: Read + Seek>(reader: R, format: DocumentFormat) -> Result<Self> {
        match format {
            DocumentFormat::Docx => {
                let doc = docx::DocxDocument::from_reader(reader)?;
                Ok(Self {
                    inner: DocumentInner::Docx(Box::new(doc)),
                })
            },
            DocumentFormat::Xlsx => {
                let doc = xlsx::XlsxDocument::from_reader(reader)?;
                Ok(Self {
                    inner: DocumentInner::Xlsx(Box::new(doc)),
                })
            },
            DocumentFormat::Pptx => {
                let doc = pptx::PptxDocument::from_reader(reader)?;
                Ok(Self {
                    inner: DocumentInner::Pptx(Box::new(doc)),
                })
            },
            DocumentFormat::Doc => {
                let doc = doc::DocDocument::from_reader(reader)?;
                Ok(Self {
                    inner: DocumentInner::Doc(Box::new(doc)),
                })
            },
            DocumentFormat::Xls => {
                let doc = xls::XlsDocument::from_reader(reader)?;
                Ok(Self {
                    inner: DocumentInner::Xls(Box::new(doc)),
                })
            },
            DocumentFormat::Ppt => {
                let doc = ppt::PptDocument::from_reader(reader)?;
                Ok(Self {
                    inner: DocumentInner::Ppt(Box::new(doc)),
                })
            },
        }
    }

    /// Returns the document format.
    pub fn format(&self) -> DocumentFormat {
        match &self.inner {
            DocumentInner::Docx(_) => DocumentFormat::Docx,
            DocumentInner::Xlsx(_) => DocumentFormat::Xlsx,
            DocumentInner::Pptx(_) => DocumentFormat::Pptx,
            DocumentInner::Doc(_) => DocumentFormat::Doc,
            DocumentInner::Xls(_) => DocumentFormat::Xls,
            DocumentInner::Ppt(_) => DocumentFormat::Ppt,
        }
    }

    /// Extract plain text using the format-specific implementation.
    pub fn plain_text(&self) -> String {
        dispatch_inner!(self, plain_text)
    }

    /// Convert to markdown using the format-specific implementation.
    pub fn to_markdown(&self) -> String {
        dispatch_inner!(self, to_markdown)
    }

    /// Convert to an HTML fragment.
    pub fn to_html(&self) -> String {
        self.to_ir().to_html()
    }

    /// Convert to the format-agnostic Document IR.
    pub fn to_ir(&self) -> DocumentIR {
        match &self.inner {
            DocumentInner::Docx(doc) => convert_docx::docx_to_ir(doc),
            DocumentInner::Xlsx(doc) => convert_xlsx::xlsx_to_ir(doc),
            DocumentInner::Pptx(doc) => convert_pptx::pptx_to_ir(doc),
            DocumentInner::Doc(doc) => convert_doc::doc_to_ir(doc),
            DocumentInner::Xls(doc) => convert_xls::xls_to_ir(doc),
            DocumentInner::Ppt(doc) => convert_ppt::ppt_to_ir(doc),
        }
    }

    /// Return the inner DOCX document, if this document is a DOCX.
    pub fn as_docx(&self) -> Option<&docx::DocxDocument> {
        match &self.inner {
            DocumentInner::Docx(doc) => Some(doc),
            _ => None,
        }
    }

    /// Return the inner XLSX document, if this document is an XLSX.
    pub fn as_xlsx(&self) -> Option<&xlsx::XlsxDocument> {
        match &self.inner {
            DocumentInner::Xlsx(doc) => Some(doc),
            _ => None,
        }
    }

    /// Return the inner PPTX document, if this document is a PPTX.
    pub fn as_pptx(&self) -> Option<&pptx::PptxDocument> {
        match &self.inner {
            DocumentInner::Pptx(doc) => Some(doc),
            _ => None,
        }
    }

    /// Return the inner DOC document, if this document is a legacy DOC.
    pub fn as_doc(&self) -> Option<&doc::DocDocument> {
        match &self.inner {
            DocumentInner::Doc(doc) => Some(doc),
            _ => None,
        }
    }

    /// Return the inner XLS document, if this document is a legacy XLS.
    pub fn as_xls(&self) -> Option<&xls::XlsDocument> {
        match &self.inner {
            DocumentInner::Xls(doc) => Some(doc),
            _ => None,
        }
    }

    /// Return the inner PPT document, if this document is a legacy PPT.
    pub fn as_ppt(&self) -> Option<&ppt::PptDocument> {
        match &self.inner {
            DocumentInner::Ppt(doc) => Some(doc),
            _ => None,
        }
    }

    /// Save/convert the document to a file. Format is detected from the extension.
    ///
    /// Legacy formats (DOC, XLS, PPT) are automatically converted to OOXML
    /// (DOCX, XLSX, PPTX) via the intermediate representation.
    pub fn save_as(&self, path: impl AsRef<Path>) -> Result<()> {
        let path = path.as_ref();
        let target_format = DocumentFormat::from_path(path).ok_or_else(|| {
            OfficeError::UnsupportedFormat(
                path.extension()
                    .and_then(|e| e.to_str())
                    .unwrap_or("(none)")
                    .to_string(),
            )
        })?;
        let ir = self.to_ir();
        create::create_from_ir(&ir, target_format, path)?;
        Ok(())
    }
}

impl OfficeDocument for Document {
    fn plain_text(&self) -> String {
        self.plain_text()
    }

    fn to_markdown(&self) -> String {
        self.to_markdown()
    }
}

/// Sniff magic bytes to detect format mismatches.
fn sniff_format(path: &Path, ext_format: DocumentFormat) -> DocumentFormat {
    let Ok(mut file) = std::fs::File::open(path) else {
        return ext_format;
    };
    let mut magic = [0u8; 4];
    if std::io::Read::read(&mut file, &mut magic).unwrap_or(0) < 4 {
        return ext_format;
    }

    let is_zip = magic == [0x50, 0x4B, 0x03, 0x04];
    let is_cfb = magic == [0xD0, 0xCF, 0x11, 0xE0];

    match ext_format {
        DocumentFormat::Doc if is_zip => DocumentFormat::Docx,
        DocumentFormat::Xls if is_zip => DocumentFormat::Xlsx,
        DocumentFormat::Ppt if is_zip => DocumentFormat::Pptx,
        DocumentFormat::Docx if is_cfb => DocumentFormat::Doc,
        DocumentFormat::Xlsx if is_cfb => DocumentFormat::Xls,
        DocumentFormat::Pptx if is_cfb => DocumentFormat::Ppt,
        _ => ext_format,
    }
}

/// Extract plain text from any supported document file.
pub fn extract_text(path: impl AsRef<Path>) -> Result<String> {
    Ok(Document::open(path)?.plain_text())
}

/// Convert any supported document file to markdown.
pub fn to_markdown(path: impl AsRef<Path>) -> Result<String> {
    Ok(Document::open(path)?.to_markdown())
}

/// Convert any supported document file to an HTML fragment.
pub fn to_html(path: impl AsRef<Path>) -> Result<String> {
    Ok(Document::open(path)?.to_html())
}