summaryrefslogtreecommitdiff
path: root/src/emphasis.rs
blob: 12502adf0b0a5d2d6e3dd526487841db1cdabc05 (plain)
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
//! Emphasis.
use crate::xml::element::Tagged;

/// Emphasis.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Emphasis
{
    /// The emphasised text.
    pub text: String,

    /// Emphasis role.
    pub role: Role,
}

impl Emphasis
{
    pub(crate) fn from_tagged_element(tagged_element: &Tagged) -> Result<Self, Error>
    {
        return Ok(Emphasis {
            text: tagged_element
                .child_elements()
                .get_first_text_element()
                .cloned()
                .unwrap_or_default(),
            role: tagged_element
                .attributes()
                .iter()
                .find(|attr| attr.key == "role")
                .map(|attr| {
                    let value = String::from_utf8(attr.value.clone())
                        .map_err(|_| Error::EmphasisRoleNotUTF8)?;

                    if value == "bold" {
                        return Ok(Role::Bold);
                    }

                    Err(Error::UnknownEmphasisRole(value))
                })
                .unwrap_or(Ok(Role::None))?,
        });
    }
}

/// [`Emphasis`] error.
#[derive(Debug, thiserror::Error)]
pub enum Error
{
    /// Emphasis role is not valid UTF-8.
    #[error("Emphasis role is not valid UTF-8")]
    EmphasisRoleNotUTF8,

    /// Unknown emphasis role.
    #[error("Unknown emphasis role '{0}'")]
    UnknownEmphasisRole(String),
}

/// Emphasis role.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Role
{
    /// Bold.
    Bold,

    /// None.
    None,
}