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
use std::collections::HashMap;

use quick_xml::Writer;
use quick_xml::events::{BytesDecl, BytesStart, Event};

use super::error::{Error, Result};
use super::opc::PartName;
use super::xml;

/// Standard relationship type URIs (Transitional / ECMA-376).
pub mod rel_types {
    /// Relationship type for the main office document part.
    pub const OFFICE_DOCUMENT: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
    /// Relationship type for core (Dublin Core) properties.
    pub const CORE_PROPERTIES: &str =
        "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties";
    /// Relationship type for extended (application) properties.
    pub const EXTENDED_PROPERTIES: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties";
    /// Relationship type for the package thumbnail.
    pub const THUMBNAIL: &str =
        "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail";
    /// Relationship type for `styles.xml`.
    pub const STYLES: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles";
    /// Relationship type for `theme/theme1.xml`.
    pub const THEME: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme";
    /// Relationship type for document settings.
    pub const SETTINGS: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings";
    /// Relationship type for the font table.
    pub const FONT_TABLE: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable";
    /// Relationship type for embedded images.
    pub const IMAGE: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
    /// Relationship type for hyperlinks.
    pub const HYPERLINK: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink";
    /// Relationship type for `numbering.xml`.
    pub const NUMBERING: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering";
    /// Relationship type for comments.
    pub const COMMENTS: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments";
    /// Relationship type for document headers.
    pub const HEADER: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header";
    /// Relationship type for document footers.
    pub const FOOTER: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer";
    /// Relationship type for worksheet parts.
    pub const WORKSHEET: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet";
    /// Relationship type for the shared string table.
    pub const SHARED_STRINGS: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings";
    /// Relationship type for slide parts.
    pub const SLIDE: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide";
    /// Relationship type for slide layout parts.
    pub const SLIDE_LAYOUT: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout";
    /// Relationship type for slide master parts.
    pub const SLIDE_MASTER: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster";
    /// Relationship type for notes slide parts.
    pub const NOTES_SLIDE: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide";
    /// Relationship type for chart parts.
    pub const CHART: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart";
    /// Relationship type for the footnotes part.
    pub const FOOTNOTES: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes";
    /// Relationship type for the endnotes part.
    pub const ENDNOTES: &str =
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes";
}

/// Strict (ISO 29500) relationship type prefix.
const STRICT_REL_PREFIX: &str = "http://purl.oclc.org/ooxml/officeDocument/relationships/";
/// Transitional relationship type prefix.
const TRANSITIONAL_REL_PREFIX: &str =
    "http://schemas.openxmlformats.org/officeDocument/2006/relationships/";

/// Normalize a Strict relationship type URI to its Transitional equivalent.
/// Strict uses `http://purl.oclc.org/ooxml/officeDocument/relationships/...`
/// Transitional uses `http://schemas.openxmlformats.org/officeDocument/2006/relationships/...`
/// If it's already Transitional or an unrecognized URI, return as-is.
fn normalize_rel_type(rel_type: String) -> String {
    if let Some(suffix) = rel_type.strip_prefix(STRICT_REL_PREFIX) {
        format!("{TRANSITIONAL_REL_PREFIX}{suffix}")
    } else {
        rel_type
    }
}

/// Indicates whether a relationship target is inside or outside the package.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TargetMode {
    /// Target is another part within the same OPC package.
    Internal,
    /// Target is an external resource (e.g., a hyperlink URL).
    External,
}

/// A single relationship entry from a `.rels` file.
#[derive(Debug, Clone)]
pub struct Relationship {
    /// Relationship ID (`rId1`, `rId2`, …).
    pub id: String,
    /// Relationship type URI.
    pub rel_type: String,
    /// Target path or URL.
    pub target: String,
    /// Whether the target is internal or external.
    pub target_mode: TargetMode,
}

/// Parsed collection of relationships from a `.rels` file.
#[derive(Debug, Clone)]
pub struct Relationships {
    rels: Vec<Relationship>,
    by_id: HashMap<String, usize>,
    by_type: HashMap<String, Vec<usize>>,
}

