rbook 0.7.4

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
//! EPUB-specific spine content.
//!
//! # See Also
//! - [`ebook::spine`](crate::ebook::spine) for the general spine module.

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

use crate::ebook::element::{Attributes, AttributesData, Properties, PropertiesData};
use crate::ebook::resource::Resource;
use crate::ebook::spine::{PageDirection, Spine, SpineEntry};
use crate::epub::manifest::{EpubManifestContext, EpubManifestEntry};
use crate::epub::metadata::{EpubRefinements, EpubRefinementsData};
use crate::epub::package::EpubPackageMetaContext;
use crate::util::{Sealed, doc};
use std::fmt::Debug;

#[cfg(feature = "write")]
pub use write::{DetachedEpubSpineEntry, EpubSpineEntryMut, EpubSpineIterMut, EpubSpineMut};

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

#[derive(Debug, PartialEq)]
pub(super) struct EpubSpineData {
    pub(super) page_direction: PageDirection,
    pub(super) entries: Vec<EpubSpineEntryData>,
}

impl EpubSpineData {
    pub(super) fn new(page_direction: PageDirection, entries: Vec<EpubSpineEntryData>) -> Self {
        Self {
            page_direction,
            entries,
        }
    }

    pub(super) fn empty() -> Self {
        Self {
            page_direction: PageDirection::Default,
            entries: Vec::new(),
        }
    }
}

#[derive(Clone, Debug, Default, PartialEq)]
pub(super) struct EpubSpineEntryData {
    pub(super) id: Option<String>,
    pub(super) idref: String,
    pub(super) linear: bool,
    pub(super) properties: PropertiesData,
    pub(super) attributes: AttributesData,
    pub(super) refinements: EpubRefinementsData,
}

#[derive(Copy, Clone)]
pub(super) struct EpubSpineContext<'ebook> {
    manifest_ctx: EpubManifestContext<'ebook>,
    meta_ctx: EpubPackageMetaContext<'ebook>,
}

impl<'ebook> EpubSpineContext<'ebook> {
    pub(super) fn new(
        manifest_ctx: EpubManifestContext<'ebook>,
        meta_ctx: EpubPackageMetaContext<'ebook>,
    ) -> Self {
        Self {
            manifest_ctx,
            meta_ctx,
        }
    }

    pub(super) fn create_entry(
        self,
        data: &'ebook EpubSpineEntryData,
        index: usize,
    ) -> EpubSpineEntry<'ebook> {
        EpubSpineEntry {
            ctx: self,
            data,
            index,
        }
    }
}

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

/// The EPUB spine, accessible via [`Epub::spine`](super::Epub::spine).
/// See [`Spine`] for more details.
///
/// # See Also
/// - [`EpubSpineMut`] for a mutable view.
#[derive(Copy, Clone)]
pub struct EpubSpine<'ebook> {
    ctx: EpubSpineContext<'ebook>,
    spine: &'ebook EpubSpineData,
}

impl<'ebook> EpubSpine<'ebook> {
    pub(super) fn new(
        manifest_ctx: EpubManifestContext<'ebook>,
        meta_ctx: EpubPackageMetaContext<'ebook>,
        spine: &'ebook EpubSpineData,
    ) -> Self {
        Self {
            ctx: EpubSpineContext::new(manifest_ctx, meta_ctx),
            spine,
        }
    }

