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
//! UTF-8 XML parsing

use crate::ebook::element::{Attribute, AttributesData};
use crate::ebook::errors::FormatError;
use crate::parser::ParserResult;
use crate::util::str::StringExt;
use quick_xml::Decoder;
use quick_xml::encoding::EncodingError;
use quick_xml::escape;
use quick_xml::events::attributes::Attribute as QuickXmlAttribute;
use quick_xml::events::{BytesCData, BytesEnd, BytesRef, BytesStart, BytesText, Event};
use std::borrow::Cow;
use std::str;

#[doc(hidden)]
impl From<EncodingError> for FormatError {
    fn from(error: EncodingError) -> Self {
        Self::Unparsable(Box::new(error))
    }
}

pub(crate) enum XmlEvent<'a> {
    /// Represent a start element:
    /// - `<start x="y"></start>`
    /// - `<start x="y"/>`
    Start(XmlStartElement<'a>),
    End(BytesEnd<'a>),
    Text(BytesText<'a>),
    CData(BytesCData<'a>),
    GeneralRef(BytesRef<'a>),
    Eof,
    /// Skipped events:
    /// - [`quick_xml::events::Comment`]
    /// - [`quick_xml::events::Decl`]
    /// - [`quick_xml::events::PI`]
    /// - [`quick_xml::events::DocType`]
    Skipped,
}

impl<'a> XmlEvent<'a> {
    fn new(ctx: XmlReaderContext, event: Event<'a>) -> Self {
        match event {
            // `Start` and `Empty` are merged for convenience.
            // - `XmlStartElement::is_self_closing` indicates if the element is empty.
            Event::Start(e) => XmlEvent::Start(XmlStartElement::new(ctx, e, false)),
            Event::Empty(e) => XmlEvent::Start(XmlStartElement::new(ctx, e, true)),
            Event::End(e) => XmlEvent::End(e),
            Event::Text(e) => XmlEvent::Text(e),
            Event::CData(e) => XmlEvent::CData(e),
            Event::GeneralRef(e) => XmlEvent::GeneralRef(e),
            Event::Eof => XmlEvent::Eof,
            _ => XmlEvent::Skipped,
        }
    }
}

#[derive(Copy, Clone, Debug)]
pub(crate) struct XmlReaderContext {
    decoder: Decoder,
    strict: bool,
}

impl XmlReaderContext {
    fn unescape_value(&self, bytes: &[u8]) -> ParserResult<String> {
        let decoded = self.decoder.decode(bytes)?;

        match escape::unescape(&decoded) {
            Ok(unescaped) => Ok(unescaped.into_owned()),
            Err(error) if self.strict => Err(FormatError::Unparsable(Box::new(error))),
            Err(_) => Ok(decoded.into_owned()),
        }
    }
}

pub(crate) struct XmlReader<'a> {
    reader: quick_xml::Reader<&'a [u8]>,
    strict: bool,
}

impl<'a> XmlReader<'a> {
    pub(crate) fn from_bytes(strict: bool, reader: &'a [u8]) -> Self {
        Self {
            reader: quick_xml::Reader::from_reader(reader),
            strict,
        }
    }

    fn ctx(&self) -> XmlReaderContext {
        XmlReaderContext {
            decoder: self.reader.decoder(),
            strict: self.strict,
        }
    }

    /// Iterator-like method to read the next [`Event`].
    pub(crate) fn next(&mut self) -> Option<ParserResult<XmlEvent<'a>>> {
        match self
            .reader
            .read_event()
            .map(|event| XmlEvent::new(self.ctx(), event))
        {
            Ok(XmlEvent::Eof) => None,
            result => Some(result.map_err(|error| FormatError::Unparsable(Box::new(error)))),
        }
    }

    /// If `event` is [`Some`], takes the [`Event`] and returns it,
    /// otherwise invokes [`Self::next`].
    ///
    /// After this call, `event` **will** have a value of [`None`].
    pub(crate) fn take_or_next(
        &mut self,
        event: &mut Option<XmlEvent<'a>>,
    ) -> Option<ParserResult<XmlEvent<'a>>> {
        event.take().map(Ok).or_else(|| self.next())
    }

    /// Retrieve all text until a designated stopping point.
    /// During the process, when the stopping point is reached,
    /// the event that caused the stop is consumed from the reader,
    /// which may need to also be read by the caller.
    ///
    /// As such, returns the [`Event`] that caused the stop and text.
    fn get_text(
        &mut self,
        mut is_stop: impl FnMut(&XmlEvent) -> bool,
    ) -> ParserResult<(Option<XmlEvent<'a>>, String)> {
        let mut value = String::new();
        let mut consumed_event = None;

        while let Some(result) = self.next() {
            let event = result?;

            if is_stop(&event) {
                value.trim_in_place();
                consumed_event.replace(event);
                break;
            }
            match event {
                XmlEvent::Text(mut text) => Self::handle_text(&mut value, &mut text)?,
                XmlEvent::CData(cdata) => Self::handle_cdata(&mut value, &cdata)?,
                XmlEvent::GeneralRef(general_ref) => {
                    self.handle_general_ref(&mut value, &general_ref)?;
                }
                _ => {}
            }
        }
        Ok((consumed_event, value))
    }

    /// Retrieve consolidated text for a specified element up to its end tag.
    pub(crate) fn get_element_text(&mut self, start: &XmlStartElement<'_>) -> ParserResult<String> {
        self.get_text(|event| matches!(event, XmlEvent::End(el) if el.name().0 == start.name()))
            .map(|(_, text)| text)
    }

    /// See [`Self::get_text`]
    pub(crate) fn get_text_till_either(
        &mut self,
        start: &[u8],
        till: &[u8],
    ) -> ParserResult<(Option<XmlEvent<'a>>, String)> {
        self.get_text(|event| {
            let predicate = |el| el == start || el == till;

            match event {
                XmlEvent::Start(el) if predicate(el.name()) => true,
                XmlEvent::End(el) if predicate(el.name().0) => true,
                _ => false,
            }
        })
    }

    fn handle_general_ref(&self, value: &mut String, general_ref: &BytesRef) -> ParserResult<()> {
        fn push_unsupported(value: &mut String, reference: &str) {
            // Unsupported custom entity/character reference
            // - This is a rare scenario if there are non-standard entities/char refs.
            // - NOTE: Despite this being a safe option when parsing,
            //   when writing back, the unresolved entity/ref will be double-escaped.
            value.push('&');
            value.push_str(reference);
            value.push(';');
        }

        if general_ref.is_char_ref() {
            match general_ref.resolve_char_ref() {
                Ok(Some(resolved)) => value.push(resolved),
                // The `None` case should never happen as
                // `is_char_ref` was called before resolving
                Ok(None) => (),
                // An invalid char ref is given
                Err(quick_xml::Error::Escape(_)) if !self.strict => {
                    push_unsupported(value, &general_ref.decode()?);
                }
                Err(error) => return Err(FormatError::Unparsable(Box::new(error))),
            }
        } else {
            let decoded = general_ref.decode()?;

            // Resolve xml/html entity
            match escape::resolve_predefined_entity(&decoded) {
                Some(resolved) => value.push_str(resolved),
                None => push_unsupported(value, &decoded),
            }
        }
        Ok(())
    }

    fn handle_cdata(value: &mut String, cdata: &BytesCData) -> ParserResult<()> {
        value.push_str(cdata.decode()?.trim());
        Ok(())
    }

    fn handle_text(value: &mut String, text: &mut BytesText) -> ParserResult<()> {
        // Determine when to add spacing
        let has_padding_start = text.try_trim_start();
        let has_padding_end = text.try_trim_end();
        let last_char = value.chars().last().unwrap_or_default();

        // Check "start" spacing
        if (text.is_empty() || has_padding_start) && last_char != ' ' {
            // Only add spacing if there's content
            if !value.is_empty() {
                // Add a space to ensure all text doesn't squeeze together
                value.push(' ');
            }
            // Return early if there is no text to process
            if text.is_empty() {
                return Ok(());
            }
        }
        let text = text.decode()?;

        // Consolidate into a single paragraph
        for text in text.lines().map(str::trim).filter(|s| !s.is_empty()) {
            value.push_str(text);
            value.push(' ');
        }
        // If there should be no end spacing, remove the last space added by the loop
        if !has_padding_end {
            value.pop();
        }
        Ok(())
    }
}

pub(crate) struct XmlStartElement<'a> {
    ctx: XmlReaderContext,
    element: BytesStart<'a>,
    is_self_closing: bool,
}

