Skip to main content

oxml_opc/
relationship.rs

1//! Parsing and writing of `.rels` relationship files.
2
3use std::collections::{HashMap, HashSet};
4use std::sync::Arc;
5
6use quick_xml::encoding::Decoder;
7use quick_xml::events::{BytesDecl, BytesEnd, BytesStart, Event};
8use quick_xml::name::ResolveResult;
9use quick_xml::reader::NsReader;
10use quick_xml::{Writer, XmlVersion};
11
12use crate::error::{OpcError, Result};
13
14const RELATIONSHIPS_NAMESPACE: &[u8] =
15    b"http://schemas.openxmlformats.org/package/2006/relationships";
16
17/// Well-known OOXML relationship types.
18pub mod rel_types {
19    // Package-level relationships.
20    pub const CORE_PROPERTIES: &str =
21        "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties";
22    pub const THUMBNAIL: &str =
23        "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail";
24    pub const DIGITAL_SIGNATURE_ORIGIN: &str =
25        "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/origin";
26    pub const DIGITAL_SIGNATURE: &str =
27        "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature";
28
29    // Shared officeDocument relationships.
30    pub const DOCUMENT: &str =
31        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
32    pub const EXTENDED_PROPERTIES: &str =
33        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties";
34    pub const CUSTOM_PROPERTIES: &str =
35        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties";
36    pub const STYLES: &str =
37        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles";
38    pub const NUMBERING: &str =
39        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering";
40    pub const HEADER: &str =
41        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header";
42    pub const FOOTER: &str =
43        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer";
44    pub const IMAGE: &str =
45        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
46    pub const AUDIO: &str =
47        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/audio";
48    pub const VIDEO: &str =
49        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/video";
50    pub const POWERPOINT_MEDIA: &str =
51        "http://schemas.microsoft.com/office/2007/relationships/media";
52    pub const SETTINGS: &str =
53        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings";
54    pub const WEB_SETTINGS: &str =
55        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings";
56    pub const FONT_TABLE: &str =
57        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable";
58    pub const FONT: &str =
59        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/font";
60    pub const THEME: &str =
61        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme";
62    pub const HYPERLINK: &str =
63        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink";
64    pub const FOOTNOTES: &str =
65        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes";
66    pub const ENDNOTES: &str =
67        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes";
68    pub const COMMENTS: &str =
69        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments";
70    pub const GLOSSARY_DOCUMENT: &str =
71        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/glossaryDocument";
72    pub const CHART: &str =
73        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart";
74    pub const DIAGRAM_DATA: &str =
75        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/diagramData";
76    pub const DIAGRAM_LAYOUT: &str =
77        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/diagramLayout";
78    pub const DIAGRAM_QUICK_STYLE: &str =
79        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/diagramQuickStyle";
80    pub const DIAGRAM_COLORS: &str =
81        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/diagramColors";
82    pub const DIAGRAM_DRAWING: &str =
83        "http://schemas.microsoft.com/office/2007/relationships/diagramDrawing";
84    pub const PACKAGE: &str =
85        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/package";
86    pub const OLE_OBJECT: &str =
87        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject";
88    pub const CONTROL: &str =
89        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/control";
90    pub const STRICT_OLE_OBJECT: &str =
91        "http://purl.oclc.org/ooxml/officeDocument/relationships/oleObject";
92    pub const STRICT_CONTROL: &str =
93        "http://purl.oclc.org/ooxml/officeDocument/relationships/control";
94    pub const ACTIVEX_CONTROL_BINARY: &str =
95        "http://schemas.microsoft.com/office/2006/relationships/activeXControlBinary";
96    pub const VBA_PROJECT: &str =
97        "http://schemas.microsoft.com/office/2006/relationships/vbaProject";
98    pub const VBA_PROJECT_SIGNATURE: &str =
99        "http://schemas.microsoft.com/office/2006/relationships/vbaProjectSignature";
100    pub const VBA_PROJECT_SIGNATURE_AGILE: &str =
101        "http://schemas.microsoft.com/office/2006/relationships/vbaProjectSignatureAgile";
102
103    // SpreadsheetML relationships.
104    pub const WORKSHEET: &str =
105        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet";
106    pub const SHARED_STRINGS: &str =
107        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings";
108
109    // PresentationML relationships.
110    pub const SLIDE: &str =
111        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide";
112    pub const SLIDE_LAYOUT: &str =
113        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout";
114    pub const SLIDE_MASTER: &str =
115        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster";
116    pub const NOTES_SLIDE: &str =
117        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide";
118    pub const NOTES_MASTER: &str =
119        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster";
120    pub const PRES_PROPS: &str =
121        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/presProps";
122    pub const VIEW_PROPS: &str =
123        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/viewProps";
124    pub const TABLE_STYLES: &str =
125        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/tableStyles";
126    pub const HANDOUT_MASTER: &str =
127        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/handoutMaster";
128    pub const POWERPOINT_COMMENTS: &str =
129        "http://schemas.microsoft.com/office/2018/10/relationships/comments";
130    pub const POWERPOINT_AUTHORS: &str =
131        "http://schemas.microsoft.com/office/2018/10/relationships/authors";
132}
133
134/// A single relationship entry.
135#[derive(Debug, Clone, PartialEq)]
136pub struct Relationship {
137    pub id: String,
138    pub rel_type: String,
139    pub target: String,
140    pub target_mode: Option<String>,
141}
142
143/// A collection of relationships parsed from a `.rels` file.
144#[derive(Debug, Clone, Default)]
145pub struct Relationships {
146    pub items: Vec<Relationship>,
147    next_id: u32,
148    // The bytes read and the items they gave, shared between clones.
149    source: Option<Arc<(Vec<u8>, Vec<Relationship>)>>,
150}
151
152impl Relationships {
153    pub fn new() -> Self {
154        Self {
155            items: Vec::new(),
156            next_id: 1,
157            source: None,
158        }
159    }
160
161    /// Parse from XML bytes.
162    pub fn from_xml(xml: &[u8]) -> Result<Self> {
163        let mut reader = NsReader::from_reader(xml);
164        reader.config_mut().trim_text(true);
165
166        let mut items = Vec::new();
167        let mut ids = HashSet::new();
168        let mut max_id: u32 = 0;
169        let mut buf = Vec::new();
170        let mut depth = 0usize;
171        let mut owned_root = false;
172
173        loop {
174            let decoder = reader.decoder();
175            match reader.read_resolved_event_into(&mut buf) {
176                Ok((namespace, Event::Empty(ref e)))
177                    if owned_root
178                        && depth == 1
179                        && matches!(namespace, ResolveResult::Bound(value) if namespace_uri(value.as_ref(), decoder)? == std::str::from_utf8(RELATIONSHIPS_NAMESPACE).expect("static namespace"))
180                        && e.local_name().as_ref() == b"Relationship" =>
181                {
182                    let relationship = parse_relationship(e, reader.decoder())?;
183                    if !ids.insert(relationship.id.clone()) {
184                        return Err(OpcError::InvalidRelationship);
185                    }
186                    update_max_relationship_id(&relationship.id, &mut max_id);
187                    items.push(relationship);
188                }
189                Ok((namespace, Event::Start(ref e)))
190                    if owned_root
191                        && depth == 1
192                        && matches!(namespace, ResolveResult::Bound(value) if namespace_uri(value.as_ref(), decoder)? == std::str::from_utf8(RELATIONSHIPS_NAMESPACE).expect("static namespace"))
193                        && e.local_name().as_ref() == b"Relationship" =>
194                {
195                    let relationship = parse_relationship(e, reader.decoder())?;
196                    if !ids.insert(relationship.id.clone()) {
197                        return Err(OpcError::InvalidRelationship);
198                    }
199                    update_max_relationship_id(&relationship.id, &mut max_id);
200                    items.push(relationship);
201                    reader.read_to_end_into(e.name(), &mut Vec::new())?;
202                }
203                Ok((namespace, Event::Start(ref start))) => {
204                    if depth == 0 {
205                        owned_root = matches!(namespace, ResolveResult::Bound(value) if namespace_uri(value.as_ref(), decoder)? == std::str::from_utf8(RELATIONSHIPS_NAMESPACE).expect("static namespace"))
206                            && start.local_name().as_ref() == b"Relationships";
207                    }
208                    depth += 1;
209                }
210                Ok((_, Event::End(_))) => {
211                    depth = depth.checked_sub(1).ok_or(OpcError::InvalidRelationship)?
212                }
213                Ok((_, Event::Eof)) => break,
214                Err(e) => return Err(e.into()),
215                _ => {}
216            }
217            buf.clear();
218        }
219
220        if depth != 0 {
221            return Err(OpcError::InvalidRelationship);
222        }
223        Ok(Relationships {
224            source: Some(Arc::new((xml.to_vec(), items.clone()))),
225            items,
226            next_id: next_relationship_number(max_id),
227        })
228    }
229
230    /// Rebinds one imported scope, preserving opaque source around owned records.
231    /// ID changes are explicit, and absent proposed records are removed atomically.
232    pub fn rebind_for_import(
233        &self,
234        items: Vec<Relationship>,
235        ids: &HashMap<String, String>,
236    ) -> Result<Self> {
237        self.validate_ids()?;
238        let mut proposed = Self::new();
239        proposed.items = items;
240        proposed.validate_ids()?;
241        for item in &proposed.items {
242            if item.rel_type.is_empty()
243                || item.target.is_empty()
244                || item.rel_type.chars().any(char::is_control)
245                || item.target.chars().any(char::is_control)
246                || item
247                    .target_mode
248                    .as_deref()
249                    .is_some_and(|mode| !matches!(mode, "External" | "Internal"))
250            {
251                return Err(OpcError::InvalidRelationship);
252            }
253        }
254        let source = match &self.source {
255            Some(source) => source.0.clone(),
256            None => self.to_xml()?,
257        };
258        let parsed = relationship_xml(&source)?;
259        let proposed_by_id = proposed
260            .items
261            .iter()
262            .map(|item| (item.id.as_str(), item))
263            .collect::<HashMap<_, _>>();
264        let mut edits = Vec::new();
265        let mut seen = HashSet::new();
266        let mut old = HashSet::new();
267        for record in &parsed.records {
268            let id = record
269                .attributes
270                .iter()
271                .find(|attribute| attribute.name == b"Id")
272                .ok_or(OpcError::InvalidRelationship)?;
273            if !old.insert(id.value.as_str()) {
274                return Err(OpcError::InvalidRelationship);
275            }
276            let mapped = ids.get(&id.value).map(String::as_str).unwrap_or(&id.value);
277            let Some(item) = proposed_by_id.get(mapped) else {
278                edits.push((record.range.clone(), Vec::new()));
279                continue;
280            };
281            if !seen.insert(item.id.as_str()) {
282                return Err(OpcError::InvalidRelationship);
283            }
284            for (name, value) in [
285                (b"Id".as_slice(), Some(item.id.as_str())),
286                (b"Type", Some(item.rel_type.as_str())),
287                (b"Target", Some(item.target.as_str())),
288                (b"TargetMode", item.target_mode.as_deref()),
289            ] {
290                match (
291                    record
292                        .attributes
293                        .iter()
294                        .find(|attribute| attribute.name == name),
295                    value,
296                ) {
297                    (Some(attribute), Some(value)) if attribute.value != value => edits.push((
298                        attribute.value_range.clone(),
299                        quick_xml::escape::escape(value).into_owned().into_bytes(),
300                    )),
301                    (Some(attribute), None) => {
302                        edits.push((attribute.full_range.clone(), Vec::new()))
303                    }
304                    (None, Some(value)) => {
305                        let at = record.head_end - if record.empty { 2 } else { 1 };
306                        edits.push((
307                            at..at,
308                            format!(
309                                " {}=\"{}\"",
310                                std::str::from_utf8(name)
311                                    .map_err(|_| OpcError::InvalidRelationship)?,
312                                quick_xml::escape::escape(value)
313                            )
314                            .into_bytes(),
315                        ));
316                    }
317                    _ => {}
318                }
319            }
320        }
321        let current_ids = self
322            .items
323            .iter()
324            .map(|item| item.id.as_str())
325            .collect::<HashSet<_>>();
326        if ids
327            .keys()
328            .any(|id| !current_ids.contains(id.as_str()) && !old.contains(id.as_str()))
329        {
330            return Err(OpcError::InvalidRelationship);
331        }
332        // A changed public ID does not identify its historical opaque row.
333        // An explicit retained-ID map proves that ownership. Otherwise refuse
334        // a missing raw owner combined with newly emitted, unowned rows.
335        let unclaimed_raw_owner = old
336            .iter()
337            .any(|id| !current_ids.contains(*id) && !ids.contains_key(*id));
338        if unclaimed_raw_owner
339            && proposed
340                .items
341                .iter()
342                .any(|item| !seen.contains(item.id.as_str()))
343        {
344            return Err(OpcError::InvalidRelationship);
345        }
346        let prefix = parsed
347            .name
348            .rsplit_once(':')
349            .map(|(prefix, _)| format!("{prefix}:"))
350            .unwrap_or_default();
351        let mut added = Vec::new();
352        for item in &proposed.items {
353            if !seen.contains(item.id.as_str()) {
354                let mut start = BytesStart::new(format!("{prefix}Relationship"));
355                start.push_attribute(("Id", item.id.as_str()));
356                start.push_attribute(("Type", item.rel_type.as_str()));
357                start.push_attribute(("Target", item.target.as_str()));
358                if let Some(mode) = &item.target_mode {
359                    start.push_attribute(("TargetMode", mode.as_str()));
360                }
361                let mut writer = Writer::new(Vec::new());
362                writer.write_event(Event::Empty(start))?;
363                added.extend(writer.into_inner());
364            }
365        }
366        if parsed.empty {
367            let replacement = [
368                b">".as_slice(),
369                &added,
370                format!("</{}>", parsed.name).as_bytes(),
371            ]
372            .concat();
373            edits.push((parsed.head_end - 2..parsed.head_end, replacement));
374        } else if !added.is_empty() {
375            edits.push((parsed.close_start..parsed.close_start, added));
376        }
377        let xml = apply_relationship_edits(&source, edits)?;
378        let result = Self::from_xml(&xml)?;
379        if result.items != proposed.items {
380            return Err(OpcError::InvalidRelationship);
381        }
382        Ok(result)
383    }
384
385    /// Merges an imported scope without rebuilding its opaque XML.
386    /// Conflicting root metadata is refused before either scope changes.
387    pub fn merge_for_import(&self, other: &Self) -> Result<(Self, HashMap<String, String>)> {
388        let left_xml = self
389            .rebind_for_import(self.items.clone(), &HashMap::new())?
390            .to_xml()?;
391        let left = relationship_xml(&left_xml)?;
392        let right_xml = other
393            .rebind_for_import(other.items.clone(), &HashMap::new())?
394            .to_xml()?;
395        let right = relationship_xml(&right_xml)?;
396        let mut root_attributes = Vec::new();
397        for attribute in &right.attributes {
398            if let Some(existing) = left.attributes.iter().find(|item| {
399                if attribute.name == b"xmlns" || attribute.name.starts_with(b"xmlns:") {
400                    item.name == attribute.name
401                } else {
402                    item.expanded_name == attribute.expanded_name
403                }
404            }) {
405                if existing.value != attribute.value {
406                    return Err(OpcError::InvalidRelationship);
407                }
408            } else {
409                root_attributes.extend_from_slice(&right_xml[attribute.full_range.clone()]);
410            }
411        }
412        let mut occupied = self.clone();
413        let mut ids = HashMap::new();
414        let mut imported = other.items.clone();
415        for item in &mut imported {
416            let old = item.id.clone();
417            if occupied.get_by_id(&item.id).is_some() {
418                item.id = occupied.allocate_id();
419            }
420            ids.insert(old, item.id.clone());
421            occupied.items.push(item.clone());
422        }
423        let rebound = other.rebind_for_import(imported, &ids)?.to_xml()?;
424        let rebound_root = relationship_xml(&rebound)?;
425        let interior = if rebound_root.empty {
426            Vec::new()
427        } else {
428            let mut inner = rebound[rebound_root.head_end..rebound_root.close_start].to_vec();
429            let mut edits = Vec::new();
430            for child in &rebound_root.children {
431                let mut reader = quick_xml::Reader::from_reader(&rebound[child.clone()]);
432                let start = match reader.read_event()? {
433                    Event::Start(start) | Event::Empty(start) => start,
434                    _ => return Err(OpcError::InvalidRelationship),
435                };
436                let empty = rebound[child.start + reader.buffer_position() as usize - 2] == b'/';
437                let declared = start
438                    .attributes()
439                    .map(|attribute| attribute.map(|attribute| attribute.key.as_ref().to_vec()))
440                    .collect::<std::result::Result<HashSet<_>, _>>()?;
441                let mut closure = Vec::new();
442                for attribute in rebound_root.attributes.iter().filter(|attribute| {
443                    attribute.name == b"xmlns" || attribute.name.starts_with(b"xmlns:")
444                }) {
445                    if !declared.contains(&attribute.name) {
446                        closure.extend_from_slice(&rebound[attribute.full_range.clone()]);
447                    }
448                }
449                if !declared.contains(b"xmlns".as_slice())
450                    && !rebound_root
451                        .attributes
452                        .iter()
453                        .any(|attribute| attribute.name == b"xmlns")
454                {
455                    closure.extend_from_slice(b" xmlns=\"\"");
456                }
457                let at = child.start + reader.buffer_position() as usize
458                    - if empty { 2 } else { 1 }
459                    - rebound_root.head_end;
460                edits.push((at..at, closure));
461            }
462            inner = apply_relationship_edits(&inner, edits)?;
463            inner
464        };
465        let mut edits = Vec::new();
466        if left.empty {
467            let replacement = [
468                root_attributes.as_slice(),
469                b">",
470                &interior,
471                format!("</{}>", left.name).as_bytes(),
472            ]
473            .concat();
474            edits.push((left.head_end - 2..left.head_end, replacement));
475        } else {
476            edits.push((left.head_end - 1..left.head_end - 1, root_attributes));
477            edits.push((left.close_start..left.close_start, interior));
478        }
479        let xml = apply_relationship_edits(&left_xml, edits)?;
480        let result = Self::from_xml(&xml)?;
481        if result.items != occupied.items {
482            return Err(OpcError::InvalidRelationship);
483        }
484        Ok((result, ids))
485    }
486
487    /// Serialize to XML bytes.
488    pub fn to_xml(&self) -> Result<Vec<u8>> {
489        self.validate_ids()?;
490        if let Some(source) = &self.source
491            && source.1 == self.items
492        {
493            return Ok(source.0.clone());
494        }
495        let mut writer = Writer::new_with_indent(Vec::new(), b' ', 2);
496
497        writer.write_event(Event::Decl(BytesDecl::new(
498            "1.0",
499            Some("UTF-8"),
500            Some("yes"),
501        )))?;
502
503        let mut rels_start = BytesStart::new("Relationships");
504        rels_start.push_attribute((
505            "xmlns",
506            "http://schemas.openxmlformats.org/package/2006/relationships",
507        ));
508        writer.write_event(Event::Start(rels_start))?;
509
510        for rel in &self.items {
511            let mut elem = BytesStart::new("Relationship");
512            elem.push_attribute(("Id", rel.id.as_str()));
513            elem.push_attribute(("Type", rel.rel_type.as_str()));
514            elem.push_attribute(("Target", rel.target.as_str()));
515            if let Some(ref mode) = rel.target_mode {
516                elem.push_attribute(("TargetMode", mode.as_str()));
517            }
518            writer.write_event(Event::Empty(elem))?;
519        }
520
521        writer.write_event(Event::End(BytesEnd::new("Relationships")))?;
522
523        Ok(writer.into_inner())
524    }
525
526    /// Compare retained metadata of two qualified records after assigned ids and
527    /// targets have been matched by the caller. Opaque values retain the full
528    /// decoded namespace context, because their QName semantics are unmodelled.
529    pub fn record_metadata_equal_for_import(
530        &self,
531        id: &str,
532        other: &Self,
533        other_id: &str,
534    ) -> Result<bool> {
535        let left = self
536            .rebind_for_import(self.items.clone(), &HashMap::new())?
537            .to_xml()?;
538        let right = other
539            .rebind_for_import(other.items.clone(), &HashMap::new())?
540            .to_xml()?;
541        let a = relationship_xml(&left)?;
542        let b = relationship_xml(&right)?;
543        let record = |root: &RelationshipXmlRoot, id: &str| {
544            root.records.iter().position(|record| {
545                record.attributes.iter().any(|attribute| {
546                    attribute.expanded_name.0.is_none()
547                        && attribute.name == b"Id"
548                        && attribute.value == id
549                })
550            })
551        };
552        let (Some(ai), Some(bi)) = (record(&a, id), record(&b, other_id)) else {
553            return Err(OpcError::InvalidRelationship);
554        };
555        let a_record = &a.records[ai];
556        let b_record = &b.records[bi];
557        let metadata = |record: &RelationshipXmlRecord| {
558            record
559                .attributes
560                .iter()
561                .enumerate()
562                .filter(|(_, attribute)| {
563                    attribute.name != b"xmlns"
564                        && !attribute.name.starts_with(b"xmlns:")
565                        && (attribute.expanded_name.0.is_some()
566                            || !matches!(
567                                attribute.name.as_slice(),
568                                b"Id" | b"Type" | b"Target" | b"TargetMode"
569                            ))
570                })
571                .map(|(index, _)| index)
572                .collect::<Vec<_>>()
573        };
574        let a_attributes = metadata(a_record);
575        let b_attributes = metadata(b_record);
576        let content = |xml: &[u8], record: &RelationshipXmlRecord| -> Vec<u8> {
577            if record.empty {
578                Vec::new()
579            } else {
580                let interior = &xml[record.head_end..record.range.end];
581                interior[..interior.iter().rposition(|byte| *byte == b'<').unwrap_or(0)].to_vec()
582            }
583        };
584        if a_attributes.is_empty()
585            && b_attributes.is_empty()
586            && content(&left, a_record).is_empty()
587            && content(&right, b_record).is_empty()
588        {
589            return Ok(true);
590        }
591        // Namespace closure can add redundant declarations to a copied record.
592        // Compare its complete effective authority, not declaration placement.
593        let namespaces = |root: &RelationshipXmlRoot, record: &RelationshipXmlRecord| {
594            root.attributes
595                .iter()
596                .chain(&record.attributes)
597                .filter(|attribute| {
598                    attribute.name == b"xmlns" || attribute.name.starts_with(b"xmlns:")
599                })
600                .map(|attribute| (attribute.name.clone(), attribute.value.clone()))
601                .collect::<std::collections::BTreeMap<_, _>>()
602        };
603        if namespaces(&a, a_record) != namespaces(&b, b_record)
604            || a_attributes.len() != b_attributes.len()
605        {
606            return Ok(false);
607        }
608        for (left_index, right_index) in a_attributes.iter().zip(b_attributes) {
609            let left_attribute = &a_record.attributes[*left_index];
610            let right_attribute = &b_record.attributes[right_index];
611            if left_attribute.expanded_name != right_attribute.expanded_name
612                || left[left_attribute.full_range.clone()]
613                    != right[right_attribute.full_range.clone()]
614            {
615                return Ok(false);
616            }
617        }
618        Ok(content(&left, a_record) == content(&right, b_record))
619    }
620
621    /// Find a relationship by its ID.
622    pub fn get_by_id(&self, id: &str) -> Option<&Relationship> {
623        self.items.iter().find(|r| r.id == id)
624    }
625
626    /// Find the first relationship matching a given type.
627    pub fn get_by_type(&self, rel_type: &str) -> Option<&Relationship> {
628        self.items.iter().find(|r| r.rel_type == rel_type)
629    }
630
631    /// Find all relationships matching a given type.
632    pub fn get_all_by_type(&self, rel_type: &str) -> Vec<&Relationship> {
633        self.items
634            .iter()
635            .filter(|r| r.rel_type == rel_type)
636            .collect()
637    }
638
639    /// Add a new relationship and return its generated ID.
640    pub fn add(&mut self, rel_type: &str, target: &str) -> String {
641        let id = self.allocate_id();
642        self.items.push(Relationship {
643            id: id.clone(),
644            rel_type: rel_type.to_string(),
645            target: target.to_string(),
646            target_mode: None,
647        });
648        id
649    }
650
651    /// Add an externally-targeted relationship (e.g. a hyperlink URL) and
652    /// return its generated ID.
653    pub fn add_external(&mut self, rel_type: &str, target: &str) -> String {
654        let id = self.allocate_id();
655        self.items.push(Relationship {
656            id: id.clone(),
657            rel_type: rel_type.to_string(),
658            target: target.to_string(),
659            target_mode: Some("External".to_string()),
660        });
661        id
662    }
663
664    /// Add a relationship with a specific ID.
665    ///
666    /// If a relationship with this ID already exists, it is replaced.
667    /// The `next_id` counter is updated to avoid future collisions.
668    pub fn add_with_id(&mut self, id: &str, rel_type: &str, target: &str) {
669        self.items.retain(|r| r.id != id);
670        self.items.push(Relationship {
671            id: id.to_string(),
672            rel_type: rel_type.to_string(),
673            target: target.to_string(),
674            target_mode: None,
675        });
676        if let Some(num) = id.strip_prefix("rId").and_then(|s| s.parse::<u32>().ok())
677            && num >= self.next_id
678        {
679            self.next_id = next_relationship_number(num);
680        }
681    }
682
683    fn allocate_id(&mut self) -> String {
684        let mut candidate = self.next_id;
685        let numeric_space = usize::try_from(u32::MAX).unwrap_or(usize::MAX);
686        let attempts = self.items.len().saturating_add(1).min(numeric_space);
687        for _ in 0..attempts {
688            let id = format!("rId{candidate}");
689            let next = next_relationship_number(candidate);
690            if self.items.iter().all(|relationship| relationship.id != id) {
691                self.next_id = next;
692                return id;
693            }
694            candidate = next;
695        }
696
697        for ordinal in 1u128.. {
698            let id = format!("rIdGenerated{ordinal}");
699            if self.items.iter().all(|relationship| relationship.id != id) {
700                return id;
701            }
702        }
703        unreachable!("the generated relationship id space is unbounded")
704    }
705
706    /// Whether two relationship sets hold the same items, identifier counter
707    /// and source.
708    pub(crate) fn same_as(&self, other: &Relationships) -> bool {
709        self.items == other.items && self.next_id == other.next_id && self.source == other.source
710    }
711
712    /// Whether these relationships still hold the items their source bytes
713    /// were read into, with the identifier counter reading them sets, so
714    /// that writing and reading them back gives them unchanged.
715    pub(crate) fn is_as_read(&self) -> bool {
716        let Some(source) = &self.source else {
717            return false;
718        };
719        let mut maximum = 0;
720        for item in &self.items {
721            update_max_relationship_id(&item.id, &mut maximum);
722        }
723        source.1 == self.items && self.next_id == next_relationship_number(maximum)
724    }
725
726    pub(crate) fn validate_ids(&self) -> Result<()> {
727        let mut ids = HashSet::with_capacity(self.items.len());
728        if self
729            .items
730            .iter()
731            .all(|relationship| ids.insert(relationship.id.as_str()))
732        {
733            Ok(())
734        } else {
735            Err(OpcError::InvalidRelationship)
736        }
737    }
738}
739
740struct RelationshipXmlAttribute {
741    name: Vec<u8>,
742    expanded_name: (Option<String>, Vec<u8>),
743    value: String,
744    value_range: std::ops::Range<usize>,
745    full_range: std::ops::Range<usize>,
746}
747
748struct RelationshipXmlRecord {
749    range: std::ops::Range<usize>,
750    head_end: usize,
751    empty: bool,
752    attributes: Vec<RelationshipXmlAttribute>,
753}
754
755struct RelationshipXmlRoot {
756    name: String,
757    head_end: usize,
758    close_start: usize,
759    empty: bool,
760    attributes: Vec<RelationshipXmlAttribute>,
761    records: Vec<RelationshipXmlRecord>,
762    children: Vec<std::ops::Range<usize>>,
763}
764
765fn namespace_uri(bytes: &[u8], decoder: Decoder) -> Result<String> {
766    // NamespaceResolver retains the declaration's lexical attribute value.
767    // Namespace identity uses XML attribute normalization, including references.
768    let declaration = quick_xml::events::attributes::Attribute {
769        key: quick_xml::name::QName(b"xmlns"),
770        value: std::borrow::Cow::Borrowed(bytes),
771    };
772    Ok(declaration
773        .decoded_and_normalized_value(XmlVersion::Implicit1_0, decoder)?
774        .into_owned())
775}
776
777fn relationship_xml(xml: &[u8]) -> Result<RelationshipXmlRoot> {
778    // quick-xml consumes its initial BOM without counting it in buffer_position.
779    // Parse the remaining slice explicitly and translate every splice offset.
780    let origin = if xml.starts_with(b"\xef\xbb\xbf") {
781        3
782    } else {
783        0
784    };
785    let mut reader = NsReader::from_reader(&xml[origin..]);
786    let mut buffer = Vec::new();
787    let mut depth = 0usize;
788    let mut root = None;
789    let mut record = None;
790    let mut child = None;
791    loop {
792        let begin = origin + reader.buffer_position() as usize;
793        let decoder = reader.decoder();
794        let (namespace, event) = reader.read_resolved_event_into(&mut buffer)?;
795        let qualified = matches!(namespace, ResolveResult::Bound(uri) if namespace_uri(uri.as_ref(), decoder)? == std::str::from_utf8(RELATIONSHIPS_NAMESPACE).expect("static namespace"));
796        let empty = matches!(event, Event::Empty(_));
797        match event {
798            Event::Start(start) | Event::Empty(start) => {
799                let end = origin + reader.buffer_position() as usize;
800                let mut attributes = Vec::new();
801                let mut expanded_attributes = HashSet::new();
802                let raw_start: &[u8] = start.as_ref();
803                for attribute in start.attributes() {
804                    let attribute = attribute?;
805                    let name_offset = (attribute.key.as_ref().as_ptr() as usize)
806                        .checked_sub(raw_start.as_ptr() as usize)
807                        .ok_or(OpcError::InvalidRelationship)?;
808                    let value_offset = (attribute.value.as_ptr() as usize)
809                        .checked_sub(raw_start.as_ptr() as usize)
810                        .ok_or(OpcError::InvalidRelationship)?;
811                    let value_start = begin + 1 + value_offset;
812                    let value_end = value_start + attribute.value.len();
813                    if value_end >= xml.len() {
814                        return Err(OpcError::InvalidRelationship);
815                    }
816                    let mut full_start = begin + 1 + name_offset;
817                    while full_start > begin && xml[full_start - 1].is_ascii_whitespace() {
818                        full_start -= 1;
819                    }
820                    let declaration = attribute.key.as_ref() == b"xmlns"
821                        || attribute.key.as_ref().starts_with(b"xmlns:");
822                    let expanded_name = if declaration {
823                        (
824                            Some("http://www.w3.org/2000/xmlns/".to_owned()),
825                            attribute.key.as_ref().to_vec(),
826                        )
827                    } else {
828                        let (namespace, local) = reader.resolver().resolve_attribute(attribute.key);
829                        let namespace = match namespace {
830                            ResolveResult::Bound(uri) => {
831                                Some(namespace_uri(uri.as_ref(), decoder)?)
832                            }
833                            ResolveResult::Unbound => None,
834                            ResolveResult::Unknown(_) => return Err(OpcError::InvalidRelationship),
835                        };
836                        (namespace, local.as_ref().to_vec())
837                    };
838                    if !expanded_attributes.insert(expanded_name.clone()) {
839                        return Err(OpcError::InvalidRelationship);
840                    }
841                    attributes.push(RelationshipXmlAttribute {
842                        name: attribute.key.as_ref().to_vec(),
843                        expanded_name,
844                        value: attribute
845                            .decoded_and_normalized_value(XmlVersion::Implicit1_0, start.decoder())?
846                            .into_owned(),
847                        value_range: value_start..value_end,
848                        full_range: full_start..value_end + 1,
849                    });
850                }
851                if depth == 0 {
852                    if root.is_some()
853                        || !qualified
854                        || start.local_name().as_ref() != b"Relationships"
855                    {
856                        return Err(OpcError::InvalidRelationship);
857                    }
858                    root = Some(RelationshipXmlRoot {
859                        name: std::str::from_utf8(start.name().as_ref())
860                            .map_err(|_| OpcError::InvalidRelationship)?
861                            .to_owned(),
862                        head_end: end,
863                        close_start: end,
864                        empty,
865                        attributes,
866                        records: Vec::new(),
867                        children: Vec::new(),
868                    });
869                } else if depth == 1 {
870                    child = Some(begin);
871                    if qualified && start.local_name().as_ref() == b"Relationship" {
872                        let current = RelationshipXmlRecord {
873                            range: begin..end,
874                            head_end: end,
875                            empty,
876                            attributes,
877                        };
878                        if empty {
879                            root.as_mut()
880                                .ok_or(OpcError::InvalidRelationship)?
881                                .records
882                                .push(current);
883                        } else {
884                            record = Some(current);
885                        }
886                    }
887                    if empty {
888                        root.as_mut()
889                            .ok_or(OpcError::InvalidRelationship)?
890                            .children
891                            .push(begin..end);
892                        child = None;
893                    }
894                }
895                if !empty {
896                    depth += 1;
897                }
898            }
899            Event::End(_) => {
900                depth = depth.checked_sub(1).ok_or(OpcError::InvalidRelationship)?;
901                let current = root.as_mut().ok_or(OpcError::InvalidRelationship)?;
902                if depth == 1 {
903                    if let Some(mut record) = record.take() {
904                        record.range.end = origin + reader.buffer_position() as usize;
905                        current.records.push(record);
906                    }
907                    if let Some(begin) = child.take() {
908                        current
909                            .children
910                            .push(begin..origin + reader.buffer_position() as usize);
911                    }
912                } else if depth == 0 {
913                    current.close_start = begin;
914                }
915            }
916            Event::Eof => break,
917            _ => {}
918        }
919        buffer.clear();
920    }
921    if depth != 0 || record.is_some() || child.is_some() {
922        return Err(OpcError::InvalidRelationship);
923    }
924    root.ok_or(OpcError::InvalidRelationship)
925}
926
927fn apply_relationship_edits(
928    xml: &[u8],
929    mut edits: Vec<(std::ops::Range<usize>, Vec<u8>)>,
930) -> Result<Vec<u8>> {
931    edits.sort_by_key(|(range, _)| range.start);
932    let mut end = 0;
933    for (range, _) in &edits {
934        if range.start < end || range.start > range.end || range.end > xml.len() {
935            return Err(OpcError::InvalidRelationship);
936        }
937        end = range.end;
938    }
939    let mut result = xml.to_vec();
940    for (range, bytes) in edits.into_iter().rev() {
941        result.splice(range, bytes);
942    }
943    Ok(result)
944}
945
946fn parse_relationship(element: &BytesStart<'_>, decoder: Decoder) -> Result<Relationship> {
947    let mut id = None;
948    let mut rel_type = None;
949    let mut target = None;
950    let mut target_mode = None;
951    for attribute in element.attributes() {
952        let attribute = attribute?;
953        let value = attribute
954            .decoded_and_normalized_value(XmlVersion::Implicit1_0, decoder)?
955            .into_owned();
956        match attribute.key.as_ref() {
957            b"Id" => id = Some(value),
958            b"Type" => rel_type = Some(value),
959            b"Target" => target = Some(value),
960            b"TargetMode" => target_mode = Some(value),
961            _ => {}
962        }
963    }
964    match (id, rel_type, target) {
965        (Some(id), Some(rel_type), Some(target)) => Ok(Relationship {
966            id,
967            rel_type,
968            target,
969            target_mode,
970        }),
971        _ => Err(OpcError::InvalidRelationship),
972    }
973}
974
975fn update_max_relationship_id(id: &str, maximum: &mut u32) {
976    if let Some(number) = id.strip_prefix("rId").and_then(|value| value.parse().ok()) {
977        *maximum = (*maximum).max(number);
978    }
979}
980
981fn next_relationship_number(current: u32) -> u32 {
982    current.checked_add(1).unwrap_or(1).max(1)
983}
984
985#[cfg(test)]
986mod tests {
987    use super::*;
988
989    #[test]
990    fn relationship_and_content_type_constants_are_unique_and_well_formed() {
991        const PACKAGE_PREFIX: &str =
992            "http://schemas.openxmlformats.org/package/2006/relationships/";
993        const OFFICE_PREFIX: &str =
994            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/";
995
996        let package_relationships = [rel_types::CORE_PROPERTIES, rel_types::THUMBNAIL];
997        let office_relationships = [
998            rel_types::DOCUMENT,
999            rel_types::STYLES,
1000            rel_types::NUMBERING,
1001            rel_types::HEADER,
1002            rel_types::FOOTER,
1003            rel_types::IMAGE,
1004            rel_types::SETTINGS,
1005            rel_types::WEB_SETTINGS,
1006            rel_types::FONT_TABLE,
1007            rel_types::FONT,
1008            rel_types::THEME,
1009            rel_types::HYPERLINK,
1010            rel_types::FOOTNOTES,
1011            rel_types::ENDNOTES,
1012            rel_types::GLOSSARY_DOCUMENT,
1013            rel_types::CHART,
1014            rel_types::DIAGRAM_DATA,
1015            rel_types::DIAGRAM_LAYOUT,
1016            rel_types::DIAGRAM_QUICK_STYLE,
1017            rel_types::DIAGRAM_COLORS,
1018            rel_types::PACKAGE,
1019            rel_types::OLE_OBJECT,
1020            rel_types::CONTROL,
1021            rel_types::WORKSHEET,
1022            rel_types::SHARED_STRINGS,
1023            rel_types::EXTENDED_PROPERTIES,
1024            rel_types::CUSTOM_PROPERTIES,
1025            rel_types::SLIDE,
1026            rel_types::SLIDE_LAYOUT,
1027            rel_types::SLIDE_MASTER,
1028            rel_types::NOTES_SLIDE,
1029            rel_types::NOTES_MASTER,
1030            rel_types::PRES_PROPS,
1031            rel_types::VIEW_PROPS,
1032            rel_types::TABLE_STYLES,
1033            rel_types::HANDOUT_MASTER,
1034        ];
1035        let strict_relationships = [rel_types::STRICT_OLE_OBJECT, rel_types::STRICT_CONTROL];
1036        let microsoft_relationships = [
1037            rel_types::ACTIVEX_CONTROL_BINARY,
1038            rel_types::VBA_PROJECT,
1039            rel_types::VBA_PROJECT_SIGNATURE,
1040            rel_types::VBA_PROJECT_SIGNATURE_AGILE,
1041        ];
1042
1043        let mut relationship_values = std::collections::HashSet::new();
1044        for value in package_relationships {
1045            assert!(value.starts_with(PACKAGE_PREFIX));
1046            assert!(!value.chars().any(char::is_whitespace));
1047            assert!(relationship_values.insert(value));
1048        }
1049        for value in office_relationships {
1050            assert!(value.starts_with(OFFICE_PREFIX));
1051            assert!(!value.chars().any(char::is_whitespace));
1052            assert!(relationship_values.insert(value));
1053        }
1054        for value in strict_relationships {
1055            assert!(value.starts_with("http://purl.oclc.org/ooxml/officeDocument/relationships/"));
1056            assert!(!value.chars().any(char::is_whitespace));
1057            assert!(relationship_values.insert(value));
1058        }
1059        for value in microsoft_relationships {
1060            assert!(value.starts_with("http://schemas.microsoft.com/office/2006/relationships/"));
1061            assert!(!value.chars().any(char::is_whitespace));
1062            assert!(relationship_values.insert(value));
1063        }
1064        for value in [
1065            rel_types::POWERPOINT_COMMENTS,
1066            rel_types::POWERPOINT_AUTHORS,
1067            rel_types::DIAGRAM_DRAWING,
1068        ] {
1069            assert!(value.starts_with("http://schemas.microsoft.com/office/"));
1070            assert!(!value.chars().any(char::is_whitespace));
1071            assert!(relationship_values.insert(value));
1072        }
1073
1074        let content_type_values = [
1075            crate::content_types::RELATIONSHIPS,
1076            crate::content_types::XML,
1077            crate::content_types::CORE_PROPERTIES,
1078            crate::content_types::EXTENDED_PROPERTIES,
1079            crate::content_types::CUSTOM_PROPERTIES,
1080            crate::content_types::THEME,
1081            crate::content_types::CHART,
1082            crate::content_types::WORD_GLOSSARY,
1083            crate::content_types::WORD_DOCUMENT,
1084            crate::content_types::WORD_DOCUMENT_MACRO_ENABLED,
1085            crate::content_types::WORD_TEMPLATE,
1086            crate::content_types::WORD_TEMPLATE_MACRO_ENABLED,
1087            crate::content_types::PRESENTATION,
1088            crate::content_types::SLIDESHOW,
1089            crate::content_types::SLIDE,
1090            crate::content_types::SLIDE_LAYOUT,
1091            crate::content_types::SLIDE_MASTER,
1092            crate::content_types::NOTES_SLIDE,
1093            crate::content_types::NOTES_MASTER,
1094            crate::content_types::PRES_PROPS,
1095            crate::content_types::VIEW_PROPS,
1096            crate::content_types::TABLE_STYLES,
1097            crate::content_types::HANDOUT_MASTER,
1098            crate::content_types::POWERPOINT_COMMENTS,
1099            crate::content_types::POWERPOINT_AUTHORS,
1100            crate::content_types::WORKBOOK,
1101            crate::content_types::EMBEDDED_WORKBOOK,
1102            crate::content_types::WORKSHEET,
1103            crate::content_types::SHARED_STRINGS,
1104            crate::content_types::STYLES,
1105        ];
1106
1107        let mut content_types = std::collections::HashSet::new();
1108        for value in content_type_values {
1109            let (kind, subtype) = value.split_once('/').expect("valid MIME type");
1110            assert_eq!(kind, "application");
1111            assert!(!subtype.is_empty());
1112            assert!(!subtype.contains('/'));
1113            assert!(!value.chars().any(char::is_whitespace));
1114            assert!(content_types.insert(value));
1115        }
1116    }
1117
1118    #[test]
1119    fn round_trip_relationships() {
1120        let mut rels = Relationships::new();
1121        rels.add(rel_types::DOCUMENT, "word/document.xml");
1122        rels.add(rel_types::STYLES, "word/styles.xml");
1123
1124        let xml = rels.to_xml().unwrap();
1125        let parsed = Relationships::from_xml(&xml).unwrap();
1126
1127        assert_eq!(parsed.items.len(), 2);
1128        assert_eq!(parsed.items[0].id, "rId1");
1129        assert_eq!(parsed.items[0].target, "word/document.xml");
1130        assert_eq!(parsed.items[1].id, "rId2");
1131    }
1132
1133    #[test]
1134    fn find_by_type() {
1135        let mut rels = Relationships::new();
1136        rels.add(rel_types::DOCUMENT, "word/document.xml");
1137        rels.add(rel_types::STYLES, "word/styles.xml");
1138
1139        let doc = rels.get_by_type(rel_types::DOCUMENT).unwrap();
1140        assert_eq!(doc.target, "word/document.xml");
1141    }
1142
1143    #[test]
1144    fn high_numeric_relationship_ids_roll_over_without_collision() {
1145        let xml = br#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1146<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
1147  <Relationship Id="rId4294967294" Type="type-a" Target="a.xml"/>
1148</Relationships>"#;
1149        let mut relationships = Relationships::from_xml(xml).unwrap();
1150        assert_eq!(relationships.add("type-b", "b.xml"), "rId4294967295");
1151        assert_eq!(relationships.add("type-c", "c.xml"), "rId1");
1152        assert_eq!(
1153            relationships.add_external("type-d", "https://example.com"),
1154            "rId2"
1155        );
1156        let ids = relationships
1157            .items
1158            .iter()
1159            .map(|relationship| relationship.id.as_str())
1160            .collect::<std::collections::HashSet<_>>();
1161        assert_eq!(ids.len(), relationships.items.len());
1162        assert!(!ids.contains("rId0"));
1163    }
1164
1165    #[test]
1166    fn parsed_u32_max_relationship_id_rolls_to_first_free_positive_id() {
1167        let xml = br#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1168<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
1169  <Relationship Id="rId4294967295" Type="type-max" Target="max.xml"/>
1170  <Relationship Id="rId1" Type="type-one" Target="one.xml"/>
1171</Relationships>"#;
1172        let mut relationships = Relationships::from_xml(xml).unwrap();
1173        assert_eq!(relationships.add("type-two", "two.xml"), "rId2");
1174        relationships.add_with_id("rId4294967295", "type-max", "replacement.xml");
1175        assert_eq!(relationships.add("type-three", "three.xml"), "rId3");
1176    }
1177
1178    #[test]
1179    fn aliased_and_expanded_relationship_entries_parse_but_foreign_decoys_do_not() {
1180        let xml = br#"<pr:Relationships xmlns:pr="http://schemas.openxmlformats.org/package/2006/relationships" xmlns:x="urn:foreign"><x:Relationship Id="rId9" Type="urn:wrong" Target="wrong.xml"/><pr:Relationship Id="rId2" Type="urn:first" Target="first.xml"></pr:Relationship><pr:Relationship Id="rId3" Type="urn:second" Target="second.xml"/></pr:Relationships>"#;
1181        let parsed = Relationships::from_xml(xml).expect("canonical relationships parse");
1182        assert_eq!(parsed.items.len(), 2);
1183        assert_eq!(parsed.items[0].id, "rId2");
1184        assert_eq!(parsed.items[1].id, "rId3");
1185    }
1186
1187    #[test]
1188    fn duplicate_relationship_ids_are_rejected_on_parse_and_serialize() {
1189        let xml = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="urn:first" Target="first.xml"/><Relationship Id="rId1" Type="urn:second" Target="second.xml"/></Relationships>"#;
1190        assert!(matches!(
1191            Relationships::from_xml(xml),
1192            Err(OpcError::InvalidRelationship)
1193        ));
1194
1195        let mut relationships = Relationships::new();
1196        relationships.items.push(Relationship {
1197            id: "producer".to_owned(),
1198            rel_type: "urn:first".to_owned(),
1199            target: "first.xml".to_owned(),
1200            target_mode: None,
1201        });
1202        relationships.items.push(Relationship {
1203            id: "producer".to_owned(),
1204            rel_type: "urn:second".to_owned(),
1205            target: "second.xml".to_owned(),
1206            target_mode: None,
1207        });
1208        assert!(matches!(
1209            relationships.to_xml(),
1210            Err(OpcError::InvalidRelationship)
1211        ));
1212    }
1213
1214    #[test]
1215    fn encoded_relationship_values_are_decoded_before_validation_and_escape_once() {
1216        let duplicate = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="urn:first" Target="first.xml"/><Relationship Id="rId&#49;" Type="urn:second" Target="second.xml"/></Relationships>"#;
1217        assert!(matches!(
1218            Relationships::from_xml(duplicate),
1219            Err(OpcError::InvalidRelationship)
1220        ));
1221
1222        let xml = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId&#49;" Type="urn:test?a=1&amp;b=2" Target="folder/a&amp;b.xml"/></Relationships>"#;
1223        let parsed = Relationships::from_xml(xml).unwrap();
1224        assert_eq!(parsed.items[0].id, "rId1");
1225        assert_eq!(parsed.items[0].rel_type, "urn:test?a=1&b=2");
1226        assert_eq!(parsed.items[0].target, "folder/a&b.xml");
1227        let saved = String::from_utf8(parsed.to_xml().unwrap()).unwrap();
1228        assert!(saved.contains("folder/a&amp;b.xml"));
1229        assert!(!saved.contains("&amp;amp;"));
1230        assert_eq!(
1231            Relationships::from_xml(saved.as_bytes()).unwrap().items,
1232            parsed.items
1233        );
1234    }
1235
1236    #[test]
1237    fn unchanged_relationship_parts_serialize_byte_for_byte() {
1238        let xml = br#"<?xml version='1.0' encoding='UTF-8'?>
1239<r:Relationships xmlns:r="http://schemas.openxmlformats.org/package/2006/relationships">
1240 <r:Relationship Target="word/document.xml" Type="urn:document" Id="producer-id"></r:Relationship>
1241</r:Relationships>"#;
1242        let mut relationships = Relationships::from_xml(xml).unwrap();
1243        assert_eq!(relationships.to_xml().unwrap(), xml);
1244
1245        relationships.items[0].target = "word/changed.xml".to_owned();
1246        let changed = relationships.to_xml().unwrap();
1247        assert_ne!(changed, xml);
1248        assert!(
1249            String::from_utf8(changed)
1250                .unwrap()
1251                .contains("word/changed.xml")
1252        );
1253    }
1254
1255    #[test]
1256    fn fx216_relationship_projection_excludes_foreign_capsules() {
1257        let xml = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships" xmlns:z="urn:fx216:opaque" z:root="keep"><Relationship Id="owned" Type="urn:owned" Target="owned.xml" z:marker="record"><z:child/></Relationship><z:capsule><Relationship Id="foreign" Type="urn:foreign" Target="https://foreign.example" TargetMode="External"/></z:capsule></Relationships>"#;
1258        let relationships = Relationships::from_xml(xml).unwrap();
1259        assert_eq!(relationships.items.len(), 1);
1260        assert_eq!(relationships.items[0].id, "owned");
1261        assert_eq!(relationships.to_xml().unwrap(), xml);
1262    }
1263
1264    #[test]
1265    fn fx216_scoped_relationship_rebind_preserves_opaque_source() {
1266        let xml = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships" xmlns:z="urn:fx216:opaque" z:root="keep"><Relationship Id="owned" Type="urn:owned" Target="owned.xml" z:marker="record"><z:child/></Relationship></Relationships>"#;
1267        let relationships = Relationships::from_xml(xml).unwrap();
1268        let mut items = relationships.items.clone();
1269        items[0].target = "copied.xml".into();
1270        let rebound = relationships
1271            .rebind_for_import(items, &HashMap::new())
1272            .unwrap();
1273        let changed = String::from_utf8(rebound.to_xml().unwrap()).unwrap();
1274        assert!(
1275            changed.contains("z:root=\"keep\""),
1276            "import needs a scoped preservation path"
1277        );
1278        assert!(changed.contains("z:marker=\"record\"") && changed.contains("<z:child/>"));
1279    }
1280
1281    #[test]
1282    fn fx216_relationship_bom_rebind_and_either_side_merge_keep_original_coordinates() {
1283        for declaration in ["", "<?xml version='1.0'?>"] {
1284            let raw = format!(
1285                "{declaration}<Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships' xmlns:z='urn:bom' z:root='keep'><Relationship Id='rId1' Type='urn:owned' Target='old.xml' z:record='keep'><z:child/></Relationship><!--tail--></Relationships>"
1286            );
1287            let xml = [b"\xef\xbb\xbf".as_slice(), raw.as_bytes()].concat();
1288            let original = Relationships::from_xml(&xml).unwrap();
1289            assert_eq!(original.items.len(), 1);
1290            assert_eq!(original.to_xml().unwrap(), xml);
1291            let mut items = original.items.clone();
1292            items[0].target = "new.xml".into();
1293            let changed = original.rebind_for_import(items, &HashMap::new()).unwrap();
1294            assert_eq!(
1295                changed.to_xml().unwrap(),
1296                [
1297                    b"\xef\xbb\xbf".as_slice(),
1298                    raw.replace("old.xml", "new.xml").as_bytes()
1299                ]
1300                .concat()
1301            );
1302            let plain = Relationships::from_xml(br#"<Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships'><Relationship Id='plain' Type='urn:plain' Target='plain.xml'/></Relationships>"#).unwrap();
1303            let (left_bom, _) = original.merge_for_import(&plain).unwrap();
1304            let left_bytes = left_bom.to_xml().unwrap();
1305            assert!(left_bytes.starts_with(b"\xef\xbb\xbf"));
1306            assert_eq!(left_bom.items.len(), 2);
1307            let (right_bom, _) = plain.merge_for_import(&original).unwrap();
1308            let right_bytes = right_bom.to_xml().unwrap();
1309            assert!(!right_bytes.starts_with(b"\xef\xbb\xbf"));
1310            assert_eq!(right_bom.items.len(), 2);
1311            for bytes in [&left_bytes, &right_bytes] {
1312                let text = std::str::from_utf8(bytes).unwrap();
1313                assert!(
1314                    text.contains("z:root='keep'")
1315                        && text.contains("z:record='keep'")
1316                        && text.contains("<z:child/>")
1317                        && text.contains("<!--tail-->")
1318                );
1319            }
1320            assert_eq!(original.to_xml().unwrap(), xml);
1321        }
1322    }
1323
1324    #[test]
1325    fn fx216_relationship_encoded_namespace_owns_root_and_direct_records() {
1326        for xml in [
1327            br#"<q:Relationships xmlns:q='http://schemas.openxmlformats.org/package/2006/relationship&#115;'><q:Relationship Id='owned' Type='urn:owned' Target='old.xml'/></q:Relationships>"#.as_slice(),
1328            br#"<Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships' xmlns:q='http://schemas.openxmlformats.org/package/2006/relationship&#x73;'><q:Relationship Id='owned' Type='urn:owned' Target='old.xml'/></Relationships>"#.as_slice(),
1329        ] {
1330            let relationships = Relationships::from_xml(xml).unwrap();
1331            assert_eq!(relationships.items.len(), 1);
1332            assert_eq!(relationships.to_xml().unwrap(), xml);
1333            let mut items = relationships.items.clone();
1334            items[0].target = "copied.xml".into();
1335            let rebound = relationships.rebind_for_import(items, &HashMap::new()).unwrap();
1336            assert_eq!(rebound.items[0].target, "copied.xml");
1337            assert!(std::str::from_utf8(&rebound.to_xml().unwrap()).unwrap().contains("relationship&#"));
1338            assert_eq!(relationships.to_xml().unwrap(), xml);
1339        }
1340    }
1341
1342    #[test]
1343    fn fx216_relationship_entity_equivalent_namespace_aliases_are_one_identity() {
1344        let left = Relationships::from_xml(br#"<Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships' xmlns:z='urn:metadata' z:mark='left'/>"#).unwrap();
1345        let conflicting = Relationships::from_xml(br#"<Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships' xmlns:y='urn:met&#97;data' y:mark='right'/>"#).unwrap();
1346        let before = left.to_xml().unwrap();
1347        assert!(left.merge_for_import(&conflicting).is_err());
1348        let equal = Relationships::from_xml(br#"<Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships' xmlns:y='urn:met&#97;data' y:mark='left'><y:opaque/></Relationships>"#).unwrap();
1349        let (merged, _) = left.merge_for_import(&equal).unwrap();
1350        let raw = merged.to_xml().unwrap();
1351        let mut reader = quick_xml::Reader::from_reader(raw.as_slice());
1352        let start = match reader.read_event().unwrap() {
1353            Event::Start(start) => start,
1354            _ => panic!("root"),
1355        };
1356        assert_eq!(
1357            start
1358                .attributes()
1359                .map(|attribute| attribute.unwrap())
1360                .filter(|attribute| attribute.key.local_name().as_ref() == b"mark")
1361                .count(),
1362            1
1363        );
1364        let duplicate = Relationships::from_xml(br#"<Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships' xmlns:z='urn:metadata' xmlns:y='urn:met&#97;data' z:mark='left' y:mark='left'/>"#).unwrap();
1365        assert!(
1366            duplicate
1367                .rebind_for_import(Vec::new(), &HashMap::new())
1368                .is_err()
1369        );
1370        let different = Relationships::from_xml(br#"<Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships' xmlns:y='urn:different' y:mark='right'/>"#).unwrap();
1371        assert!(left.merge_for_import(&different).is_ok());
1372        assert_eq!(left.to_xml().unwrap(), before);
1373    }
1374
1375    #[test]
1376    fn fx216_relationship_root_alias_conflict_refuses_and_equal_alias_is_single() {
1377        let left = Relationships::from_xml(br#"<Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships' xmlns:z='urn:metadata' z:mark='left'/>"#).unwrap();
1378        let conflicting = Relationships::from_xml(br#"<Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships' xmlns:y='urn:metadata' y:mark='right'/>"#).unwrap();
1379        let before = left.to_xml().unwrap();
1380        assert!(left.merge_for_import(&conflicting).is_err());
1381        let equal = Relationships::from_xml(br#"<Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships' xmlns:y='urn:metadata' y:mark='left'><y:opaque/></Relationships>"#).unwrap();
1382        let (merged, _) = left.merge_for_import(&equal).unwrap();
1383        let xml = merged.to_xml().unwrap();
1384        let mut reader = NsReader::from_reader(xml.as_slice());
1385        let mut buffer = Vec::new();
1386        let (_, event) = reader.read_resolved_event_into(&mut buffer).unwrap();
1387        let root = match event {
1388            Event::Start(root) => root,
1389            _ => panic!("merged root"),
1390        };
1391        let marks = root.attributes().map(|attribute| {
1392            let attribute = attribute.unwrap();
1393            let (namespace, local) = reader.resolver().resolve_attribute(attribute.key);
1394            usize::from(matches!(namespace, ResolveResult::Bound(uri) if uri.as_ref() == b"urn:metadata") && local.as_ref() == b"mark")
1395        }).sum::<usize>();
1396        assert_eq!(marks, 1);
1397        assert!(std::str::from_utf8(&xml).unwrap().contains("<y:opaque"));
1398        assert_eq!(left.to_xml().unwrap(), before);
1399    }
1400
1401    #[test]
1402    fn fx216_relationship_merge_keeps_both_scopes_and_rolls_back_root_conflicts() {
1403        let left = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships" xmlns:z="urn:opaque" z:left='keep'><Relationship Id='rId1' Type='urn:a' Target='a'/><z:tail/></Relationships>"#;
1404        let right = br#"<q:Relationships xmlns:q="http://schemas.openxmlformats.org/package/2006/relationships" xmlns:z="urn:opaque" z:right='keep'><!--source--><q:Relationship Id='rId1' Type='urn:b' Target='https://b' TargetMode='External' z:record='keep'><z:child/></q:Relationship><capsule><q:Relationship Id='ghost' Type='urn:foreign' Target='unknown'/></capsule></q:Relationships>"#;
1405        let original = Relationships::from_xml(left).unwrap();
1406        let source = Relationships::from_xml(right).unwrap();
1407        let (merged, ids) = original.merge_for_import(&source).unwrap();
1408        assert_ne!(ids["rId1"], "rId1");
1409        assert_eq!(merged.items.len(), 2);
1410        assert_eq!(merged.items[1].target_mode.as_deref(), Some("External"));
1411        let raw = String::from_utf8(merged.to_xml().unwrap()).unwrap();
1412        for retained in [
1413            "z:left='keep'",
1414            "z:right='keep'",
1415            "<!--source-->",
1416            "z:record='keep'",
1417            "<z:child/>",
1418            "Id='ghost'",
1419        ] {
1420            assert!(raw.contains(retained), "{retained}");
1421        }
1422        assert!(raw.contains("xmlns=\"\""));
1423        let conflict = Relationships::from_xml(br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships" xmlns:z="urn:opaque" z:left='unequal'/>"#).unwrap();
1424        assert!(original.merge_for_import(&conflict).is_err());
1425        assert_eq!(original.to_xml().unwrap(), left);
1426        assert_eq!(source.to_xml().unwrap(), right);
1427    }
1428
1429    #[test]
1430    fn fx216_relationship_rebind_removes_adds_and_rolls_back_invalid_schema() {
1431        let xml = br#"<?xml version='1.0'?><q:Relationships xmlns:q="http://schemas.openxmlformats.org/package/2006/relationships" xmlns:z="urn:fx216:opaque" z:root='keep'><q:Relationship Target='https://old.example' z:record='keep' Id='kept' TargetMode='External' Type='urn:owned'><z:child/></q:Relationship><!--between--><q:Relationship Id='removed' Type='urn:owned' Target='removed.xml'/><z:capsule><q:Relationship Id='foreign' Type='urn:metadata' Target='foreign.xml'/></z:capsule><z:tail/></q:Relationships>"#;
1432        let original = Relationships::from_xml(xml).unwrap();
1433        let items = vec![
1434            Relationship {
1435                id: "renamed".into(),
1436                rel_type: "urn:owned".into(),
1437                target: "copied.xml".into(),
1438                target_mode: None,
1439            },
1440            Relationship {
1441                id: "added".into(),
1442                rel_type: "urn:new".into(),
1443                target: "https://new.example/?a=1&b=2".into(),
1444                target_mode: Some("External".into()),
1445            },
1446        ];
1447        let map = HashMap::from([("kept".into(), "renamed".into())]);
1448        let changed = original.rebind_for_import(items.clone(), &map).unwrap();
1449        assert_eq!(changed.items, items);
1450        let raw = String::from_utf8(changed.to_xml().unwrap()).unwrap();
1451        assert!(
1452            raw.contains("z:root='keep'")
1453                && raw.contains("z:record='keep'")
1454                && raw.contains("<z:child/>")
1455                && raw.contains("<!--between-->")
1456                && raw.contains("<z:tail/>")
1457        );
1458        assert!(raw.contains("<z:capsule><q:Relationship Id='foreign' Type='urn:metadata' Target='foreign.xml'/></z:capsule>"));
1459        assert!(!raw.contains("Id='removed'"));
1460        assert!(!raw.contains("TargetMode='External'"));
1461        assert_eq!(changed.items[1].target, "https://new.example/?a=1&b=2");
1462        assert_eq!(original.to_xml().unwrap(), xml);
1463        assert!(
1464            original
1465                .rebind_for_import(vec![items[0].clone(), items[0].clone()], &map)
1466                .is_err()
1467        );
1468        let mut invalid = items.clone();
1469        invalid[0].target.clear();
1470        assert!(original.rebind_for_import(invalid, &map).is_err());
1471        let mut invalid = items;
1472        invalid[0].target_mode = Some("invalid".into());
1473        assert!(original.rebind_for_import(invalid, &map).is_err());
1474        assert!(
1475            original
1476                .rebind_for_import(
1477                    Vec::new(),
1478                    &HashMap::from([("foreign".into(), "guessed".into())])
1479                )
1480                .is_err()
1481        );
1482        assert_eq!(original.to_xml().unwrap(), xml);
1483    }
1484
1485    #[test]
1486    fn fx216_relationship_rebind_maps_rows_added_after_parsing() {
1487        let xml = br#"<q:Relationships xmlns:q="http://schemas.openxmlformats.org/package/2006/relationships" xmlns:z="urn:opaque" z:root='keep'><q:Relationship Id='kept' Type='urn:owned' Target='old.xml' z:record='keep'><!--inside--></q:Relationship><!--between--><z:tail/></q:Relationships>"#;
1488        let mut original = Relationships::from_xml(xml).unwrap();
1489        original.add_with_id("draft", "urn:new", "new.xml");
1490        let before = original.to_xml().unwrap();
1491        let mut items = original.items.clone();
1492        items.last_mut().unwrap().id = "imported".into();
1493        let map = HashMap::from([("draft".into(), "imported".into())]);
1494        let changed = original.rebind_for_import(items.clone(), &map).unwrap();
1495        assert_eq!(changed.items, items);
1496        let saved = changed.to_xml().unwrap();
1497        let written = std::str::from_utf8(&saved).unwrap();
1498        for opaque in [
1499            "z:root='keep'",
1500            "z:record='keep'",
1501            "<!--inside-->",
1502            "<!--between-->",
1503            "<z:tail/>",
1504        ] {
1505            assert!(written.contains(opaque), "lost {opaque}");
1506        }
1507        assert_eq!(Relationships::from_xml(&saved).unwrap().items, items);
1508        assert!(
1509            original
1510                .rebind_for_import(
1511                    items.clone(),
1512                    &HashMap::from([("unknown".into(), "imported".into())])
1513                )
1514                .is_err()
1515        );
1516        let mut duplicate = original.clone();
1517        duplicate.items.push(duplicate.items[0].clone());
1518        assert!(duplicate.rebind_for_import(items, &map).is_err());
1519        assert_eq!(original.to_xml().unwrap(), before);
1520    }
1521
1522    #[test]
1523    fn fx216_relationship_rebind_requires_explicit_renamed_raw_owner() {
1524        let xml = br#"<q:Relationships xmlns:q="http://schemas.openxmlformats.org/package/2006/relationships" xmlns:z="urn:opaque" z:root='keep'><q:Relationship Id='kept' Type='urn:owned' Target='old.xml' z:record='keep'><z:child keep='&#65;'/><!--inside--></q:Relationship><!--between--><z:tail/></q:Relationships>"#;
1525        let mut original = Relationships::from_xml(xml).unwrap();
1526        original.items[0].id = "draft".into();
1527        let before_items = original.items.clone();
1528        let before_source = original.source.clone();
1529        let before = original.to_xml().unwrap();
1530        let mut items = original.items.clone();
1531        items[0].id = "imported".into();
1532        items[0].target = "new.xml".into();
1533
1534        // Neither the new public ID nor matching position/target proves which
1535        // retained XML row owns the opaque payload.
1536        let current_map = HashMap::from([("draft".into(), "imported".into())]);
1537        assert!(matches!(
1538            original.rebind_for_import(items.clone(), &current_map),
1539            Err(crate::OpcError::InvalidRelationship)
1540        ));
1541        assert!(matches!(
1542            original.rebind_for_import(original.items.clone(), &HashMap::new()),
1543            Err(crate::OpcError::InvalidRelationship)
1544        ));
1545        assert_eq!(original.items, before_items);
1546        assert_eq!(original.source, before_source);
1547        assert_eq!(original.to_xml().unwrap(), before);
1548
1549        // Naming the retained source ID is a complete ownership route even
1550        // though the caller has already changed the public item ID.
1551        let retained_map = HashMap::from([("kept".into(), "imported".into())]);
1552        let changed = original
1553            .rebind_for_import(items.clone(), &retained_map)
1554            .unwrap();
1555        assert_eq!(changed.items, items);
1556        let saved = changed.to_xml().unwrap();
1557        let written = std::str::from_utf8(&saved).unwrap();
1558        for opaque in [
1559            "z:root='keep'",
1560            "z:record='keep'",
1561            "<z:child keep='&#65;'/>",
1562            "<!--inside-->",
1563            "<!--between-->",
1564            "<z:tail/>",
1565        ] {
1566            assert!(written.contains(opaque), "lost {opaque}");
1567        }
1568        assert!(written.contains("Id='imported'"));
1569        assert!(written.contains("Target='new.xml'"));
1570        assert_eq!(Relationships::from_xml(&saved).unwrap().items, items);
1571        assert_eq!(original.items, before_items);
1572        assert_eq!(original.source, before_source);
1573        assert_eq!(original.to_xml().unwrap(), before);
1574    }
1575
1576    #[test]
1577    fn fx216_relationship_rebind_distinguishes_removal_from_ambiguous_addition() {
1578        let xml = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships" xmlns:z="urn:opaque" z:root='keep'><Relationship Id='kept' Type='urn:owned' Target='old.xml' z:record='keep'><z:child/></Relationship><!--between--><z:tail/></Relationships>"#;
1579        let parsed = Relationships::from_xml(xml).unwrap();
1580        let mut ambiguous = parsed.clone();
1581        ambiguous.items.clear();
1582        ambiguous.add_with_id("draft", "urn:new", "new.xml");
1583        let before_items = ambiguous.items.clone();
1584        let before_source = ambiguous.source.clone();
1585        let before = ambiguous.to_xml().unwrap();
1586        let mut items = ambiguous.items.clone();
1587        items[0].id = "imported".into();
1588        let map = HashMap::from([("draft".into(), "imported".into())]);
1589        assert!(matches!(
1590            ambiguous.rebind_for_import(items.clone(), &map),
1591            Err(crate::OpcError::InvalidRelationship)
1592        ));
1593        assert_eq!(ambiguous.items, before_items);
1594        assert_eq!(ambiguous.source, before_source);
1595        assert_eq!(ambiguous.to_xml().unwrap(), before);
1596
1597        // A removal is still supported. Staging it first makes a subsequent
1598        // new row unambiguous without inventing a raw-owner correspondence.
1599        let mut removed = parsed
1600            .rebind_for_import(Vec::new(), &HashMap::new())
1601            .unwrap();
1602        let raw = String::from_utf8(removed.to_xml().unwrap()).unwrap();
1603        assert!(!raw.contains("z:record") && !raw.contains("<z:child/>"));
1604        assert!(
1605            raw.contains("z:root='keep'")
1606                && raw.contains("<!--between-->")
1607                && raw.contains("<z:tail/>")
1608        );
1609        removed.add_with_id("draft", "urn:new", "new.xml");
1610        let changed = removed.rebind_for_import(items.clone(), &map).unwrap();
1611        assert_eq!(changed.items, items);
1612        let raw = String::from_utf8(changed.to_xml().unwrap()).unwrap();
1613        assert!(raw.contains("z:root='keep'") && raw.contains("<z:tail/>"));
1614        assert!(
1615            changed
1616                .rebind_for_import(
1617                    changed.items.clone(),
1618                    &HashMap::from([("unknown".into(), "imported".into())]),
1619                )
1620                .is_err()
1621        );
1622        assert_eq!(parsed.to_xml().unwrap(), xml);
1623    }
1624
1625    #[test]
1626    fn fx216_import_record_metadata_ignores_redundant_closure_declarations() {
1627        let uri = "http://schemas.openxmlformats.org/package/2006/relationships";
1628        let source = Relationships::from_xml(format!(r#"<Relationships xmlns="{uri}" xmlns:z="urn:style-record"><Relationship Id="picture" Type="image" Target="media/image.png" z:keep='&#69;'><z:payload value="z"/></Relationship></Relationships>"#).as_bytes()).unwrap();
1629        let destination =
1630            Relationships::from_xml(format!(r#"<Relationships xmlns="{uri}"/>"#).as_bytes())
1631                .unwrap();
1632        let (merged, ids) = destination.merge_for_import(&source).unwrap();
1633        assert!(
1634            source
1635                .record_metadata_equal_for_import("picture", &merged, &ids["picture"])
1636                .unwrap()
1637        );
1638        let changed = Relationships::from_xml(format!(r#"<Relationships xmlns="{uri}" xmlns:z="urn:style-record"><Relationship Id="picture" Type="image" Target="media/image.png" z:keep='&#69;' xmlns:z="urn:foreign"><z:payload value="z"/></Relationship></Relationships>"#).as_bytes()).unwrap();
1639        assert!(
1640            !source
1641                .record_metadata_equal_for_import("picture", &changed, "picture")
1642                .unwrap()
1643        );
1644        let encoded = Relationships::from_xml(format!(r#"<Relationships xmlns="{uri}"><Relationship Id="picture" Type="image" Target="media/image.png" z:keep='&#69;' xmlns:z="urn:style-rec&#111;rd"><z:payload value="z"/></Relationship></Relationships>"#).as_bytes()).unwrap();
1645        assert!(
1646            source
1647                .record_metadata_equal_for_import("picture", &encoded, "picture")
1648                .unwrap()
1649        );
1650    }
1651
1652    #[test]
1653    fn fx216_import_record_metadata_checks_opaque_namespace_authority() {
1654        let uri = "http://schemas.openxmlformats.org/package/2006/relationships";
1655        let fixture = |binding: &str, id: &str| {
1656            format!(
1657                r#"<Relationships xmlns="{uri}" xmlns:z="{binding}"><Relationship Id="{id}" Type="font" Target="font.bin" z:marker='&#65;'><z:payload prefix="z"/></Relationship><z:capsule><Relationship Id="ghost" Type="font" Target="hidden"/></z:capsule></Relationships>"#
1658            )
1659        };
1660        let source = Relationships::from_xml(fixture("urn:metadata", "source").as_bytes()).unwrap();
1661        let equivalent =
1662            Relationships::from_xml(fixture("urn:met&#97;data", "destination").as_bytes()).unwrap();
1663        let foreign =
1664            Relationships::from_xml(fixture("urn:foreign", "destination").as_bytes()).unwrap();
1665        assert!(
1666            source
1667                .record_metadata_equal_for_import("source", &equivalent, "destination")
1668                .unwrap()
1669        );
1670        assert!(
1671            !source
1672                .record_metadata_equal_for_import("source", &foreign, "destination")
1673                .unwrap()
1674        );
1675        assert!(
1676            source
1677                .record_metadata_equal_for_import("ghost", &source, "source")
1678                .is_err()
1679        );
1680        let plain = Relationships::from_xml(format!(r#"<x:Relationships xmlns:x="{uri}"><x:Relationship Id="other" Type="font" Target="other.bin"/></x:Relationships>"#).as_bytes()).unwrap();
1681        let other = Relationships::from_xml(format!(r#"<Relationships xmlns="{uri}"><Relationship Id="source" Type="font" Target="font.bin"></Relationship></Relationships>"#).as_bytes()).unwrap();
1682        assert!(
1683            plain
1684                .record_metadata_equal_for_import("other", &other, "source")
1685                .unwrap()
1686        );
1687    }
1688}