rbook 0.7.1

A fast, format-agnostic, ergonomic ebook library for reading, building, and editing EPUB 2 and 3.
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
//! Format-agnostic [`Metadata`]-related content.
//!
//! # See Also
//! - [`epub::metadata`][crate::epub::metadata] for the epub-specific metadata module.

pub mod datetime;

use crate::util::Sealed;
use std::fmt::Display;
use std::hash::Hash;

/// The metadata of an [`Ebook`](super::Ebook), encompassing detailed information,
/// such as the [`Version`], [`Title`], and [`Identifier`].
///
/// # See Also
/// - [`EpubMetadata`](crate::epub::metadata::EpubMetadata) for epub-specific metadata information.
///
/// # Examples
/// - Retrieving the [`author`](Metadata::creators) and [`subtitle`](Metadata::title):
/// ```
/// # use rbook::Epub;
/// # use rbook::ebook::metadata::TitleKind;
/// # fn main() -> rbook::ebook::errors::EbookResult<()> {
/// let epub = Epub::open("tests/ebooks/example_epub")?;
/// let metadata = epub.metadata();
///
/// // Retrieving the creator:
/// let author = metadata.creators().next().unwrap();
/// assert_eq!("John Doe", author.value());
/// assert_eq!(Some("Doe, John"), author.file_as());
/// assert_eq!(0, author.order());
///
/// // An EPUB may include multiple titles,
/// // here we retrieve the second title:
/// let title = metadata.titles().nth(1).unwrap();
/// assert_eq!("A subtitle", title.value());
/// assert_eq!(TitleKind::Subtitle, title.kind());
/// assert_eq!(1, title.order());
///
/// // Retrieving the last modified date:
/// let modified = epub.metadata().modified().unwrap();
/// let date = modified.date();
/// let time = modified.time();
/// assert_eq!((2023, 1, 25), (date.year(), date.month(), date.day()));
/// assert_eq!((10, 11, 35), (time.hour(), time.minute(), time.second()));
/// # Ok(())
/// # }
/// ```
pub trait Metadata<'ebook>: Sealed {
    /// The version of an [`ebook's`](super::Ebook) format in the form of a string.
    ///
    /// # See Also
    /// - [`Self::version`] for the parsed representation.
    ///
    /// # Examples
    /// - Retrieving the version of an ebook in EPUB format:
    /// ```
    /// # use rbook::Epub;
    /// # use rbook::ebook::metadata::Metadata;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let metadata = epub.metadata();
    ///
    /// // Calling the trait method directly returns `Option<&str>`
    /// assert_eq!(Some("3.3"), Metadata::version_str(&metadata));
    /// // The inherent method `EpubMetadata::version_str` returns `&str` instead:
    /// assert_eq!("3.3", metadata.version_str());
    /// # Ok(())
    /// # }
    /// ```
    fn version_str(&self) -> Option<&'ebook str>;

    /// The version of an [`Ebook`](super::Ebook).
    ///
    /// # See Also
    /// - [`Self::version_str`] for the original representation.
    ///
    /// # Examples
    /// - Retrieving the version of an ebook in EPUB format:
    /// ```
    /// # use rbook::Epub;
    /// # use rbook::ebook::metadata::Metadata;
    /// # use rbook::ebook::metadata::Version;
    /// # use rbook::epub::metadata::EpubVersion;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let metadata = epub.metadata();
    ///
    /// // Calling the trait method directly returns `Option<Version>`
    /// assert_eq!(Some(Version(3, 3)), Metadata::version(&metadata));
    /// // The inherent method `EpubMetadata::version` returns `EpubVersion` instead:
    /// assert_eq!(EpubVersion::from(Version(3, 3)), metadata.version());
    /// # Ok(())
    /// # }
    /// ```
    fn version(&self) -> Option<Version>;

    /// The publication date; when an [`Ebook`](super::Ebook) was published.
    ///
    /// # Examples
    /// - Retrieving the publication date:
    /// ```
    /// # use rbook::Epub;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/epub2")?;
    /// let published = epub.metadata().published().unwrap();
    /// let entry = epub.metadata().published_entry().unwrap();
    /// let date = published.date();
    ///
    /// assert_eq!("2023-01-25", entry.value());
    /// assert_eq!(2023, date.year());
    /// assert_eq!(1, date.month());
    /// assert_eq!(25, date.day());
    /// # Ok(())
    /// # }
    /// ```
    fn published(&self) -> Option<datetime::DateTime>;

    /// The last modified date; when an [`Ebook`](super::Ebook) was last modified.
    ///
    /// # See Also
    /// - [`Self::published`] to retrieve the data en ebook was published.
    ///
    /// # Examples
    /// - Retrieving the modification date:
    /// ```
    /// # use rbook::Epub;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/epub2")?;
    /// let modified = epub.metadata().modified().unwrap();
    /// let entry = epub.metadata().modified_entry().unwrap();
    ///
    /// assert_eq!("2025-11-27", entry.value());
    /// assert_eq!(2025, modified.date().year());
    /// assert_eq!(0, modified.time().hour());
    /// assert_eq!(false, modified.time().is_utc());
    /// # Ok(())
    /// # }
    /// ```
    fn modified(&self) -> Option<datetime::DateTime>;

    /// The main unique [`Identifier`] of an [`Ebook`](super::Ebook).
    fn identifier(&self) -> Option<impl Identifier<'ebook> + 'ebook>;

    /// Returns an iterator over **all** [identifiers](Identifier)
    /// by [`order`](MetaEntry::order).
    ///
    /// Note that the first entry may not be the main [`Identifier`],
    /// as depending on the ebook, the order of the main identifier may be greater than `0`.
    /// Generally, such a scenario is rare, although possible.
    ///
    /// # See Also
    /// - [`Self::identifier`] to get the main identifier, disregarding
    ///   [`order`](MetaEntry::order).
    fn identifiers(&self) -> impl Iterator<Item = impl Identifier<'ebook> + 'ebook> + 'ebook;

    /// The main [`Language`] with an [`order`](MetaEntry::order) of `0`.
    fn language(&self) -> Option<impl Language<'ebook> + 'ebook>;

    /// Returns an iterator over **all** [`Languages`](Language)
    /// by [`order`](MetaEntry::order).
    fn languages(&self) -> impl Iterator<Item = impl Language<'ebook> + 'ebook> + 'ebook;

    /// The main [`Title`].
    ///
    /// # See Also
    /// - [`Self::titles`] to retrieve all titles by [`order`](MetaEntry::order).
    ///
    /// # Examples
    /// - Retrieving the main title:
    /// ```
    /// # use rbook::Epub;
    /// # use rbook::ebook::metadata::TitleKind;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let title = epub.metadata().title().unwrap();
    ///
    /// assert_eq!("Example EPUB", title.value());
    /// assert_eq!(TitleKind::Main, title.kind());
    /// assert_eq!(2, title.order());
    /// # Ok(())
    /// # }
    /// ```
    fn title(&self) -> Option<impl Title<'ebook> + 'ebook>;

    /// Returns an iterator over **all** [titles](Title)
    /// by [`order`](MetaEntry::order).
    ///
    /// Note that the first entry may not be the main [`Title`],
    /// as depending on the ebook, the order of the main title may be greater than `0`.
    /// Generally, such a scenario is rare, although possible.
    ///
    /// # See Also
    /// - [`Self::title`] to get the main title, disregarding [`order`](MetaEntry::order).
    /// - [`Title::kind`] to get the kind of title.
    ///
    /// # Examples
    /// - Retrieving the titles of an ebook:
    /// ```
    /// # use rbook::Epub;
    /// # use rbook::ebook::metadata::TitleKind;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let mut titles = epub.metadata().titles();
    ///
    /// let title_a = titles.next().unwrap();
    /// assert_eq!("This is not the main title", title_a.value());
    /// assert_eq!(TitleKind::Unknown, title_a.kind());
    /// assert_eq!(0, title_a.order());
    ///
    /// let title_b = titles.next().unwrap();
    /// assert_eq!("A subtitle", title_b.value());
    /// assert_eq!(TitleKind::Subtitle, title_b.kind());
    /// assert_eq!(1, title_b.order());
    ///
    /// let title_c = titles.next().unwrap();
    /// assert_eq!("Example EPUB", title_c.value());
    /// assert_eq!(TitleKind::Main, title_c.kind());
    /// assert_eq!(2, title_c.order());
    /// # Ok(())
    /// # }
    /// ```
    fn titles(&self) -> impl Iterator<Item = impl Title<'ebook> + 'ebook> + 'ebook;

    /// The main description with an [`order`](MetaEntry::order) of `0`.
    fn description(&self) -> Option<impl MetaEntry<'ebook> + 'ebook>;

    /// Returns an iterator over **all** descriptions by [`order`](MetaEntry::order).
    fn descriptions(&self) -> impl Iterator<Item = impl MetaEntry<'ebook> + 'ebook> + 'ebook;

    /// Returns an iterator over **all** [creators](Contributor)
    /// by [`order`](MetaEntry::order).
    fn creators(&self) -> impl Iterator<Item = impl Contributor<'ebook> + 'ebook> + 'ebook;

    /// Returns an iterator over **all** [contributors](Contributor)
    /// by [`order`](MetaEntry::order).
    fn contributors(&self) -> impl Iterator<Item = impl Contributor<'ebook> + 'ebook> + 'ebook;

    /// Returns an iterator over **all** [publishers](Contributor)
    /// by [`order`](MetaEntry::order).
    fn publishers(&self) -> impl Iterator<Item = impl Contributor<'ebook> + 'ebook> + 'ebook;

    /// Returns an iterator over **all** generators.
    ///
    /// A generator indicates the software used to create an [`Ebook`](super::Ebook).
    fn generators(&self) -> impl Iterator<Item = impl MetaEntry<'ebook> + 'ebook> + 'ebook;

    /// Returns an iterator over **all** [tags](Tag)
    /// by [`order`](MetaEntry::order).
    fn tags(&self) -> impl Iterator<Item = impl Tag<'ebook> + 'ebook> + 'ebook;

    /// Returns an iterator over **all** metadata entries.
    fn iter(&self) -> impl Iterator<Item = impl MetaEntry<'ebook> + 'ebook> + 'ebook;
}