impl<'a> XmlStartElement<'a> {
    fn new(ctx: XmlReaderContext, element: BytesStart<'a>, is_self_closing: bool) -> Self {
        Self {
            ctx,
            element,
            is_self_closing,
        }
    }

    pub(crate) fn name(&self) -> &[u8] {
        self.element.name().0
    }

    pub(crate) fn name_decoded(&self) -> ParserResult<Cow<'_, str>> {
        self.ctx
            .decoder
            .decode(self.name())
            .map_err(|error| FormatError::Unparsable(Box::new(error)))
    }

    pub(crate) fn local_name(&self) -> &[u8] {
        self.element.local_name().into_inner()
    }

    pub(crate) fn is_local_name(&self, target_local_name: impl AsRef<[u8]>) -> bool {
        self.local_name() == target_local_name.as_ref()
    }

    pub(crate) fn is_prefix(&self, target_prefix: impl AsRef<[u8]>) -> bool {
        self.element
            .name()
            .prefix()
            .is_some_and(|p| p.as_ref() == target_prefix.as_ref())
    }

    pub(crate) fn is_self_closing(&self) -> bool {
        self.is_self_closing
    }

    /// Returns the raw attribute value
    pub(crate) fn get_attribute_raw(
        &self,
        key: impl AsRef<[u8]>,
    ) -> ParserResult<Option<Cow<'_, [u8]>>> {
        match self.element.try_get_attribute(key) {
            Ok(option) => Ok(option.map(|attribute| attribute.value)),
            Err(error) if self.ctx.strict => Err(FormatError::Unparsable(Box::new(error))),
            Err(_) => Ok(None),
        }
    }

    pub(crate) fn get_attribute(&self, key: impl AsRef<[u8]>) -> ParserResult<Option<String>> {
        self.get_attribute_raw(key).and_then(|value| match value {
            Some(value) => self.ctx.unescape_value(&value).map(Some),
            None => Ok(None),
        })
    }

    pub(crate) fn has_attribute(&self, key: impl AsRef<[u8]>) -> ParserResult<bool> {
        match self.element.try_get_attribute(key) {
            Ok(attribute) => Ok(attribute.is_some()),
            Err(error) if self.ctx.strict => Err(FormatError::Unparsable(Box::new(error))),
            Err(_) => Ok(false),
        }
    }

    pub(crate) fn attributes(&self) -> ParserResult<XmlAttributes<'_>> {
        let attributes = self
            .element
            .attributes()
            .filter_map(|result| match result {
                Ok(_) => Some(result),
                Err(_) if self.ctx.strict => Some(result),
                // Skip the attribute if not `strict`
                Err(_) => None,
            })
            .collect::<Result<Vec<_>, _>>()
            .map_err(|error| FormatError::Unparsable(Box::new(error)))?;

        Ok(XmlAttributes {
            ctx: self.ctx,
            attributes,
        })
    }
}

