summaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: 8e9e1e713d354ad3fe1007342c5decc31542e779 (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
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
//! Rust API for the [OpenGL reference page sources].
//!
//! [OpenGL reference page sources]: https://github.com/KhronosGroup/OpenGL-Refpages
#![cfg_attr(doc_cfg, feature(doc_cfg))]
#![deny(clippy::all, clippy::pedantic, missing_docs)]

use std::os::unix::prelude::OsStrExt;

use include_dir::{include_dir, Dir};

use crate::description::{Description, Error as DescriptionError};
use crate::xml::element::{Attribute, Elements, FromElements};
use crate::xml::parser::{Error as ParserError, Parser};

pub mod description;

mod util;
mod xml;

static GL4_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/OpenGL-Refpages/gl4");

/// Reference entry.
#[derive(Debug)]
pub struct ReferenceEntry
{
    purpose: String,
    description: Description,
}

impl ReferenceEntry
{
    /// Returns a function reference entry.
    ///
    /// # Errors
    /// Returns `Err` if
    /// - No reference entry file was found.
    /// - Parsing the reference entry file data fails.
    /// - The reference entry file data is invalid.
    pub fn get_function(function_name: &str) -> Result<Self, ReferenceEntryError>
    {
        let function_file = GL4_DIR
            .files()
            .find_map(|file| {
                if file.path().extension()?.as_bytes() != b"xml" {
                    return None;
                }

                if function_name.starts_with(file.path().file_stem()?.to_str()?) {
                    Some(file)
                } else {
                    None
                }
            })
            .ok_or_else(|| ReferenceEntryError::NoFileFound(function_name.to_string()))?;

        let function_ref_content = function_file.contents();

        let mut parser = Parser::new(function_ref_content);

        let root_elements = parser.parse()?;

        ReferenceEntry::from_elements(&root_elements)
    }

    /// Returns the reference entry purpose.
    #[must_use]
    pub fn purpose(&self) -> &str
    {
        &self.purpose
    }

    /// Returns the reference entry description.
    #[must_use]
    pub fn description(&self) -> &Description
    {
        &self.description
    }
}

impl FromElements for ReferenceEntry
{
    type Error = ReferenceEntryError;

    fn from_elements(elements: &Elements) -> Result<Self, Self::Error>
    {
        let refentry_element = elements
            .get_first_tagged_with_name("refentry")
            .ok_or(ReferenceEntryError::MissingRefEntry)?;

        let refnamediv_element = refentry_element
            .child_elements()
            .get_first_tagged_with_name("refnamediv")
            .ok_or(ReferenceEntryError::MissingRefNameDiv)?;

        let refpurpose_element = refnamediv_element
            .child_elements()
            .get_first_tagged_with_name("refpurpose")
            .ok_or(ReferenceEntryError::MissingRefPurpose)?;

        let purpose = refpurpose_element
            .child_elements()
            .get_first_text_element()
            .cloned()
            .unwrap_or_default();

        let description_refsect = refentry_element
            .child_elements()
            .get_first_tagged_with_name_and_attr(
                "refsect1",
                &Attribute {
                    key: "xml:id".to_string(),
                    value: b"description".to_vec(),
                },
            )
            .ok_or(ReferenceEntryError::MissingDescriptionRefSect)?;

        let description =
            Description::from_elements(description_refsect.child_elements())?;

        Ok(ReferenceEntry {
            purpose,
            description,
        })
    }
}

/// [`ReferenceEntry`] error.
#[derive(Debug, thiserror::Error)]
pub enum ReferenceEntryError
{
    /// No reference entry file was found.
    #[error("No reference entry file was found for '{0}'")]
    NoFileFound(String),

    /// No 'refentry' element was found.
    #[error("No 'refentry' element was found")]
    MissingRefEntry,

    /// No 'refnamediv' element was found.
    #[error("No 'refnamediv' element was found")]
    MissingRefNameDiv,

    /// No 'refpurpose' element was found.
    #[error("No 'refpurpose' element was found")]
    MissingRefPurpose,

    /// No 'refsect1' element was found with id 'description''.
    #[error("No 'refsect1' element was found with id 'description'")]
    MissingDescriptionRefSect,

    /// Invalid description.
    #[error("Invalid description")]
    InvalidDescription(#[from] DescriptionError),

    /// Parsing failed.
    #[error("Parsing failed")]
    ParsingFailed(#[from] ParserError),
}