/// The scheme of metadata entries, specifying a registry [`source`](Scheme::source)
/// and [`code`](Scheme::code).
///
/// A `source` identifies "who" (such as an authority) that defines the code, such
/// as `BCP 47`, `BISAC`, and `marc:relators`.
///
/// Sources are optional and will not be specified if there is no known
/// registry for a `code`.
///
/// # Equality
/// Two schemes are equal if their [`source`](Scheme::source) and [`code`](Scheme::code)
/// are **case-sensitively** equal.
///
/// # Examples
/// - Retrieving the source and code:
/// ```
/// # use rbook::Epub;
/// # fn main() -> rbook::ebook::errors::EbookResult<()> {
/// let epub = Epub::open("tests/ebooks/example_epub")?;
/// let primary_language = epub.metadata().language().unwrap();
/// let scheme = primary_language.scheme();
///
/// assert_eq!(Some("BCP 47"), scheme.source());
/// assert_eq!("en", scheme.code());
/// # Ok(())
/// # }
/// ```
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub struct Scheme<'ebook> {
    source: Option<&'ebook str>,
    code: &'ebook str,
}

impl<'ebook> Scheme<'ebook> {
    pub(crate) fn new(source: Option<&'ebook str>, code: &'ebook str) -> Self {
        Self { source, code }
    }

