f-office-opc 0.3.0

Open Packaging Conventions container: ZIP package and relationships, with input limits.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
//! Open Packaging Conventions container (ECMA-376 Part 2).
//!
//! This crate reads the ZIP package that holds every Office Open XML file, with its
//! relationships. It enforces input limits on the size of each part, the total size, the
//! compression ratio and the number of entries. It also writes a package with changed or added
//! parts ([`write_package`]), in which every byte that no change touches stays as it was.

use std::collections::BTreeMap;
use std::collections::btree_map::Entry;
use std::fmt;
use std::io::Read;
#[cfg(not(target_arch = "wasm32"))]
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};

use f_office_xml::Document;

mod error;
mod source;
#[cfg(any(test, feature = "testing"))]
pub mod testing;
mod write;

pub use error::{Error, Limit, ZipFault};
/// The limits of each XML part, which [`Limits::xml`] holds.
pub use f_office_xml::Limits as XmlLimits;
pub use source::RandomAccessRead;
pub use write::{LayoutFault, PartChange, WriteError, write_package};

use source::{Backing, BackingReader};

const RELATIONSHIPS_NS: &str = "http://schemas.openxmlformats.org/package/2006/relationships";

/// Limits that protect the reader against hostile packages: those of the ZIP file, and those of
/// each XML part, which the package keeps for the readers of its parts ([`Package::limits`]).
/// Start from [`Limits::default`] and set the limits that differ, so that a new limit breaks no
/// caller.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Limits {
    /// The largest uncompressed part, in bytes.
    pub max_part_size: u64,
    /// The largest uncompressed total of all parts, in bytes.
    pub max_total_size: u64,
    /// The most entries in the ZIP file.
    pub max_entries: usize,
    /// The highest ratio of uncompressed to compressed size for parts above 1 MiB.
    pub max_ratio: u64,
    /// The limits of each XML part: the package's relationships parts and every part that a
    /// reader of the package parses.
    pub xml: XmlLimits,
    /// The largest package that [`write_package`] writes, in bytes.
    pub max_written_size: u64,
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            max_part_size: 256 << 20,
            max_total_size: 1 << 30,
            max_entries: 20_000,
            max_ratio: 1_000,
            xml: XmlLimits::default(),
            max_written_size: 1 << 30,
        }
    }
}

impl Limits {
    /// Limits tuned for memory-constrained devices such as phones and browser tabs
    /// (32 MiB max part, 128 MiB max total, 500k XML nodes, 64 MiB max written package).
    #[must_use]
    pub const fn mobile() -> Self {
        Self {
            max_part_size: 32 << 20,
            max_total_size: 128 << 20,
            max_entries: 10_000,
            max_ratio: 1_000,
            xml: XmlLimits::mobile(),
            max_written_size: 64 << 20,
        }
    }
}

/// One relationship from a source part to a target.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Relationship {
    /// The relationship ID, such as `rId1`.
    pub id: String,
    /// The relationship type URI.
    pub rel_type: String,
    /// The target part name, resolved against the source part, or the URI of an external target.
    pub target: String,
    /// Whether the target is outside the package.
    pub external: bool,
}

/// What one relationships part holds, as [`Package::relationships`] reads it.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct RelationshipsPart {
    /// The part's name as the package writes it, without a leading `/`, such as
    /// `word/_rels/document.xml.rels`; empty when the package has no such part.
    pub name: String,
    /// The relationships, in the order of the part.
    pub relationships: Vec<Relationship>,
    /// The namespace prefixes that the part uses without a declaration, each once
    /// ([`Document::undeclared_prefixes`]): a relationship written with one of them is not
    /// among [`RelationshipsPart::relationships`].
    pub undeclared_prefixes: Vec<String>,
}

/// What a source without a relationships part has.
static NO_RELATIONSHIPS: RelationshipsPart = RelationshipsPart {
    name: String::new(),
    relationships: Vec::new(),
    undeclared_prefixes: Vec::new(),
};

