rbook 0.7.6

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
//! EPUB package content.

#[cfg(feature = "write")]
mod write;

use crate::ebook::element::{Attributes, AttributesData, Href, TextDirection};
use crate::epub::metadata::{
    EpubMetaEntry, EpubMetaEntryData, EpubRefinements, EpubRefinementsData, EpubVersion,
};
use crate::util::collection::{Keyed, KeyedVec};
use crate::util::uri;

#[cfg(feature = "write")]
pub use write::{EpubPackageMut, PrefixesMutIter};

////////////////////////////////////////////////////////////////////////////////
// PRIVATE API
////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq)]
pub(super) struct EpubPackageData {
    /// ***Absolute percent-encoded*** `.opf` package file location
    /// (e.g. `/OEBPS/package.opf`).
    pub(super) location: String,
    pub(super) version: EpubVersionData,
    /// The `id` of the primary unique identifier.
    pub(super) unique_identifier: String,
    pub(super) prefixes: Prefixes,
    /// Default package document language
    pub(super) language: Option<String>,
    /// Default package document text directionality
    pub(super) text_direction: TextDirection,
    pub(super) attributes: AttributesData,
}

/// Contains the raw and parsed epub version
#[derive(Debug, PartialEq)]
pub(super) struct EpubVersionData {
    pub(super) raw: String,
    pub(super) parsed: EpubVersion,
}

impl From<EpubVersion> for EpubVersionData {
    fn from(parsed: EpubVersion) -> Self {
        Self {
            raw: parsed.to_string(),
            parsed,
        }
    }
}

impl<'ebook> From<&'ebook EpubPackageData> for EpubPackageMetaContext<'ebook> {
    fn from(value: &'ebook EpubPackageData) -> Self {
        Self::new(value)
    }
}

#[derive(Copy, Clone, Debug)]
pub(super) struct EpubPackageMetaContext<'ebook>(Option<&'ebook EpubPackageData>);

impl<'ebook> EpubPackageMetaContext<'ebook> {
    #[cfg(feature = "write")]
    pub(super) const EMPTY: EpubPackageMetaContext<'static> = EpubPackageMetaContext(None);

    pub(super) fn new(package: &'ebook EpubPackageData) -> Self {
        Self(Some(package))
    }

    pub(super) fn package_language(&self) -> Option<&'ebook str> {
        self.0?.language.as_deref()
    }

    pub(super) fn package_text_direction(&self) -> TextDirection {
        self.0
            .as_ref()
            .map_or(TextDirection::Auto, |pkg| pkg.text_direction)
    }

    pub(super) fn create_entry(
        self,
        data: &'ebook EpubMetaEntryData,
        index: usize,
    ) -> EpubMetaEntry<'ebook> {
        EpubMetaEntry::new(self, None, data, index)
    }

    pub(super) fn create_refining_entry(
        self,
        parent_id: Option<&'ebook str>,
        data: &'ebook EpubMetaEntryData,
        index: usize,
    ) -> EpubMetaEntry<'ebook> {
        EpubMetaEntry::new(self, parent_id, data, index)
    }

    pub(super) fn create_refinements(
        self,
        parent_id: Option<&'ebook str>,
        data: &'ebook EpubRefinementsData,
    ) -> EpubRefinements<'ebook> {
        EpubRefinements::new(self, parent_id, data)
    }
}

////////////////////////////////////////////////////////////////////////////////
// PUBLIC API
////////////////////////////////////////////////////////////////////////////////

/// The EPUB package, mapped to the `<package>` element,
/// accessible via [`Epub::package`](super::Epub::package).
///
/// # See Also
/// - [`EpubPackageMut`] for a mutable view.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct EpubPackage<'ebook>(&'ebook EpubPackageData);

impl<'ebook> EpubPackage<'ebook> {
    pub(super) fn new(data: &'ebook EpubPackageData) -> Self {
        Self(data)
    }