    /// The authority or registry that defines a [`code`](Self::code)
    /// (e.g. `BCP 47`, `BISAC` `marc:relators`), or [`None`] if unknown.
    pub fn source(&self) -> Option<&'ebook str> {
        self.source
    }

    /// The identification code (e.g., `FIC002000`, `zh-CN`).
    pub fn code(&self) -> &'ebook str {
        self.code
    }
}

/// The language tag, consisting of a [`Scheme`] and [`LanguageKind`].
///
/// Represents a language code (e.g. `en`, `ja`) alongside its source (e.g. `BCP 47`).
///
/// Unlike [`Language`], [`LanguageTag`] complements metadata entries
/// instead of specifying an ebook-wide language.
///
/// # See Also
/// - [`AlternateScript`]
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub struct LanguageTag<'ebook> {
    scheme: Scheme<'ebook>,
    kind: LanguageKind,
}

impl<'ebook> LanguageTag<'ebook> {
    pub(crate) fn new(code: &'ebook str, kind: LanguageKind) -> Self {
        Self {
            scheme: Scheme::new((kind != LanguageKind::Unknown).then(|| kind.as_str()), code),
            kind,
        }
    }

    /// The [`Scheme`] that identifies the authority and language code.
    pub fn scheme(&self) -> Scheme<'ebook> {
        self.scheme
    }

    /// The language tag scheme kind (e.g., `BCP 47`).
    pub fn kind(&self) -> LanguageKind {
        self.kind
    }
}