impl Relationship {
    /// The first of `relationships` with the ID `id` whose target is a part of the package.
    #[must_use]
    pub fn by_id<'r>(relationships: &'r [Self], id: &str) -> Option<&'r Self> {
        relationships
            .iter()
            .find(|rel| rel.id == id && !rel.external)
    }

    /// The first of `relationships` whose type ends with `suffix`, such as `/styles`, and whose
    /// target is a part of the package. The suffix matches the type in the strict and in the
    /// transitional namespace.
    #[must_use]
    pub fn by_type<'r>(relationships: &'r [Self], suffix: &str) -> Option<&'r Self> {
        relationships
            .iter()
            .find(|rel| rel.rel_type.ends_with(suffix) && !rel.external)
    }
}

/// An indexed ZIP package whose parts decompress lazily on demand.
///
/// Opening a package reads only the ZIP central directory and validates [`Limits`] without
/// inflating any part bytes. Unused parts (such as thumbnails, embedded workbooks, or unvisited
/// media) consume no memory.
#[derive(Clone, Default)]
pub struct Package {
    /// Indexed ZIP archive kept open for O(1) lazy entry decompression.
    archive: Arc<Mutex<Option<zip::ZipArchive<BackingReader>>>>,
    /// The parts by their keys ([`key`]).
    parts: BTreeMap<String, Part>,
    /// The relationships that each relationships part holds, by the part's key, read on their
    /// first use and kept.
    relationships: BTreeMap<String, OnceLock<Result<RelationshipsPart, Error>>>,
    /// The names of the entries left out because an earlier entry has an equivalent name.
    equivalent: Vec<String>,
    /// Cumulative decompressed bytes across distinct parts inflated so far.
    inflated_total: Arc<AtomicU64>,
    /// The limits that the package was opened with.
    limits: Limits,
}

impl fmt::Debug for Package {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Package")
            .field("parts", &self.parts.len())
            .field("limits", &self.limits)
            .finish_non_exhaustive()
    }
}

/// One indexed part: its normalized name, ZIP central-directory metadata, and lazy byte cache.
struct Part {
    name: String,
    zip_index: usize,
    compressed_size: u64,
    uncompressed_size: u64,
    counted: AtomicBool,
    data: OnceLock<Result<Vec<u8>, Error>>,
}

impl Clone for Part {
    fn clone(&self) -> Self {
        Self {
            name: self.name.clone(),
            zip_index: self.zip_index,
            compressed_size: self.compressed_size,
            uncompressed_size: self.uncompressed_size,
            counted: AtomicBool::new(self.counted.load(Ordering::Relaxed)),
            data: self.data.clone(),
        }
    }
}

impl Package {
    /// Indexes a package from in-memory bytes without eagerly decompressing its parts.
    ///
    /// # Errors
    ///
    /// Returns an error when the ZIP central directory is unreadable or breaks a limit.
    pub fn open(bytes: &[u8], limits: &Limits) -> Result<Self, Error> {
        Self::open_shared(Arc::<[u8]>::from(bytes), limits)
    }

    /// Indexes a package from a shared byte buffer without copying or eagerly decompressing it.
    ///
    /// # Errors
    ///
    /// Returns an error when the ZIP central directory is unreadable or breaks a limit.
    pub fn open_shared(bytes: Arc<[u8]>, limits: &Limits) -> Result<Self, Error> {
        Self::open_backing(Arc::new(Backing::Memory(bytes)), limits)
    }

    /// Indexes a package from a caller-provided random-access byte source (such as browser
    /// `File.slice()` or OPFS `FileSystemSyncAccessHandle`) without copying the archive into RAM.
    ///
    /// # Errors
    ///
    /// Returns an error when the ZIP central directory is unreadable or breaks a limit.
    pub fn open_source(source: Arc<dyn RandomAccessRead>, limits: &Limits) -> Result<Self, Error> {
        Self::open_backing(Arc::new(Backing::Custom(source)), limits)
    }

