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
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
//! [`Reader`]-specific implementations for the [`Epub`] format.

use crate::epub::Epub;
use crate::epub::errors::EpubError;
use crate::epub::manifest::EpubManifestEntry;
use crate::epub::spine::EpubSpineEntry;
use crate::reader::errors::{ReaderError, ReaderResult};
use crate::reader::{Reader, ReaderContent, ReaderKey};
use crate::util::iter::IndexCursor;
use crate::util::{Sealed, doc};
use std::cmp::PartialEq;

/// A [`Reader`] for an [`Epub`].
///
/// # Configuration
/// Reading behavior, such as how to handle non-linear content,
/// can be configured using [`Epub::reader_builder`] or [`EpubReaderOptions`].
///
/// # Examples
/// - Retrieving a new EPUB reader instance with configuration:
/// ```
/// # use rbook::Epub;
/// # use rbook::epub::reader::LinearBehavior;
/// # fn main() -> rbook::ebook::errors::EbookResult<()> {
/// let epub = Epub::open("tests/ebooks/example_epub")?;
/// let mut reader = epub.reader_builder()
///     .linear_behavior(LinearBehavior::LinearOnly) // Omit non-linear readable entries
///     .create();
/// # let mut count = 0;
///
/// // Stream over all linear content
/// for content_result in &mut reader {
///     # count += 1;
///     let content = content_result?;
///     assert!(content.spine_entry().is_linear());
/// }
/// # assert_eq!(3, count);
/// # assert_eq!(count, reader.len());
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct EpubReader<'ebook> {
    entries: Vec<EpubSpineEntry<'ebook>>,
    cursor: IndexCursor,
}

impl<'ebook> EpubReader<'ebook> {
    pub(super) fn new(epub: &'ebook Epub, config: &EpubReaderConfig) -> Self {
        let entries = Self::get_entries(epub, config.linear_behavior);

        EpubReader {
            cursor: IndexCursor::new(entries.len()),
            entries,
        }
    }

    // If and when EpubReader grows, this method will be extracted to a submodule.
    fn get_entries(epub: &'ebook Epub, behavior: LinearBehavior) -> Vec<EpubSpineEntry<'ebook>> {
        let iterator = epub.spine().iter();
        match behavior {
            LinearBehavior::Original => iterator.collect(),
            LinearBehavior::LinearOnly | LinearBehavior::NonLinearOnly => {
                let predicate = behavior == LinearBehavior::LinearOnly;
                iterator
                    .filter(|entry| entry.is_linear() == predicate)
                    .collect()
            }
            LinearBehavior::PrependNonLinear | LinearBehavior::AppendNonLinear => {
                let (mut linear, mut non_linear) =
                    iterator.partition::<Vec<_>, _>(EpubSpineEntry::is_linear);

                if matches!(&behavior, LinearBehavior::AppendNonLinear) {
                    linear.extend(non_linear);
                    linear
                } else {
                    non_linear.extend(linear);
                    non_linear
                }
            }
        }
    }

    fn get_manifest_entry(
        spine_entry: EpubSpineEntry<'ebook>,
    ) -> ReaderResult<EpubManifestEntry<'ebook>> {
        spine_entry.manifest_entry().ok_or_else(|| {
            ReaderError::Format(EpubError::InvalidIdref(spine_entry.idref().to_owned()).into())
        })
    }

    fn find_entry_by_idref(&self, idref: &str) -> ReaderResult<usize> {
        self.entries
            .iter()
            .position(|entry| entry.idref() == idref)
            .ok_or_else(|| ReaderError::NoMapping(idref.to_string()))
    }

    fn find_entry_by_position(&self, position: usize) -> ReaderResult<EpubReaderContent<'ebook>> {
        let spine_entry = self.entries[position];
        let manifest_entry = Self::get_manifest_entry(spine_entry)?;