/// Alternate script to portray an alternative form of textual content
/// in a different language or script.
///
/// # Examples
/// ```
/// # use rbook::Epub;
/// # use rbook::ebook::metadata::LanguageKind;
/// # fn main() -> rbook::ebook::errors::EbookResult<()> {
/// let epub = Epub::open("tests/ebooks/example_epub")?;
/// let title = epub.metadata().title().unwrap();
///
/// assert_eq!("Example EPUB", title.value());
///
/// let alternate_script = title.alternate_scripts().next().unwrap();
///
/// assert_eq!("サンプルEPUB", alternate_script.value());
/// assert_eq!("ja", alternate_script.language().scheme().code());
/// assert_eq!(LanguageKind::Bcp47, alternate_script.language().kind());
/// # Ok(())
/// # }
/// ```
pub struct AlternateScript<'ebook> {
    script: &'ebook str,
    tag: LanguageTag<'ebook>,
}

impl<'ebook> AlternateScript<'ebook> {
    pub(crate) fn new(script: &'ebook str, tag: LanguageTag<'ebook>) -> Self {
        Self { script, tag }
    }

    /// The alternate form text value.
    pub fn value(&self) -> &'ebook str {
        self.script
    }

    /// The language tag associated with the alternate form.
    pub fn language(&self) -> LanguageTag<'ebook> {
        self.tag
    }
}

/// A [`Metadata`] entry containing information associated with an [`Ebook`](super::Ebook).
///
/// This trait provides access to details such as its [`value`](MetaEntry::value),
/// [`order`](MetaEntry::order), [`sort key`](MetaEntry::file_as), and
/// [`alternate scripts`](MetaEntry::alternate_scripts).
///
/// # See Also
/// - [`EpubMetaEntry`](crate::epub::metadata::EpubMetaEntry) for epub-specific entry information.
pub trait MetaEntry<'ebook>: Sealed {
    /// The plain text value of an entry.
    ///
    /// # Example
    /// - Retrieving the value of a description:
    /// ```
    /// # use rbook::Epub;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let description = epub.metadata().description().unwrap();
    ///
    /// assert_eq!(
    ///     "Hello world! CData 1. A descriptive statement. CData 2. Another statement !",
    ///     description.value(),
    /// );
    /// # Ok(())
    /// # }
    /// ```
    fn value(&self) -> &'ebook str;

    /// The (0-based) order/display-sequence of an entry relative to another associated entry.
    ///
    /// For example, if there are multiple creators, this field indicates who
    /// is ordered before one another.
    ///
    /// A value of `0` means first, `1` means second, and so on.
    ///
    /// # Example
    /// - Retrieving the order of tags:
    /// ```
    /// # use rbook::Epub;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let mut tags = epub.metadata().tags();
    ///
    /// let tag_a = tags.next().unwrap();
    /// assert_eq!("FICTION / Occult & Supernatural", tag_a.value());
    /// assert_eq!(0, tag_a.order());
    ///
    /// let tag_b = tags.next().unwrap();
    /// assert_eq!("Quests (Expeditions) -- Fiction", tag_b.value());
    /// assert_eq!(1, tag_b.order());
    ///
    /// let tag_c = tags.next().unwrap();
    /// assert_eq!("Fantasy", tag_c.value());
    /// assert_eq!(2, tag_c.order());
    /// # Ok(())
    /// # }
    /// ```
    fn order(&self) -> usize;

    /// The `file-as` sort key, if present.
    ///
    /// # Example
    /// - Retrieving the sort key:
    /// ```
    /// # use rbook::Epub;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    ///
    /// let creator = epub.metadata().creators().next().unwrap();
    /// assert_eq!("John Doe", creator.value());
    /// assert_eq!(Some("Doe, John"), creator.file_as());
    /// # Ok(())
    /// # }
    /// ```
    fn file_as(&self) -> Option<&'ebook str>;

    /// Returns an iterator over **all** [`AlternateScript`].
    ///
    /// Alternate script is an **alternative** form of [`Self::value`]
    /// in a different language or script.
    fn alternate_scripts(&self) -> impl Iterator<Item = AlternateScript<'ebook>> + 'ebook;
}