    /// The absolute percent-encoded location of the package `.opf` file.
    ///
    /// This is ***not*** a filesystem path.
    /// It always starts with `/` to indicate the EPUB container root,
    /// and is percent encoded (e.g., `/my%20dir/my%20pkg.opf`).
    ///
    /// # See Also
    /// - [`Href::decode`] to retrieve the percent-decoded form.
    /// - [`Href::name`] to retrieve the filename.
    /// - [`EpubPackageMut::set_location`] to modify the location.
    ///
    /// # Examples
    /// - Retrieving the package file:
    /// ```
    /// # use rbook::Epub;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    ///
    /// assert_eq!("/EPUB/example.opf", epub.package().location().as_str());
    /// # Ok(())
    /// # }
    /// ```
    pub fn location(&self) -> Href<'ebook> {
        Href::new(&self.0.location)
    }

    /// The absolute percent-encoded directory, the package [file](Self::location) resides in.
    ///
    /// This is ***not*** a filesystem path.
    /// It always starts with `/` to indicate the EPUB container root,
    /// and is percent encoded (e.g., `/my%20dir`).
    ///
    /// [`Resources`](crate::ebook::resource::Resource)
    /// referenced in the package file are resolved relative to the package directory.
    ///
    /// # See Also
    /// - [`Href::decode`] to retrieve the percent-decoded form.
    ///
    /// # Examples
    /// - Retrieving the package file and directory:
    /// ```
    /// # use rbook::Epub;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let package_dir = epub.package().directory().as_str();
    /// let package_file = epub.package().location().as_str();
    ///
    /// assert_eq!("/EPUB", package_dir);
    /// assert_eq!(format!("{package_dir}/example.opf"), package_file);
    /// # Ok(())
    /// # }
    /// ```
    pub fn directory(&self) -> Href<'ebook> {
        Href::new(uri::parent(&self.0.location))
    }

    /// The [`Epub`](super::Epub) version (e.g., `2.0`, `3.2`, etc.).
    ///
    /// The returned version may be [`EpubVersion::Unknown`] if
    /// [`EpubOpenOptions::strict`](super::EpubOpenOptions::strict) is disabled.
    ///
    /// # Note
    /// This method is equivalent to calling
    /// [`EpubMetadata::version`](super::metadata::EpubMetadata::version).
    ///
    /// # See Also
    /// - [`Self::version_str`] for the original representation.
    /// - [`EpubPackageMut::set_version`] to modify the version.
    pub fn version(&self) -> EpubVersion {
        self.0.version.parsed
    }

    /// The underlying [`Epub`](super::Epub) version string.
    ///
    /// # Note
    /// This method is equivalent to calling
    /// [`EpubMetadata::version_str`](super::metadata::EpubMetadata::version_str).
    pub fn version_str(&self) -> &'ebook str {
        self.0.version.raw.as_str()
    }

    /// The `id` of the package's unique identifier metadata entry.
    ///
    /// This is a lower-level call than
    /// [`EpubMetadata::identifier`](super::metadata::EpubMetadata::identifier).
    ///
    /// # See Also
    /// - [`EpubPackageMut::set_unique_identifier`] to modify the identifier.
    ///
    /// # Examples
    /// - Comparing the unique identifier:
    /// ```
    /// # use rbook::Epub;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let unique_identifier = epub.package().unique_identifier();
    /// let identifier = epub.metadata().identifier().unwrap();
    ///
    /// assert_eq!("uid", unique_identifier);
    /// assert_eq!(Some("uid"), identifier.id());
    /// assert_eq!(unique_identifier, identifier.id().unwrap());
    /// # Ok(())
    /// # }
    /// ```
    pub fn unique_identifier(&self) -> &'ebook str {
        &self.0.unique_identifier
    }

    /// The package-level [text direction](TextDirection) (`dir`).
    ///
    /// All metadata entries within an [`Epub`](super::Epub) implicitly inherit this
    /// field if their [`EpubMetaEntry::text_direction`](EpubMetaEntry::text_direction)
    /// is set to [`TextDirection::Auto`].
    ///
    /// # See Also
    /// - [`EpubPackageMut::set_text_direction`] to modify the text direction.
    pub fn text_direction(&self) -> TextDirection {
        self.0.text_direction
    }

    /// The package-level language code (`xml:lang`) in `BCP 47` format, if present.
    ///
    /// All metadata entries within an [`Epub`](super::Epub) implicitly inherit this
    /// field if their [`EpubMetaEntry::xml_language`](EpubMetaEntry::xml_language)
    /// is set to [`None`].
    ///
    /// # See Also
    /// - [`EpubPackageMut::set_xml_language`] to modify the language code.
    pub fn xml_language(&self) -> Option<&'ebook str> {
        self.0.language.as_deref()
    }

    /// The package-level prefixes, defining prefix mappings for use in
    /// [`property`](EpubMetaEntry::property) values.
    ///
    /// # See Also
    /// - [`EpubPackageMut::prefixes_mut`] to modify the prefixes.
    pub fn prefixes(&self) -> &'ebook Prefixes {
        &self.0.prefixes
    }

    /// All additional XML [`Attributes`] of the `<package>` element.
    ///
    /// This method provides access to non-standard or vendor-specific attributes
    /// not explicitly handled by this struct.
    ///
    /// # Omitted Attributes
    /// The following attributes will **not** be found within the returned collection:
    /// - [`version`](Self::version)
    /// - [`unique-identifier`](Self::unique_identifier)
    /// - [`dir`](Self::text_direction)
    /// - [`xml:lang`](Self::xml_language)
    /// - [`prefix`](Self::prefixes)
    ///
    /// # See Also
    /// - [`EpubPackageMut::attributes_mut`] to modify the attributes.
    pub fn attributes(&self) -> &'ebook Attributes {
        &self.0.attributes
    }
}