    /// Indexes a package directly from a native file on disk without loading the file into RAM.
    ///
    /// Parts are read and decompressed lazily via random-access file I/O when requested.
    ///
    /// # Errors
    ///
    /// Returns an error when the file cannot be opened, its ZIP central directory is unreadable,
    /// or it breaks a limit.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn open_file(path: &Path, limits: &Limits) -> Result<Self, Error> {
        let file = std::fs::File::open(path).map_err(|_| Error::Zip(ZipFault::Archive))?;
        let len = file
            .metadata()
            .map_err(|_| Error::Zip(ZipFault::Archive))?
            .len();
        Self::open_backing(
            Arc::new(Backing::File {
                file: Mutex::new(file),
                len,
            }),
            limits,
        )
    }

    /// Indexes the ZIP central directory of `backing` without inflating any entries.
    fn open_backing(backing: Arc<Backing>, limits: &Limits) -> Result<Self, Error> {
        let mut archive = zip::ZipArchive::new(BackingReader::new(backing))
            .map_err(|_| Error::Zip(ZipFault::Archive))?;
        if archive.len() > limits.max_entries {
            return Err(Error::Limit(Limit::Entries));
        }
        let mut parts = BTreeMap::new();
        let mut equivalent = Vec::new();
        let mut declared_total = 0_u64;
        for index in 0..archive.len() {
            let file = archive
                .by_index_raw(index)
                .map_err(|_| Error::Zip(ZipFault::Entry))?;
            if file.is_dir() {
                continue;
            }
            let uncompressed_size = file.size();
            let compressed_size = file.compressed_size();
            check_entry(uncompressed_size, compressed_size, limits)?;
            declared_total = declared_total.saturating_add(uncompressed_size);
            if declared_total > limits.max_total_size {
                return Err(Error::Limit(Limit::TotalSize));
            }
            let name = normalize(&file.name().map_err(|_| Error::Zip(ZipFault::Name))?);
            match parts.entry(key(&name)) {
                Entry::Occupied(_) => equivalent.push(name),
                Entry::Vacant(slot) => {
                    slot.insert(Part {
                        name,
                        zip_index: index,
                        compressed_size,
                        uncompressed_size,
                        counted: AtomicBool::new(false),
                        data: OnceLock::new(),
                    });
                }
            }
        }
        let relationships = parts
            .keys()
            .filter(|name| in_relationships_folder(name))
            .map(|name| (name.clone(), OnceLock::new()))
            .collect();
        Ok(Self {
            archive: Arc::new(Mutex::new(Some(archive))),
            parts,
            relationships,
            equivalent,
            inflated_total: Arc::new(AtomicU64::new(0)),
            limits: *limits,
        })
    }

    /// Returns the limits that the package was opened with, which every reader of its parts
    /// keeps to.
    #[must_use]
    pub const fn limits(&self) -> &Limits {
        &self.limits
    }

    /// Returns the bytes of a part, decompressing and caching it on its first access. The name
    /// may start with `/`, and its ASCII letters may differ in case from the part's name in the
    /// package (ECMA-376 Part 2, 6.2.2.3).
    ///
    /// For large one-shot parts such as embedded media, prefer [`Package::read_part`] so the
    /// inflated bytes are not pinned inside the package cache.
    #[must_use]
    pub fn part(&self, name: &str) -> Option<&[u8]> {
        let part = self.parts.get(&key(name))?;
        part.data
            .get_or_init(|| self.inflate_part(part))
            .as_deref()
            .ok()
    }

    /// Reads and returns the bytes of a part on demand without pinning them in the package cache.
    /// Returns `Ok(None)` when the package holds no such part. If the part was already cached by
    /// [`Package::part`], returns a copy of the cached bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if the entry cannot be decompressed or its actual inflated size breaks
    /// [`Limits`].
    pub fn read_part(&self, name: &str) -> Result<Option<Vec<u8>>, Error> {
        let Some(part) = self.parts.get(&key(name)) else {
            return Ok(None);
        };
        if let Some(cached) = part.data.get() {
            return cached.clone().map(Some);
        }
        self.inflate_part(part).map(Some)
    }

    /// Reads and returns up to `max_bytes` leading bytes of a part on demand without inflating
    /// the remainder of the entry or pinning bytes in the package cache. Returns `Ok(None)` when
    /// the package holds no such part.
    ///
    /// Useful for sniffing image formats and parsing image headers (PNG IHDR, JPEG SOF, GIF, BMP)
    /// without decompressing multi-megabyte media entries during layout.
    ///
    /// # Errors
    ///
    /// Returns an error if the ZIP entry cannot be opened or read.
    pub fn read_part_prefix(&self, name: &str, max_bytes: usize) -> Result<Option<Vec<u8>>, Error> {
        let Some(part) = self.parts.get(&key(name)) else {
            return Ok(None);
        };
        if let Some(cached) = part.data.get() {
            return cached
                .as_ref()
                .map(|bytes| {
                    Some(
                        bytes
                            .get(..bytes.len().min(max_bytes))
                            .unwrap_or(bytes)
                            .to_vec(),
                    )
                })
                .map_err(Clone::clone);
        }
        let limit = u64::try_from(max_bytes)
            .unwrap_or(u64::MAX)
            .min(self.limits.max_part_size);
        let mut guard = self
            .archive
            .lock()
            .map_err(|_| Error::Zip(ZipFault::Read))?;
        let archive = guard.as_mut().ok_or(Error::Zip(ZipFault::Archive))?;
        let mut file = archive
            .by_index(part.zip_index)
            .map_err(|_| Error::Zip(ZipFault::Entry))?;
        let capacity = usize::try_from(part.uncompressed_size.min(limit)).unwrap_or(0);
        let mut data = Vec::with_capacity(capacity);
        (&mut file)
            .take(limit)
            .read_to_end(&mut data)
            .map_err(|_| Error::Zip(ZipFault::Read))?;
        Ok(Some(data))
    }

    /// Returns the declared uncompressed size in bytes of `name` from the ZIP central directory,
    /// without decompressing the part.
    #[must_use]
    pub fn part_size(&self, name: &str) -> Option<u64> {
        self.parts
            .get(&key(name))
            .map(|part| part.uncompressed_size)
    }

    /// Inflates `part` from the backing ZIP archive while enforcing actual size, ratio, and
    /// cumulative total limits.
    fn inflate_part(&self, part: &Part) -> Result<Vec<u8>, Error> {
        let mut guard = self
            .archive
            .lock()
            .map_err(|_| Error::Zip(ZipFault::Read))?;
        let archive = guard.as_mut().ok_or(Error::Zip(ZipFault::Archive))?;
        let mut file = archive
            .by_index(part.zip_index)
            .map_err(|_| Error::Zip(ZipFault::Entry))?;
        let capacity =
            usize::try_from(part.uncompressed_size.min(self.limits.max_part_size)).unwrap_or(0);
        let mut data = Vec::with_capacity(capacity);
        (&mut file)
            .take(self.limits.max_part_size.saturating_add(1))
            .read_to_end(&mut data)
            .map_err(|_| Error::Zip(ZipFault::Read))?;
        drop(file);
        drop(guard);

        let actual_size = data.len() as u64;
        if actual_size > self.limits.max_part_size {
            return Err(Error::Limit(Limit::PartSize));
        }
        check_entry(actual_size, part.compressed_size, &self.limits)?;
        if !part.counted.swap(true, Ordering::Relaxed) {
            let previous = self
                .inflated_total
                .fetch_add(actual_size, Ordering::Relaxed);
            if previous.saturating_add(actual_size) > self.limits.max_total_size {
                return Err(Error::Limit(Limit::TotalSize));
            }
        }
        Ok(data)
    }

    /// Returns the name under which the package holds the part `name`, which [`Package::part`]
    /// finds: as the package writes it, without a leading `/`. `None` when it holds no such
    /// part.
    #[must_use]
    pub fn part_name(&self, name: &str) -> Option<&str> {
        self.parts.get(&key(name)).map(|part| part.name.as_str())
    }

    /// Returns the names of all parts as the package writes them, without a leading `/`.
    pub fn part_names(&self) -> impl Iterator<Item = &str> {
        self.parts.values().map(|part| part.name.as_str())
    }

    /// Returns the names of the entries that the package leaves out, because an earlier entry
    /// of the ZIP file has a name that differs from theirs only in ASCII case. The package
    /// format forbids two such parts (ECMA-376 Part 2, 6.2.2.3); the package keeps the first.
    pub fn equivalent_entries(&self) -> impl Iterator<Item = &str> {
        self.equivalent.iter().map(String::as_str)
    }

    /// Returns the relationships part of a part, or of the package when `source` is empty: none
    /// when the package has no such part. The package reads a relationships part on its first
    /// use and keeps what it read.
    ///
    /// # Errors
    ///
    /// Returns an error when the relationships part cannot be read or is not valid XML.
    pub fn relationships(&self, source: &str) -> Result<&RelationshipsPart, Error> {
        let source = normalize(source);
        let name = key(&relationships_part(&source));
        let (Some(read), Some(part)) = (self.relationships.get(&name), self.parts.get(&name))
        else {
            return Ok(&NO_RELATIONSHIPS);
        };
        read.get_or_init(|| {
            let data = part
                .data
                .get_or_init(|| self.inflate_part(part))
                .as_ref()
                .map_err(Error::clone)?;
            read_relationships(&part.name, data, &source, &self.limits.xml)
        })
        .as_ref()
        .map_err(Error::clone)
    }

    /// Returns the name of the main document part, such as `word/document.xml`.
    ///
    /// # Errors
    ///
    /// Returns an error when the package relationships are invalid or name no main document.
    pub fn main_document(&self) -> Result<String, Error> {
        Relationship::by_type(&self.relationships("")?.relationships, "/officeDocument")
            .map(|rel| rel.target.clone())
            .ok_or(Error::NoMainDocument)
    }
}