/// A language that an [`Ebook`](super::Ebook) supports.
///
/// Provides both the raw scheme string and a parsed kind.
///
/// # See Also
/// - [`EpubLanguage`](crate::epub::metadata::EpubLanguage) for epub-specific information.
///
/// # Examples
/// - Retrieving a language's kind and scheme:
/// ```
/// # use rbook::Epub;
/// # use rbook::ebook::metadata::LanguageKind;
/// # fn main() -> rbook::ebook::errors::EbookResult<()> {
/// let epub = Epub::open("tests/ebooks/example_epub")?;
/// let language = epub.metadata().language().unwrap();
///
/// assert_eq!(LanguageKind::Bcp47, language.kind());
/// assert_eq!("en", language.value());
///
/// let scheme = language.scheme();
///
/// assert_eq!(Some("BCP 47"), scheme.source());
/// assert_eq!("en", scheme.code());
/// # Ok(())
/// # }
/// ```
pub trait Language<'ebook>: MetaEntry<'ebook> {
    /// The language's scheme, such as `BCP 47`.
    ///
    /// This is a lower-level call than [`Self::kind`] to retrieve the raw string value.
    fn scheme(&self) -> Scheme<'ebook>;

    /// The language kind enum.
    ///
    /// If [`LanguageKind::Unknown`] is returned, [`Self::scheme`]
    /// can be used to retrieve the string value of the unknown language kind.
    fn kind(&self) -> LanguageKind;
}

/// A unique identifier for an [`Ebook`](super::Ebook), such as `ISBN`, `DOI`, and `URL`.
///
/// # See Also
/// - [`EpubIdentifier`](crate::epub::metadata::EpubIdentifier) for epub-specific information.
///
/// # Examples
/// - Retrieving the main identifier:
/// ```
/// # use rbook::Epub;
/// # fn main() -> rbook::ebook::errors::EbookResult<()> {
/// let epub = Epub::open("tests/ebooks/example_epub")?;
/// let identifier = epub.metadata().identifier().unwrap();
/// let scheme = identifier.scheme().unwrap();
///
/// assert_eq!("https://github.com/devinsterling/rbook", identifier.value());
/// assert_eq!("URL", scheme.code());
/// assert_eq!(None, scheme.source());
/// # Ok(())
/// # }
/// ```
pub trait Identifier<'ebook>: MetaEntry<'ebook> + Eq + Hash {
    /// The identifier’s scheme or [`None`] if unspecified.
    fn scheme(&self) -> Option<Scheme<'ebook>>;
}

/// A title of an [`Ebook`](super::Ebook).
///
/// Titles may have an optional scheme for further categorization (e.g. `subtitle`, `edition`).
///
/// # See Also
/// - [`EpubTitle`](crate::epub::metadata::EpubTitle) for epub-specific information.
///
/// # Examples
/// - Retrieving a title's kind:
/// ```
/// # use rbook::Epub;
/// # use rbook::ebook::metadata::TitleKind;
/// # fn main() -> rbook::ebook::errors::EbookResult<()> {
/// let epub = Epub::open("tests/ebooks/example_epub")?;
/// let subtitle = epub.metadata().titles().nth(1).unwrap();
///
/// assert_eq!(TitleKind::Subtitle, subtitle.kind());
///
/// let scheme = subtitle.scheme().unwrap();
///
/// assert_eq!(None, scheme.source());
/// assert_eq!("subtitle", scheme.code());
/// # Ok(())
/// # }
/// ```
pub trait Title<'ebook>: MetaEntry<'ebook> {
    /// The title’s scheme or [`None`] if unspecified.
    ///
    /// This is a lower-level call than [`Self::kind`] to retrieve the raw string value, if any.
    fn scheme(&self) -> Option<Scheme<'ebook>>;

    /// The kind of title.
    ///
    /// If [`TitleKind::Unknown`] is returned, [`Self::scheme`]
    /// can be used to retrieve the string value of the unknown title kind, if present.
    fn kind(&self) -> TitleKind;
}