        Self::create_reader_content(position, spine_entry, manifest_entry)
    }

    fn find_entry_by_str(&self, idref: &str) -> ReaderResult<(usize, EpubReaderContent<'ebook>)> {
        let position = self.find_entry_by_idref(idref)?;
        let spine_entry = self.entries[position];
        let manifest_entry = Self::get_manifest_entry(spine_entry)?;

        Ok((
            position,
            Self::create_reader_content(position, spine_entry, manifest_entry)?,
        ))
    }

    fn create_reader_content(
        position: usize,
        spine_entry: EpubSpineEntry<'ebook>,
        manifest_entry: EpubManifestEntry<'ebook>,
    ) -> ReaderResult<EpubReaderContent<'ebook>> {
        Ok(EpubReaderContent {
            content: manifest_entry.read_str()?,
            position,
            spine_entry,
            manifest_entry,
        })
    }

    /// Resets the reader's cursor to its initial state; before the first entry.
    #[doc = doc::inherent!(Reader, reset)]
    pub fn reset(&mut self) {
        self.cursor.reset();
    }

    /// Returns the next [`EpubReaderContent`] and increments the reader's cursor by one.
    #[doc = doc::inherent!(Reader, read_next)]
    pub fn read_next(&mut self) -> Option<ReaderResult<EpubReaderContent<'ebook>>> {
        self.cursor
            .increment()
            .map(|index| self.find_entry_by_position(index))
    }

    /// Returns the previous [`EpubReaderContent`] and decrements the reader's cursor by one.
    #[doc = doc::inherent!(Reader, read_prev)]
    pub fn read_prev(&mut self) -> Option<ReaderResult<EpubReaderContent<'ebook>>> {
        self.cursor
            .decrement()
            .map(|index| self.find_entry_by_position(index))
    }

    /// Returns the [`EpubReaderContent`] that the reader's cursor is currently positioned at.
    #[doc = doc::inherent!(Reader, read_current)]
    pub fn read_current(&self) -> Option<ReaderResult<EpubReaderContent<'ebook>>> {
        self.current_position()
            .map(|position| self.find_entry_by_position(position))
    }

    /// Returns the [`EpubReaderContent`] at the given [`ReaderKey`]
    /// and moves the reader’s cursor to that position.
    #[doc = doc::inherent!(Reader, read)]
    pub fn read<'a>(
        &mut self,
        key: impl Into<ReaderKey<'a>>,
    ) -> ReaderResult<EpubReaderContent<'ebook>> {
        match key.into() {
            ReaderKey::Value(idref) => {
                let (index, content) = self.find_entry_by_str(idref)?;
                self.cursor.set(index);
                Ok(content)
            }
            ReaderKey::Position(index) if index < self.entries.len() => {
                let content = self.find_entry_by_position(index);
                self.cursor.set(index);
                content
            }
            ReaderKey::Position(index) => Err(ReaderError::OutOfBounds {
                position: index,
                len: self.entries.len(),
            }),
        }
    }

    /// Moves the reader’s cursor to the given [`ReaderKey`]
    /// and returns the resulting cursor position.
    #[doc = doc::inherent!(Reader, seek)]
    pub fn seek<'a>(&mut self, key: impl Into<ReaderKey<'a>>) -> ReaderResult<usize> {
        match key.into() {
            ReaderKey::Value(idref) => {
                let index = self.find_entry_by_idref(idref)?;
                self.cursor.set(index);
                Ok(index)
            }
            ReaderKey::Position(index) if index < self.entries.len() => {
                self.cursor.set(index);
                Ok(index)
            }
            ReaderKey::Position(index) => Err(ReaderError::OutOfBounds {
                position: index,
                len: self.entries.len(),
            }),
        }
    }

    /// Returns the [`EpubReaderContent`] at the given [`ReaderKey`]
    /// without moving the reader's cursor.
    #[doc = doc::inherent!(Reader, get)]
    pub fn get<'a>(
        &self,
        key: impl Into<ReaderKey<'a>>,
    ) -> ReaderResult<EpubReaderContent<'ebook>> {
        match key.into() {
            ReaderKey::Value(manifest_id) => self
                .find_entry_by_str(manifest_id)
                .map(|(_, content)| content),
            ReaderKey::Position(index) => self.find_entry_by_position(index),
        }
    }

    /// The total number of traversable [`EpubReaderContent`] entries.
    #[doc = doc::inherent!(Reader, len)]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// The position of the reader’s cursor (current entry).
    #[doc = doc::inherent!(Reader, current_position)]
    pub fn current_position(&self) -> Option<usize> {
        self.cursor.index()
    }

    /// The total number of remaining traversable [`EpubReaderContent`]
    /// until the reader's cursor reaches the end.
    #[doc = doc::inherent!(Reader, remaining)]
    pub fn remaining(&self) -> usize {
        Reader::remaining(self)
    }

    /// Returns `true` if the reader has no [`EpubReaderContent`] to provide;
    /// a [length](EpubReader::len) of `0`.
    #[doc = doc::inherent!(Reader, is_empty)]
    pub fn is_empty(&self) -> bool {
        Reader::is_empty(self)
    }
}

impl Sealed for EpubReader<'_> {}