/// The relationships part `part_name` (`data`) of `source`, parsed within `limits`.
fn read_relationships(
    part_name: &str,
    data: &[u8],
    source: &str,
    limits: &XmlLimits,
) -> Result<RelationshipsPart, Error> {
    let doc = Document::parse(data, limits).map_err(Error::Xml)?;
    let root = doc.root().map_err(Error::Xml)?;
    let relationships = doc
        .child_elements(root)
        .filter(|id| doc.is(*id, RELATIONSHIPS_NS, "Relationship"))
        .map(|id| {
            let attr = |name| doc.attribute(id, None, name).unwrap_or("").to_owned();
            let external = attr("TargetMode") == "External";
            let target = attr("Target");
            Relationship {
                id: attr("Id"),
                rel_type: attr("Type"),
                target: if external {
                    target
                } else {
                    resolve(source, &target)
                },
                external,
            }
        })
        .collect();
    Ok(RelationshipsPart {
        name: part_name.to_owned(),
        relationships,
        undeclared_prefixes: doc.undeclared_prefixes().to_vec(),
    })
}

fn check_entry(size: u64, compressed: u64, limits: &Limits) -> Result<(), Error> {
    if size > limits.max_part_size {
        return Err(Error::Limit(Limit::PartSize));
    }
    if size > 1 << 20 && size / compressed.max(1) > limits.max_ratio {
        return Err(Error::Limit(Limit::Ratio));
    }
    Ok(())
}