/// A tag that categorizes an [`Ebook`](super::Ebook).
///
/// # See Also
/// - [`EpubTag`](crate::epub::metadata::EpubTag) for epub-specific information.
///
/// # Examples
/// - Retrieving all tags:
/// ```
/// # use rbook::Epub;
/// # fn main() -> rbook::ebook::errors::EbookResult<()> {
/// let epub = Epub::open("tests/ebooks/example_epub")?;
/// let tags = epub.metadata().tags().collect::<Vec<_>>();
///
/// // Book Industry Standards and Communications (BISAC) tag
/// let bisac = tags[0].scheme().unwrap();
/// assert_eq!("FICTION / Occult & Supernatural", tags[0].value());
/// assert_eq!("FIC024000", bisac.code());
/// assert_eq!(Some("BISAC"), bisac.source());
///
/// // The Library of Congress Subject Headings (LCSH) tag
/// let lcsh = tags[1].scheme().unwrap();
/// assert_eq!("Quests (Expeditions) -- Fiction", tags[1].value());
/// assert_eq!("sh2008110314", lcsh.code());
/// assert_eq!(Some("LCSH"), lcsh.source());
///
/// // Plain tag (No scheme specified)
/// assert_eq!("Fantasy", tags[2].value());
/// assert_eq!(None, tags[2].scheme());
/// # Ok(())
/// # }
/// ```
pub trait Tag<'ebook>: MetaEntry<'ebook> {
    /// The tag’s scheme or [`None`] if unspecified.
    fn scheme(&self) -> Option<Scheme<'ebook>>;
}

/// Individuals or organizations that helped with the creation of an [`Ebook`](super::Ebook),
/// such as, `authors`, `illustrators`, and `publishers`.
///
/// # See Also
/// - [`EpubContributor`](crate::epub::metadata::EpubContributor) for epub-specific information.
///
/// # Examples
/// - Retrieving an author:
/// ```
/// # use rbook::Epub;
/// # fn main() -> rbook::ebook::errors::EbookResult<()> {
/// let epub = Epub::open("tests/ebooks/example_epub")?;
/// let author = epub.metadata().creators().next().unwrap();
/// let role = author.main_role().unwrap();
///
/// assert_eq!("John Doe", author.value());
/// assert_eq!("aut", role.code());
/// assert_eq!(Some("marc:relators"), role.source());
/// # Ok(())
/// # }
/// ```
pub trait Contributor<'ebook>: MetaEntry<'ebook> {
    /// The primary role of a contributor or [`None`] if unspecified.
    ///
    /// For example, a contributor could be the `author` and `illustrator` of an ebook.
    /// However, their main role would remain as the `author`.
    fn main_role(&self) -> Option<Scheme<'ebook>>;

    /// Returns an iterator over **all** roles by the order of importance (display sequence).
    fn roles(&self) -> impl Iterator<Item = Scheme<'ebook>> + 'ebook;
}

/// The kind of `language`.
#[non_exhaustive]
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum LanguageKind {
    /// `BCP 47`: See <https://www.rfc-editor.org/info/bcp47>.
    Bcp47,
    // ISO639,
    /// An unknown language kind.
    Unknown,
}

impl LanguageKind {
    /// Returns the string form of a [`LanguageKind`].
    ///
    /// # Examples
    /// - Retrieving the string form:
    /// ```
    /// # use rbook::ebook::metadata::LanguageKind;
    /// assert_eq!("BCP 47", LanguageKind::Bcp47.as_str());
    /// assert_eq!("unknown", LanguageKind::Unknown.as_str());
    /// ```
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Bcp47 => "BCP 47",
            Self::Unknown => "unknown",
        }
    }
}

impl Display for LanguageKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The kind of [`Title`].
#[non_exhaustive]
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum TitleKind {
    /// The primary main title.
    Main,
    /// The secondary title (subtitle).
    Subtitle,
    /// A shortened version of the main title.
    Short,
    /// An expanded detailed version of the main title.
    Expanded,
    /// The title of a collection that an [`Ebook`](super::Ebook) belongs.
    Collection,
    /// The title of a particular edition.
    Edition,
    /// An unrecognized title kind.
    Unknown,
}

impl TitleKind {
    const MAIN: &'static str = "main";
    const SUBTITLE: &'static str = "subtitle";
    const SHORT: &'static str = "short";
    const EXPANDED: &'static str = "expanded";
    const COLLECTION: &'static str = "collection";
    const EDITION: &'static str = "edition";