/// A collection of [`Prefix`] entries.
#[derive(Debug, PartialEq)]
pub struct Prefixes(KeyedVec<Prefix>);

impl Prefixes {
    pub(super) const EMPTY: Self = Self::new(Vec::new());

    pub(super) const fn new(prefixes: Vec<Prefix>) -> Self {
        Self(KeyedVec(prefixes))
    }

    /// The number of [`Prefix`] entries contained within.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns `true` if there are no prefixes.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns the associated [`Prefix`] if the given `index` is less than
    /// [`Self::len`], otherwise [`None`].
    pub fn get(&self, index: usize) -> Option<&Prefix> {
        self.0.get(index)
    }

    /// Returns an iterator over **all** [`Prefix`] entries.
    pub fn iter(&self) -> PrefixesIter<'_> {
        PrefixesIter(self.0.0.iter())
    }

    /// Returns the [`Prefix`] with the given `name` if present, otherwise [`None`].
    ///
    /// # See Also
    /// - [`Self::get_uri`] to retrieve the prefix [uri](Prefix::uri) directly.
    pub fn by_name(&self, name: &str) -> Option<&Prefix> {
        self.0.by_key(name)
    }

    /// Returns the [uri](Prefix::uri) of the [`Prefix`]
    /// with the given `name` if present, otherwise [`None`].
    pub fn get_uri(&self, name: &str) -> Option<&str> {
        self.0.by_key(name).map(|prefix| prefix.uri.as_str())
    }

    /// Returns `true` if a [`Prefix`] with the given `name` is present.
    pub fn has_name(&self, name: &str) -> bool {
        self.0.has_key(name)
    }
}

impl<'ebook> IntoIterator for &'ebook Prefixes {
    type Item = &'ebook Prefix;
    type IntoIter = PrefixesIter<'ebook>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// An iterator over all [`Prefix`] entries within [`Prefixes`].
///
/// # See Also
/// - [`Prefixes::iter`] to create an instance of this struct.
#[derive(Clone, Debug)]
pub struct PrefixesIter<'ebook>(std::slice::Iter<'ebook, Prefix>);

impl<'ebook> Iterator for PrefixesIter<'ebook> {
    type Item = &'ebook Prefix;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

/// A prefix, defining a mapping for use in [`property`](EpubMetaEntry::property) values.
///
/// A prefix encompasses a [`name`](Prefix::name)
/// as **key** and a [`URI`](Prefix::uri) as **value**.
///
/// # Note
/// When the `write` feature flag is enabled, only modification of the URI is allowed.
/// **The name cannot be modified once a prefix is created.**
/// This prevents duplicate keys within [`Prefixes`].
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct Prefix {
    name: String,
    uri: String,
}

impl Prefix {
    /// Internal constructor.
    ///
    /// The public constructor [`Self::new`] is available when the `write`
    /// feature is enabled.
    pub fn create(name: impl Into<String>, uri: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            uri: uri.into(),
        }
    }

    /// The prefix name/key.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The prefix URI.
    pub fn uri(&self) -> &str {
        &self.uri
    }
}

impl Keyed for Prefix {
    type Key = str;

    fn key(&self) -> &Self::Key {
        &self.name
    }
}