pub(crate) struct XmlAttributes<'a> {
    ctx: XmlReaderContext,
    attributes: Vec<QuickXmlAttribute<'a>>,
}

impl XmlAttributes<'_> {
    /// Removes and returns the value of the attribute by `name`.
    pub(crate) fn remove(&mut self, name: impl AsRef<[u8]>) -> ParserResult<Option<String>> {
        let name = name.as_ref();

        self.attributes
            .iter()
            .position(|attribute| attribute.key.as_ref() == name)
            .map(|i| {
                let raw = &self.attributes.swap_remove(i).value;
                self.ctx.unescape_value(raw)
            })
            .transpose()
    }
}

impl TryFrom<XmlAttributes<'_>> for AttributesData {
    type Error = FormatError;

    fn try_from(attributes: XmlAttributes<'_>) -> Result<Self, Self::Error> {
        attributes
            .attributes
            .iter()
            .map(|attribute| {
                let name = str::from_utf8(attribute.key.as_ref())
                    .map_err(|err| FormatError::Unparsable(Box::new(err)))?
                    .to_owned();
                let value = attributes.ctx.unescape_value(&attribute.value)?;
                Ok(Attribute::create(name, value))
            })
            .collect::<Result<Vec<_>, _>>()
            .map(AttributesData::from)
    }
}

pub(crate) trait XmlText {
    /// Returns `true` if the start was trimmed.
    fn try_trim_start(&mut self) -> bool;

    /// Returns `true` if the end was trimmed.
    fn try_trim_end(&mut self) -> bool;
}

impl XmlText for BytesText<'_> {
    fn try_trim_start(&mut self) -> bool {
        let before = self.len();
        self.inplace_trim_start();
        self.len() != before
    }

    fn try_trim_end(&mut self) -> bool {
        let before = self.len();
        self.inplace_trim_end();
        self.len() != before
    }
}

#[cfg(test)]
mod tests {
    use super::XmlReader;
    use quick_xml::events::BytesText;

    #[test]
    fn test_text_to_str() {
        let mut s = String::new();
        XmlReader::handle_text(
            &mut s,
            &mut BytesText::from_escaped(" \n \t \r  data1 &amp; data2  \n\r \n  \t "),
        )
        .unwrap();
        // If there is whitespace at the end, a single `space` must replace it all.
        assert_eq!("data1 &amp; data2 ", s);

        XmlReader::handle_text(&mut s, &mut BytesText::from_escaped("data3 ")).unwrap();
        assert_eq!("data1 &amp; data2 data3 ", s);

        XmlReader::handle_text(&mut s, &mut BytesText::from_escaped("  data4")).unwrap();
        assert_eq!("data1 &amp; data2 data3 data4", s);

        XmlReader::handle_text(&mut s, &mut BytesText::from_escaped("data5")).unwrap();
        assert_eq!("data1 &amp; data2 data3 data4data5", s);
    }
}