fn normalize(name: &str) -> String {
    name.trim_start_matches('/').to_owned()
}

/// The name by which the package finds a part: without a leading `/`, with the ASCII letters
/// in lower case, since part names are equivalent under ASCII case-insensitive matching
/// (ECMA-376 Part 2, 6.2.2.3 and 3.3.11).
fn key(name: &str) -> String {
    normalize(name).to_ascii_lowercase()
}

/// Whether a part lies in a `_rels` folder, where `relationships_part` puts every relationships
/// part.
fn in_relationships_folder(name: &str) -> bool {
    name.starts_with("_rels/") || name.contains("/_rels/")
}

/// The name of the relationships part of the part `source`, or of the package when `source` is
/// empty (ECMA-376 Part 2, 9.3.4): `word/_rels/document.xml.rels` for `word/document.xml`.
#[must_use]
pub fn relationships_part(source: &str) -> String {
    match source.rsplit_once('/') {
        Some((dir, file)) => format!("{dir}/_rels/{file}.rels"),
        None if source.is_empty() => "_rels/.rels".to_owned(),
        None => format!("_rels/{source}.rels"),
    }
}

fn resolve(source: &str, target: &str) -> String {
    if let Some(absolute) = target.strip_prefix('/') {
        return absolute.to_owned();
    }
    let mut segments: Vec<&str> = match source.rsplit_once('/') {
        Some((dir, _)) => dir.split('/').collect(),
        None => Vec::new(),
    };
    for segment in target.split('/') {
        match segment {
            ".." => {
                segments.pop();
            }
            "." | "" => {}
            other => segments.push(other),
        }
    }
    segments.join("/")
}

#[cfg(test)]
mod tests {
    use super::{
        Error, Limit, Limits, Package, Relationship, RelationshipsPart, ZipFault, check_entry,
        relationships_part, resolve,
    };
    use std::io::{Cursor, Write};
    use zip::write::SimpleFileOptions;