    /// Returns the [`EpubSpineEntry`] matching the given `id`, or [`None`] if not found.
    ///
    /// # See Also
    /// - [`Self::by_idref`] to retrieve spine entries by the [`id`](EpubManifestEntry::id)
    ///   of an [`EpubManifestEntry`].
    ///
    /// # Examples
    /// - Retrieving a spine entry by its ID:
    /// ```
    /// # use rbook::Epub;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    ///
    /// let spine_entry = epub.spine().by_id("supplementary").unwrap();
    /// assert_eq!(Some("supplementary"), spine_entry.id());
    /// assert_eq!(3, spine_entry.order());
    ///
    /// // Attempt to retrieve a non-existent entry
    /// assert_eq!(None, epub.spine().by_id("end"));
    /// # Ok(())
    /// # }
    /// ```
    pub fn by_id(&self, id: &str) -> Option<EpubSpineEntry<'ebook>> {
        self.spine
            .entries
            .iter()
            .enumerate()
            .find(|(_, data)| data.id.as_deref() == Some(id))
            .map(|(i, data)| self.ctx.create_entry(data, i))
    }

    /// Returns an iterator over all entries matching the given `idref`.
    ///
    /// An [`idref`](EpubSpineEntry::idref) is the [`id`](EpubManifestEntry::id) of a
    /// [`EpubManifestEntry`] referenced by a spine entry.
    ///
    /// Albeit uncommon, more than one spine entry can reference the same manifest entry.
    ///
    /// # Examples
    /// - Retrieving a spine entry by its idref:
    /// ```
    /// # use rbook::Epub;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    ///
    /// let spine_entry = epub.spine().by_idref("c1").next().unwrap();
    /// assert_eq!("c1", spine_entry.idref());
    /// assert_eq!(2, spine_entry.order());
    ///
    /// // Attempt to retrieve a non-existent entry
    /// assert_eq!(None, epub.spine().by_idref("c999").next());
    /// # Ok(())
    /// # }
    /// ```
    pub fn by_idref(
        &self,
        idref: &'ebook str,
    ) -> impl Iterator<Item = EpubSpineEntry<'ebook>> + 'ebook {
        let ctx = self.ctx;

        self.spine
            .entries
            .iter()
            .enumerate()
            .filter(move |(_, data)| data.idref == idref)
            .map(move |(i, data)| ctx.create_entry(data, i))
    }

    /// The [`PageDirection`] hint, indicating how readable content flows.
    #[doc = doc::inherent!(Spine, page_direction)]
    pub fn page_direction(&self) -> PageDirection {
        self.spine.page_direction
    }

    /// The total number of [entries](EpubSpineEntry) that makes up the spine.
    #[doc = doc::inherent!(Spine, len)]
    pub fn len(&self) -> usize {
        self.spine.entries.len()
    }

    /// Returns `true` if there are no [entries](EpubSpineEntry).
    #[doc = doc::inherent!(Spine, is_empty)]
    pub fn is_empty(&self) -> bool {
        Spine::is_empty(self)
    }

    /// Returns the associated [`EpubSpineEntry`] if the given `index` is less than
    /// [`Self::len`], otherwise [`None`].
    #[doc = doc::inherent!(Spine, get)]
    pub fn get(&self, index: usize) -> Option<EpubSpineEntry<'ebook>> {
        self.spine
            .entries
            .get(index)
            .map(|data| self.ctx.create_entry(data, index))
    }

    /// Returns an iterator over all [entries](EpubSpineEntry) within
    /// the spine in canonical order.
    #[doc = doc::inherent!(Spine, iter)]
    pub fn iter(&self) -> EpubSpineIter<'ebook> {
        EpubSpineIter {
            ctx: self.ctx,
            iter: self.spine.entries.iter().enumerate(),
        }
    }
}

impl Sealed for EpubSpine<'_> {}

#[allow(refining_impl_trait)]
impl<'ebook> Spine<'ebook> for EpubSpine<'ebook> {
    fn page_direction(&self) -> PageDirection {
        self.page_direction()
    }

    fn len(&self) -> usize {
        self.len()
    }

    fn get(&self, order: usize) -> Option<EpubSpineEntry<'ebook>> {
        self.get(order)
    }

    fn iter(&self) -> EpubSpineIter<'ebook> {
        self.iter()
    }
}

impl Debug for EpubSpine<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EpubSpine")
            .field("data", self.spine)
            .finish_non_exhaustive()
    }
}

impl PartialEq for EpubSpine<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.spine == other.spine
    }
}

impl<'ebook> IntoIterator for &EpubSpine<'ebook> {
    type Item = EpubSpineEntry<'ebook>;
    type IntoIter = EpubSpineIter<'ebook>;

    fn into_iter(self) -> EpubSpineIter<'ebook> {
        self.iter()
    }
}

impl<'ebook> IntoIterator for EpubSpine<'ebook> {
    type Item = EpubSpineEntry<'ebook>;
    type IntoIter = EpubSpineIter<'ebook>;

    fn into_iter(self) -> EpubSpineIter<'ebook> {
        self.iter()
    }
}

/// An iterator over all the [entries](EpubSpineEntry) contained within [`EpubSpine`].
///
/// # See Also
/// - [`EpubSpine::iter`] to create an instance of this struct.
///
/// # Examples
/// - Iterating over all manifest entries:
/// ```
/// # use rbook::Epub;
/// # fn main() -> rbook::ebook::errors::EbookResult<()> {
/// let epub = Epub::open("tests/ebooks/example_epub")?;
///
/// for entry in epub.spine() {
///     // process entry //
/// }
/// # Ok(())
/// # }
/// ```
pub struct EpubSpineIter<'ebook> {
    ctx: EpubSpineContext<'ebook>,
    iter: std::iter::Enumerate<std::slice::Iter<'ebook, EpubSpineEntryData>>,
}