#[allow(refining_impl_trait)]
impl<'ebook> Reader<'ebook> for EpubReader<'ebook> {
    fn reset(&mut self) {
        self.reset();
    }

    fn read_next(&mut self) -> Option<ReaderResult<EpubReaderContent<'ebook>>> {
        self.read_next()
    }

    fn read_prev(&mut self) -> Option<ReaderResult<EpubReaderContent<'ebook>>> {
        self.read_prev()
    }

    fn read_current(&self) -> Option<ReaderResult<EpubReaderContent<'ebook>>> {
        self.read_current()
    }

    fn read<'a>(
        &mut self,
        key: impl Into<ReaderKey<'a>>,
    ) -> ReaderResult<EpubReaderContent<'ebook>> {
        self.read(key)
    }

    fn seek<'a>(&mut self, key: impl Into<ReaderKey<'a>>) -> ReaderResult<usize> {
        self.seek(key)
    }

    fn get<'a>(&self, key: impl Into<ReaderKey<'a>>) -> ReaderResult<EpubReaderContent<'ebook>> {
        self.get(key)
    }

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

    fn current_position(&self) -> Option<usize> {
        self.current_position()
    }
}

impl<'ebook> Iterator for EpubReader<'ebook> {
    type Item = ReaderResult<EpubReaderContent<'ebook>>;

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

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.remaining();

        (remaining, Some(remaining))
    }
}

/// [`ReaderContent`] implementation for an [`EpubReader`].
#[derive(Clone, Debug, PartialEq)]
pub struct EpubReaderContent<'ebook> {
    content: String,
    position: usize,
    spine_entry: EpubSpineEntry<'ebook>,
    manifest_entry: EpubManifestEntry<'ebook>,
}

impl<'ebook> EpubReaderContent<'ebook> {
    /// The position of reader content within an [`EpubReader`] (0-index-based).
    #[doc = doc::inherent!(ReaderContent, position)]
    pub fn position(&self) -> usize {
        self.position
    }

    /// The readable content (e.g., `XHTML`, `HTML`, etc.).
    #[doc = doc::inherent!(ReaderContent, content)]
    pub fn content(&self) -> &str {
        self.content.as_str()
    }

    /// The associated [`EpubSpineEntry`] containing reading order details.
    #[doc = doc::inherent!(ReaderContent, spine_entry)]
    pub fn spine_entry(&self) -> EpubSpineEntry<'ebook> {
        self.spine_entry
    }

    /// The associated [`EpubManifestEntry`] containing resource details.
    #[doc = doc::inherent!(ReaderContent, manifest_entry)]
    pub fn manifest_entry(&self) -> EpubManifestEntry<'ebook> {
        self.manifest_entry
    }

    /// Takes the contained readable content string.
    #[doc = doc::inherent!(ReaderContent, into_string)]
    pub fn into_string(self) -> String {
        ReaderContent::into_string(self)
    }

    /// Takes the contained readable content bytes.
    #[doc = doc::inherent!(ReaderContent, into_bytes)]
    pub fn into_bytes(self) -> Vec<u8> {
        ReaderContent::into_bytes(self)
    }
}

impl Sealed for EpubReaderContent<'_> {}

#[allow(refining_impl_trait)]
impl<'ebook> ReaderContent<'ebook> for EpubReaderContent<'ebook> {
    fn position(&self) -> usize {
        self.position()
    }

    fn content(&self) -> &str {
        self.content()
    }

    fn spine_entry(&self) -> EpubSpineEntry<'ebook> {
        self.spine_entry()
    }

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

impl<'ebook> From<EpubReaderContent<'ebook>> for String {
    fn from(value: EpubReaderContent<'ebook>) -> Self {
        value.content
    }
}

impl<'ebook> From<EpubReaderContent<'ebook>> for Vec<u8> {
    fn from(value: EpubReaderContent<'ebook>) -> Self {
        value.content.into_bytes()
    }
}

/// Indicates arrangement/omission of `linear` and `non-linear` spine content
/// within an [`Epub`].
///
/// # See Also
/// - [`EpubSpineEntry::is_linear`] for the difference between `linear` and `non-linear` content.
///
/// Default: [`LinearBehavior::Original`]
#[derive(Copy, Clone, Debug, Default, Hash, PartialEq, Eq)]
pub enum LinearBehavior {
    /// `Linear` and `non-linear` content is retained in the original order
    /// written in the [`EpubSpine`](super::spine::EpubSpine).
    #[default]
    Original,
    /// Only `linear` content is retained; `non-linear` content is omitted.
    ///
    /// Content: `[linear…]`
    LinearOnly,
    /// Only `non-linear` content is retained; `linear` content is omitted.
    ///
    /// Content: `[non_linear…]`
    NonLinearOnly,
    /// `non-linear` content is prepended before `linear` content.
    ///
    /// Content: `[non_linear…, linear…]`
    PrependNonLinear,
    /// `non-linear` content is appended after `linear` content.
    ///
    /// Content: `[linear…, non_linear…]`
    AppendNonLinear,
}