impl Relationships {
    /// Parse a `.rels` XML file.
    pub fn parse(xml_data: &[u8]) -> Result<Self> {
        let mut reader = xml::make_fast_reader(xml_data);
        let mut rels = Vec::new();

        loop {
            match reader.read_event()? {
                Event::Start(ref e) | Event::Empty(ref e)
                    if e.local_name().as_ref() == b"Relationship" =>
                {
                    let id = xml::required_attr_str(e, b"Id")?.into_owned();
                    let rel_type =
                        normalize_rel_type(xml::required_attr_str(e, b"Type")?.into_owned());
                    let target = xml::required_attr_str(e, b"Target")?.into_owned();
                    let target_mode = match xml::optional_attr_str(e, b"TargetMode")? {
                        Some(ref m) if m.eq_ignore_ascii_case("External") => TargetMode::External,
                        _ => TargetMode::Internal,
                    };
                    rels.push(Relationship {
                        id,
                        rel_type,
                        target,
                        target_mode,
                    });
                },
                Event::Eof => break,
                _ => {},
            }
        }

        Ok(Self::from_vec(rels))
    }

    /// Create an empty relationships collection.
    pub fn empty() -> Self {
        Self {
            rels: Vec::new(),
            by_id: HashMap::new(),
            by_type: HashMap::new(),
        }
    }

    fn from_vec(rels: Vec<Relationship>) -> Self {
        let mut by_id = HashMap::with_capacity(rels.len());
        let mut by_type: HashMap<String, Vec<usize>> = HashMap::new();
        for (i, r) in rels.iter().enumerate() {
            by_id.insert(r.id.clone(), i);
            by_type.entry(r.rel_type.clone()).or_default().push(i);
        }
        Self {
            rels,
            by_id,
            by_type,
        }
    }

    /// Look up a relationship by its ID.
    pub fn get_by_id(&self, id: &str) -> Option<&Relationship> {
        self.by_id.get(id).map(|&i| &self.rels[i])
    }

    /// Return all relationships with the given type URI.
    pub fn get_by_type(&self, rel_type: &str) -> Vec<&Relationship> {
        self.by_type
            .get(rel_type)
            .map(|indices| indices.iter().map(|&i| &self.rels[i]).collect())
            .unwrap_or_default()
    }

    /// Return the first relationship with the given type URI.
    pub fn first_by_type(&self, rel_type: &str) -> Option<&Relationship> {
        self.by_type
            .get(rel_type)
            .and_then(|indices| indices.first().map(|&i| &self.rels[i]))
    }

    /// Return a slice of all relationships in parse order.
    pub fn all(&self) -> &[Relationship] {
        &self.rels
    }

    /// Resolve an internal relationship target relative to a source part name.
    ///
    /// For package-level relationships (source is root), pass a source of `PartName::new("/").ok()`
    /// or use `resolve_target_from_root`.
    pub fn resolve_target(&self, id: &str, source: &PartName) -> Result<PartName> {
        let rel = self
            .get_by_id(id)
            .ok_or_else(|| Error::RelationshipNotFound(id.to_string()))?;

        if rel.target_mode == TargetMode::External {
            return Err(Error::Unsupported(format!(
                "cannot resolve external target: {}",
                rel.target
            )));
        }

        source.resolve_relative(&rel.target)
    }

    /// Resolve an internal relationship target relative to the package root.
    pub fn resolve_target_from_root(&self, id: &str) -> Result<PartName> {
        let rel = self
            .get_by_id(id)
            .ok_or_else(|| Error::RelationshipNotFound(id.to_string()))?;

        if rel.target_mode == TargetMode::External {
            return Err(Error::Unsupported(format!(
                "cannot resolve external target: {}",
                rel.target
            )));
        }

        // Package-level targets are relative to root
        let target = if rel.target.starts_with('/') {
            rel.target.clone()
        } else {
            format!("/{}", rel.target)
        };
        PartName::new(&target)
    }
}

/// Builder for constructing relationship XML for the write path.
#[derive(Debug, Clone)]
pub struct RelationshipsBuilder {
    rels: Vec<Relationship>,
    next_id: u32,
}

impl RelationshipsBuilder {
    /// Create an empty builder.
    pub fn new() -> Self {
        Self {
            rels: Vec::new(),
            next_id: 1,
        }
    }

    /// Add a relationship and return the generated rId.
    pub fn add(&mut self, rel_type: &str, target: &str) -> String {
        self.add_with_mode(rel_type, target, TargetMode::Internal)
    }