    const ROOT_RELS: &str = r#"<?xml version="1.0"?><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"/></Relationships>"#;
    const DOC_RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="t/styles" Target="styles.xml"/><Relationship Id="rId2" Type="t/link" Target="https://example.com" TargetMode="External"/><Relationship Id="rId3" Type="t/x" Target="../custom/x.xml"/></Relationships>"#;

    fn package(files: &[(&str, &str)]) -> Vec<u8> {
        let mut out = zip::ZipWriter::new(Cursor::new(Vec::new()));
        out.add_directory("word/", SimpleFileOptions::default())
            .unwrap();
        for (name, body) in files {
            out.start_file(*name, SimpleFileOptions::default()).unwrap();
            out.write_all(body.as_bytes()).unwrap();
        }
        out.finish().unwrap().into_inner()
    }

    fn sample() -> Package {
        let bytes = package(&[
            ("_rels/.rels", ROOT_RELS),
            ("word/document.xml", "<w/>"),
            ("word/_rels/document.xml.rels", DOC_RELS),
        ]);
        Package::open(&bytes, &Limits::default()).unwrap()
    }

    #[test]
    fn finds_parts() {
        let pkg = sample();
        assert_eq!(pkg.main_document().unwrap(), "word/document.xml");
        assert_eq!(pkg.part("/word/document.xml"), Some(&b"<w/>"[..]));
        assert_eq!(pkg.part_names().count(), 3);
    }

    #[test]
    fn finds_relationships() {
        let pkg = sample();
        let read = pkg.relationships("word/document.xml").unwrap();
        assert_eq!(read.name, "word/_rels/document.xml.rels");
        assert_eq!(read.undeclared_prefixes, [] as [&str; 0]);
        let rels = &read.relationships;
        assert_eq!(rels[0].target, "word/styles.xml");
        assert!(rels[1].external);
        assert_eq!(rels[1].target, "https://example.com");
        assert_eq!(rels[2].target, "custom/x.xml");
        let none = pkg.relationships("word/styles.xml").unwrap();
        assert_eq!(*none, RelationshipsPart::default());
    }

    #[test]
    fn lists_the_undeclared_prefixes_of_a_relationships_part_without_their_relationships() {
        let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="a" Type="t/styles" Target="styles.xml"/><x:Relationship Id="b" Type="t/image" Target="media/b.png"/></Relationships>"#;
        let pkg = Package::open(
            &package(&[("word/_rels/document.xml.rels", rels)]),
            &Limits::default(),
        )
        .unwrap();
        let read = pkg.relationships("word/document.xml").unwrap();
        assert_eq!(read.undeclared_prefixes, ["x"]);
        let ids: Vec<&str> = read
            .relationships
            .iter()
            .map(|rel| rel.id.as_str())
            .collect();
        assert_eq!(ids, ["a"]);
    }

    #[test]
    fn finds_parts_and_relationships_whose_names_differ_in_ascii_case() {
        let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="t/image" Target="media/IMAGE1.png"/></Relationships>"#;
        let pkg = Package::open(
            &package(&[
                ("_rels/.rels", ROOT_RELS),
                ("word/Document.xml", "<w/>"),
                ("word/_rels/Document.XML.rels", rels),
                ("Word/Media/image1.png", "png"),
            ]),
            &Limits::default(),
        )
        .unwrap();
        let main = pkg.main_document().unwrap();
        assert_eq!(main, "word/document.xml");
        assert_eq!(pkg.part(&main), Some(&b"<w/>"[..]));
        let read = pkg.relationships(&main).unwrap();
        assert_eq!(read.name, "word/_rels/Document.XML.rels");
        let rels = &read.relationships;
        assert_eq!(rels[0].target, "word/media/IMAGE1.png");
        assert_eq!(pkg.part(&rels[0].target), Some(&b"png"[..]));
        let mut names: Vec<&str> = pkg.part_names().collect();
        names.sort_unstable();
        assert_eq!(
            names,
            [
                "Word/Media/image1.png",
                "_rels/.rels",
                "word/Document.xml",
                "word/_rels/Document.XML.rels"
            ]
        );
        assert_eq!(pkg.equivalent_entries().count(), 0);
    }