    // **For now**, there is no public From<&str>/as_str method for TitleKind because
    // other ebook formats may have different (and potentially conflicting)
    // mappings (e.g., main-title, primary, etc.)
    pub(super) fn from(kind: &str) -> Self {
        match kind {
            Self::MAIN => Self::Main,
            Self::SUBTITLE => Self::Subtitle,
            Self::SHORT => Self::Short,
            Self::COLLECTION => Self::Collection,
            Self::EDITION => Self::Edition,
            Self::EXPANDED => Self::Expanded,
            _ => Self::Unknown,
        }
    }

    #[cfg(feature = "write")]
    pub(super) fn as_str(&self) -> Option<&'static str> {
        match self {
            Self::Main => Some(Self::MAIN),
            Self::Subtitle => Some(Self::SUBTITLE),
            Self::Short => Some(Self::SHORT),
            Self::Collection => Some(Self::COLLECTION),
            Self::Edition => Some(Self::EDITION),
            Self::Expanded => Some(Self::EXPANDED),
            _ => None,
        }
    }

    /// Returns `true` if the title kind is [`TitleKind::Main`]
    pub fn is_main(&self) -> bool {
        matches!(self, Self::Main)
    }

    /// Returns `true` if the title kind is [`TitleKind::Subtitle`]
    pub fn is_subtitle(&self) -> bool {
        matches!(self, Self::Subtitle)
    }

    /// Returns `true` if the title kind is [`TitleKind::Short`]
    pub fn is_short(&self) -> bool {
        matches!(self, Self::Short)
    }

    /// Returns `true` if the title kind is [`TitleKind::Collection`]
    pub fn is_collection(&self) -> bool {
        matches!(self, Self::Collection)
    }

    /// Returns `true` if the title kind is [`TitleKind::Edition`]
    pub fn is_edition(&self) -> bool {
        matches!(self, Self::Edition)
    }

    /// Returns `true` if the title kind is [`TitleKind::Expanded`]
    pub fn is_expanded(&self) -> bool {
        matches!(self, Self::Expanded)
    }

    /// Returns `true` if the title kind is [`TitleKind::Unknown`]
    pub fn is_unknown(&self) -> bool {
        matches!(self, Self::Unknown)
    }
}

/// The version of an [`Ebook`](super::Ebook) format (e.g. `3.3`).
///
/// A version consists of:
/// - [`Major`](Version::major): Paradigm-shifting release.
/// - [`Minor`](Version::minor): Backwards-compatible, gradual update.
///
/// # Examples
/// - Retrieving the major and minor of a version:
/// ```
/// use rbook::ebook::metadata::Version;
///
/// let version = Version(2, 8);
/// assert_eq!(2, version.major());
/// assert_eq!(8, version.minor());
/// ```
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Version(
    /// Paradigm-shifting release.
    pub u16,
    /// Backwards-compatible, gradual update.
    pub u16,
);

impl Version {
    pub(crate) fn from_str(version: &str) -> Option<Self> {
        let mut components = version.trim().split('.').map(str::parse);

        Some(Self(
            // Required
            components.next()?.ok()?,
            // Optional
            components.next().unwrap_or(Ok(0)).ok()?,
        ))
    }

    /// Paradigm-shifting release number.
    pub fn major(&self) -> u16 {
        self.0
    }

    /// Backwards-compatible, gradual update number.
    pub fn minor(&self) -> u16 {
        self.1
    }
}

impl From<u16> for Version {
    fn from(version: u16) -> Self {
        Self(version, 0)
    }
}

impl Display for Version {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}.{}", self.0, self.1)
    }
}

#[cfg(test)]
mod tests {
    use crate::ebook::metadata::Version;

    #[test]
    fn test_version_from_str() {
        let expected = [
            ("2.0", Some(Version(2, 0))),
            ("3.1", Some(Version(3, 1))),
            ("3", Some(Version(3, 0))),
            (" 3.2 ", Some(Version(3, 2))),
            ("", None),
            ("x.y", None),
            ("2.3-", None),
        ];

        for (raw, expected_version) in expected {
            assert_eq!(expected_version, Version::from_str(raw));
        }
    }
}