    /// Add a relationship with explicit target mode and return the generated rId.
    pub fn add_with_mode(
        &mut self,
        rel_type: &str,
        target: &str,
        target_mode: TargetMode,
    ) -> String {
        let id = format!("rId{}", self.next_id);
        self.next_id += 1;
        self.rels.push(Relationship {
            id: id.clone(),
            rel_type: rel_type.to_string(),
            target: target.to_string(),
            target_mode,
        });
        id
    }

    /// Add a relationship with an explicit ID (for round-trip preservation).
    pub fn add_with_id(&mut self, id: &str, rel_type: &str, target: &str, target_mode: TargetMode) {
        self.rels.push(Relationship {
            id: id.to_string(),
            rel_type: rel_type.to_string(),
            target: target.to_string(),
            target_mode,
        });
    }

    /// Returns `true` if no relationships have been added.
    pub fn is_empty(&self) -> bool {
        self.rels.is_empty()
    }

    /// Serialize to `.rels` XML bytes.
    pub fn serialize(&self) -> Vec<u8> {
        let mut writer = Writer::new_with_indent(Vec::new(), b' ', 2);

        writer
            .write_event(Event::Decl(BytesDecl::new("1.0", Some("UTF-8"), Some("yes"))))
            .expect("write decl");

        let mut root = BytesStart::new("Relationships");
        root.push_attribute((
            "xmlns",
            "http://schemas.openxmlformats.org/package/2006/relationships",
        ));
        writer.write_event(Event::Start(root)).expect("write start");

        for rel in &self.rels {
            let mut elem = BytesStart::new("Relationship");
            elem.push_attribute(("Id", rel.id.as_str()));
            elem.push_attribute(("Type", rel.rel_type.as_str()));
            elem.push_attribute(("Target", rel.target.as_str()));
            if rel.target_mode == TargetMode::External {
                elem.push_attribute(("TargetMode", "External"));
            }
            writer.write_event(Event::Empty(elem)).expect("write rel");
        }

        writer
            .write_event(Event::End(quick_xml::events::BytesEnd::new("Relationships")))
            .expect("write end");

        writer.into_inner()
    }
}

impl Default for RelationshipsBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const SAMPLE_RELS: &[u8] = br#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
  <Relationship Id="rId1"
    Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"
    Target="word/document.xml"/>
  <Relationship Id="rId2"
    Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"
    Target="docProps/core.xml"/>
  <Relationship Id="rId3"
    Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"
    Target="docProps/app.xml"/>
</Relationships>"#;

    #[test]
    fn parse_relationships() {
        let rels = Relationships::parse(SAMPLE_RELS).unwrap();
        assert_eq!(rels.all().len(), 3);
    }

    #[test]
    fn get_by_id() {
        let rels = Relationships::parse(SAMPLE_RELS).unwrap();
        let r = rels.get_by_id("rId1").unwrap();
        assert_eq!(r.target, "word/document.xml");
        assert_eq!(r.target_mode, TargetMode::Internal);
    }

    #[test]
    fn get_by_type() {
        let rels = Relationships::parse(SAMPLE_RELS).unwrap();
        let docs = rels.get_by_type(rel_types::OFFICE_DOCUMENT);
        assert_eq!(docs.len(), 1);
        assert_eq!(docs[0].target, "word/document.xml");
    }

    #[test]
    fn first_by_type() {
        let rels = Relationships::parse(SAMPLE_RELS).unwrap();
        let r = rels.first_by_type(rel_types::CORE_PROPERTIES).unwrap();
        assert_eq!(r.target, "docProps/core.xml");
    }

    #[test]
    fn resolve_target_from_root() {
        let rels = Relationships::parse(SAMPLE_RELS).unwrap();
        let pn = rels.resolve_target_from_root("rId1").unwrap();
        assert_eq!(pn.as_str(), "/word/document.xml");
    }

    #[test]
    fn builder_round_trip() {
        let mut builder = RelationshipsBuilder::new();
        let id = builder.add(rel_types::OFFICE_DOCUMENT, "word/document.xml");
        assert_eq!(id, "rId1");

        let xml = builder.serialize();
        let rels = Relationships::parse(&xml).unwrap();
        assert_eq!(rels.all().len(), 1);
        assert_eq!(rels.get_by_id("rId1").unwrap().rel_type, rel_types::OFFICE_DOCUMENT);
    }
}