    #[test]
    fn keeps_the_first_of_two_entries_whose_names_differ_only_in_ascii_case() {
        let pkg = Package::open(
            &package(&[
                ("a/b.xml", "first"),
                ("A/B.xml", "second"),
                ("a/c.xml", "c"),
            ]),
            &Limits::default(),
        )
        .unwrap();
        assert_eq!(pkg.part("A/b.XML"), Some(&b"first"[..]));
        assert_eq!(pkg.part_names().count(), 2);
        assert_eq!(pkg.equivalent_entries().collect::<Vec<_>>(), ["A/B.xml"]);
    }

    #[test]
    fn reads_a_relationships_part_once_and_keeps_what_it_read() {
        let pkg = sample();
        let first = pkg.relationships("/word/document.xml").unwrap();
        let again = pkg.relationships("word/document.xml").unwrap();
        assert_eq!(first.relationships.len(), 3);
        assert!(std::ptr::eq(first, again));
        let bad = Package::open(
            &package(&[("word/_rels/document.xml.rels", "<a>")]),
            &Limits::default(),
        )
        .unwrap();
        let error = bad.relationships("word/document.xml").unwrap_err();
        assert!(matches!(error, Error::Xml(_)));
        assert_eq!(bad.relationships("word/document.xml").unwrap_err(), error);
    }

    #[test]
    fn looks_up_the_first_relationship_to_a_part_by_id_or_by_type() {
        let rel = |id: &str, rel_type: &str, target: &str, external| Relationship {
            id: id.to_owned(),
            rel_type: rel_type.to_owned(),
            target: target.to_owned(),
            external,
        };
        let rels = [
            rel("rId1", "t/styles", "https://example.com", true),
            rel(
                "rId1",
                "http://purl.oclc.org/ooxml/officeDocument/relationships/styles",
                "word/strict.xml",
                false,
            ),
            rel(
                "rId2",
                "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
                "word/transitional.xml",
                false,
            ),
            rel("rId3", "t/link", "https://example.com", true),
        ];
        let target = |rel: Option<&Relationship>| rel.map(|rel| rel.target.clone());
        assert_eq!(
            target(Relationship::by_id(&rels, "rId1")),
            Some("word/strict.xml".to_owned())
        );
        assert_eq!(
            target(Relationship::by_id(&rels, "rId2")),
            Some("word/transitional.xml".to_owned())
        );
        assert_eq!(Relationship::by_id(&rels, "rId3"), None);
        assert_eq!(Relationship::by_id(&rels, "rId4"), None);
        assert_eq!(
            target(Relationship::by_type(&rels, "/styles")),
            Some("word/strict.xml".to_owned())
        );
        assert_eq!(Relationship::by_type(&rels, "/link"), None);
        assert_eq!(Relationship::by_type(&rels, "/numbering"), None);
    }

    #[test]
    fn reports_a_missing_main_document_and_bad_zip() {
        let pkg = Package::open(&package(&[("a.xml", "<a/>")]), &Limits::default()).unwrap();
        assert_eq!(pkg.main_document().unwrap_err(), Error::NoMainDocument);
        assert_eq!(
            Package::open(b"not a zip", &Limits::default()).unwrap_err(),
            Error::Zip(ZipFault::Archive)
        );
        let bad = Package::open(&package(&[("_rels/.rels", "<a>")]), &Limits::default()).unwrap();
        assert!(matches!(bad.main_document(), Err(Error::Xml(_))));
    }

    #[test]
    fn enforces_limits() {
        let bytes = package(&[("a.xml", "0123456789"), ("b.xml", "0123456789")]);
        let small_part = Limits {
            max_part_size: 5,
            ..Limits::default()
        };
        assert_eq!(
            Package::open(&bytes, &small_part).unwrap_err(),
            Error::Limit(Limit::PartSize)
        );
        let small_total = Limits {
            max_total_size: 15,
            ..Limits::default()
        };
        assert_eq!(
            Package::open(&bytes, &small_total).unwrap_err(),
            Error::Limit(Limit::TotalSize)
        );
        let few = Limits {
            max_entries: 2,
            ..Limits::default()
        };
        assert_eq!(
            Package::open(&bytes, &few).unwrap_err(),
            Error::Limit(Limit::Entries)
        );
        assert_eq!(
            check_entry(2 << 20, 1, &Limits::default()),
            Err(Error::Limit(Limit::Ratio))
        );
        assert_eq!(check_entry(2 << 20, 1 << 20, &Limits::default()), Ok(()));
    }