impl<'ebook> Iterator for EpubSpineIter<'ebook> {
    type Item = EpubSpineEntry<'ebook>;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter
            .next()
            .map(|(i, data)| self.ctx.create_entry(data, i))
    }

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

/// An entry contained within an [`EpubSpine`], encompassing associated metadata.
///
/// # See Also
/// - [`EpubSpineEntryMut`] for a mutable view.
#[derive(Copy, Clone)]
pub struct EpubSpineEntry<'ebook> {
    ctx: EpubSpineContext<'ebook>,
    data: &'ebook EpubSpineEntryData,
    index: usize,
}

impl<'ebook> EpubSpineEntry<'ebook> {
    /// The unique ID of a spine entry.
    pub fn id(&self) -> Option<&'ebook str> {
        self.data.id.as_deref()
    }

    /// The unique ID reference to an [`EpubManifestEntry`] in the
    /// [`EpubManifest`](super::EpubManifest).
    ///
    /// For direct access to the resource, [`Self::resource`] or
    /// [`Self::manifest_entry`] is preferred.
    pub fn idref(&self) -> &'ebook str {
        &self.data.idref
    }

    /// Returns `true` if a spine entry’s `linear` attribute is `yes`
    /// (or is not specified).    
    ///
    /// When `true`, the entry is part of the default reading order.
    /// Otherwise, it is identified as supplementary content,
    /// which may be skipped or treated differently by applications.
    ///
    /// Regarding an [`EpubReader`](super::EpubReader), linear and non-linear content
    /// is shown in the exact order as written in the spine.
    /// This behavior can be changed through
    /// [`EpubReaderOptions::linear_behavior`](super::EpubReaderOptions::linear_behavior).
    pub fn is_linear(&self) -> bool {
        self.data.linear
    }

    /// The [`Properties`] associated with a spine entry.
    ///
    /// While not limited to, potential contained property values are:
    /// - `page-spread-left`
    /// - `page-spread-right`
    /// - `rendition:page-spread-left`
    /// - `rendition:page-spread-right`
    /// - `rendition:page-spread-center`
    ///
    /// See the specification for more details regarding properties:
    /// <https://www.w3.org/TR/epub/#app-itemref-properties-vocab>
    pub fn properties(&self) -> &'ebook Properties {
        &self.data.properties
    }

    /// All additional XML [`Attributes`].
    ///
    /// # Omitted Attributes
    /// The following attributes will not be found within the returned collection:
    /// - [`id`](Self::id)
    /// - [`idref`](Self::idref)
    /// - [`linear`](Self::is_linear)
    /// - [`properties`](Self::properties)
    pub fn attributes(&self) -> &'ebook Attributes {
        &self.data.attributes
    }

    /// Complementary refinement metadata entries.
    pub fn refinements(&self) -> EpubRefinements<'ebook> {
        self.ctx
            .meta_ctx
            .create_refinements(self.id(), &self.data.refinements)
    }

    /// The canonical order of an entry (`0 = first entry`).
    #[doc = doc::inherent!(SpineEntry, order)]
    pub fn order(&self) -> usize {
        self.index
    }

    /// The [`EpubManifestEntry`] associated with a [`EpubSpineEntry`].
    #[doc = doc::inherent!(SpineEntry, manifest_entry)]
    pub fn manifest_entry(&self) -> Option<EpubManifestEntry<'ebook>> {
        self.ctx.manifest_ctx.by_id(self.idref())
    }

    /// The textual [`Resource`] intended for end-user reading an entry points to.
    #[doc = doc::inherent!(SpineEntry, resource)]
    pub fn resource(&self) -> Option<Resource<'ebook>> {
        SpineEntry::resource(self)
    }
}

impl Sealed for EpubSpineEntry<'_> {}

#[allow(refining_impl_trait)]
impl<'ebook> SpineEntry<'ebook> for EpubSpineEntry<'ebook> {
    fn order(&self) -> usize {
        self.order()
    }

    fn manifest_entry(&self) -> Option<EpubManifestEntry<'ebook>> {
        self.manifest_entry()
    }
}

impl Debug for EpubSpineEntry<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EpubSpineEntry")
            .field("data", self.data)
            .finish_non_exhaustive()
    }
}

impl PartialEq for EpubSpineEntry<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data
    }
}