#[derive(Clone, Debug)]
pub(super) struct EpubReaderConfig {
    /// See [`EpubReaderOptions::linear_behavior`]
    linear_behavior: LinearBehavior,
}

impl Default for EpubReaderConfig {
    fn default() -> Self {
        Self {
            linear_behavior: LinearBehavior::Original,
        }
    }
}

/// Configuration to create an [`EpubReader`].
///
/// `EpubReaderOptions` supports two usage patterns:
/// 1. **Attached**:
///    Created via [`Epub::reader_builder`].
///    The options are bound to a specific [`Epub`].
///    Terminal methods (e.g., [`create`](EpubReaderOptions::<&Epub>::create)) consume the builder.
/// 2. **Detached**:
///    Created via [`EpubReaderOptions::default`].
///    The options are standalone.
///    Terminal methods take `&self`
///    (e.g., [`create`](EpubReaderOptions::create)),
///    and a reference to an [`Epub`], allowing the same configuration to be reused multiple times.
///
/// # Options
/// ## Ordering
/// - [`linear_behavior`](EpubReaderOptions::linear_behavior)
///   (Default: [`LinearBehavior::Original`])
///
/// # See Also
/// - [`Epub::reader_builder`] to create an [`EpubReader`] directly from an [`Epub`].
/// - [`EpubReaderOptions::default`] to create multiple [`EpubReader`] instances with identical options.
///
/// # Examples
/// - Creating an [`EpubReader`] (Attached):
/// ```
/// # use rbook::Epub;
/// # use rbook::epub::reader::LinearBehavior;
/// # fn main() -> rbook::ebook::errors::EbookResult<()> {
/// let epub = Epub::open("tests/ebooks/example_epub")?;
/// let mut reader = epub.reader_builder() // returns EpubReaderOptions
///     .linear_behavior(LinearBehavior::AppendNonLinear)
///     .create();
/// # Ok(())
/// # }
/// ```
/// - Creating multiple [`EpubReader`] instances (Detached):
/// ```
/// # use rbook::Epub;
/// # use rbook::epub::reader::{EpubReaderOptions, LinearBehavior};
/// # fn main() -> rbook::ebook::errors::EbookResult<()> {
/// let epub = Epub::open("tests/ebooks/example_epub")?;
/// let reader_options = EpubReaderOptions::new()
///     .linear_behavior(LinearBehavior::PrependNonLinear);
///
/// let mut reader_a = reader_options.create(&epub);
/// let mut reader_b = reader_options.create(&epub);
/// let mut reader_c = reader_options.create(&epub);
///
/// // All have the same applied options and initial state
/// assert_eq!(reader_a, reader_b);
/// assert_eq!(reader_b, reader_c);
/// # Ok(())
/// # }
/// ```
#[non_exhaustive]
#[derive(Clone, Debug, Default)]
pub struct EpubReaderOptions<T = ()> {
    container: T,
    config: EpubReaderConfig,
}

impl<T> EpubReaderOptions<T> {
    /// How `linear` and `non-linear` spine content are handled.
    ///
    /// Through this setting, content can be re-arranged or omitted
    /// depending on the selected [`LinearBehavior`].
    ///
    /// Default: [`LinearBehavior::Original`]
    pub fn linear_behavior(mut self, linear_behavior: LinearBehavior) -> Self {
        self.config.linear_behavior = linear_behavior;
        self
    }
}

impl<'ebook> EpubReaderOptions<&'ebook Epub> {
    pub(super) fn new(epub: &'ebook Epub) -> Self {
        Self {
            container: epub,
            config: EpubReaderConfig::default(),
        }
    }

    /// Consume this builder and create an [`EpubReader`].
    pub fn create(self) -> EpubReader<'ebook> {
        EpubReader::new(self.container, &self.config)
    }
}

impl EpubReaderOptions {
    /// Creates a new builder with default values.
    ///
    /// # See Also
    /// - [`Epub::reader_builder`] to build an [`EpubReader`] directly from an [`Epub`]
    pub fn new() -> Self {
        Self::default()
    }

    /// Consume this builder and create an [`EpubReader`] associated with the given [`Epub`].
    pub fn create<'ebook>(&self, epub: &'ebook Epub) -> EpubReader<'ebook> {
        EpubReader::new(epub, &self.config)
    }
}