    #[test]
    fn resolves_names() {
        assert_eq!(relationships_part(""), "_rels/.rels");
        assert_eq!(relationships_part("a.xml"), "_rels/a.xml.rels");
        assert_eq!(
            relationships_part("word/document.xml"),
            "word/_rels/document.xml.rels"
        );
        assert_eq!(resolve("word/document.xml", "/media/a.png"), "media/a.png");
        assert_eq!(
            resolve("word/document.xml", "./media/a.png"),
            "word/media/a.png"
        );
        assert_eq!(resolve("", "word/document.xml"), "word/document.xml");
    }

    #[test]
    fn errors_display() {
        let cases = [
            (
                Error::Zip(ZipFault::Archive),
                "unreadable ZIP package: its central directory does not read",
            ),
            (
                Error::Zip(ZipFault::Entry),
                "unreadable ZIP package: an entry of its central directory does not read",
            ),
            (
                Error::Zip(ZipFault::Name),
                "unreadable ZIP package: the name of an entry does not read",
            ),
            (
                Error::Zip(ZipFault::Read),
                "unreadable ZIP package: the data of an entry does not read",
            ),
            (
                Error::Limit(Limit::Entries),
                "package breaks the limit on the number of entries",
            ),
            (
                Error::Limit(Limit::PartSize),
                "package breaks the limit on the size of a part",
            ),
            (
                Error::Limit(Limit::TotalSize),
                "package breaks the limit on the total size",
            ),
            (
                Error::Limit(Limit::Ratio),
                "package breaks the limit on the compression ratio",
            ),
            (Error::NoMainDocument, "package has no main document"),
        ];
        for (error, message) in cases {
            assert_eq!(error.to_string(), message);
            assert!(std::error::Error::source(&error).is_none());
        }
        let xml = Error::Xml(f_office_xml::Error::DocType);
        assert_eq!(xml.to_string(), "bad relationships part");
        let cause = std::error::Error::source(&xml).map(ToString::to_string);
        assert_eq!(cause.as_deref(), Some("XML with a DOCTYPE is not allowed"));
    }

    #[test]
    fn reads_parts_lazily_without_caching_read_part() {
        let bytes = package(&[
            ("word/document.xml", "<doc/>"),
            ("word/media/large.bin", "0123456789abcdef"),
        ]);
        let pkg = Package::open(&bytes, &Limits::default()).unwrap();
        assert_eq!(pkg.part_size("word/media/large.bin"), Some(16));
        assert!(pkg.parts["word/media/large.bin"].data.get().is_none());
        let media = pkg.read_part("word/media/large.bin").unwrap();
        assert_eq!(media.as_deref(), Some(&b"0123456789abcdef"[..]));
        // `read_part` does not pin large media in the package cache.
        assert!(pkg.parts["word/media/large.bin"].data.get().is_none());
        // `part` lazily populates the cache on demand.
        assert_eq!(pkg.part("word/document.xml"), Some(&b"<doc/>"[..]));
        assert!(pkg.parts["word/document.xml"].data.get().is_some());
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn opens_a_package_lazily_from_a_file_and_enforces_mobile_limits() {
        let bytes = package(&[
            (
                "_rels/.rels",
                r#"<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"/></Relationships>"#,
            ),
            ("word/document.xml", "<w:document/>"),
        ]);
        let path = std::env::temp_dir().join(format!(
            "f-office-opc-lazy-{}-{}.docx",
            std::process::id(),
            bytes.len()
        ));
        std::fs::write(&path, &bytes).unwrap();
        let pkg = Package::open_file(&path, &Limits::mobile()).unwrap();
        assert_eq!(pkg.main_document().unwrap(), "word/document.xml");
        assert_eq!(
            pkg.read_part("word/document.xml").unwrap().as_deref(),
            Some(&b"<w:document/>"[..])
        );
        assert_eq!(pkg.limits().max_total_size, 128 << 20);
        let _ = std::fs::remove_file(&path);
    }
}