aboutsummaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: 4e33f8c0ce273a53a3fb85f55d6daa4398fa0060 (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
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
//! Rust API for the [OpenGL API and Extension Registry].
//!
//! # Usage
//! ```
//! use opengl_registry::Registry;
//!
//! let registry = Registry::retrieve().unwrap();
//!
//! for command in registry.commands() {
//!     println!("Command {}", command.prototype().name());
//!     println!("  Return type: {}", command.prototype().return_type());
//!     println!("  Parameters:");
//!
//!     for param in command.parameters() {
//!         println!("  {} {}", param.get_type(), param.name());
//!     }
//! }
//! ```
//!
//! [OpenGL API and Extension Registry]: https://github.com/KhronosGroup/OpenGL-Registry
#![cfg_attr(doc_cfg, feature(doc_cfg))]
#![deny(clippy::all, clippy::pedantic, missing_docs)]

use std::fs::File;
use std::io::Read;

use quick_xml::events::BytesStart;

use crate::api_interface_definition::APIInterfaceDefinition;
use crate::command::{Command, Error as CommandError};
use crate::deserialization::buffer_deserializer::BufferDeserializer;
use crate::deserialization::{Deserialize, Deserializer, DeserializerError, IgnoreEnd};

pub mod api_interface_definition;
pub mod command;

mod deserialization;

/// XML.
#[cfg(feature = "include-xml")]
const GL_REGISTRY_XML: &[u8] = include_bytes!("../OpenGL-Registry/xml/gl.xml");

const REGISTRY_TAG_NAME: &str = "registry";

/// Representation of the OpenGL registry.
#[derive(Debug, PartialEq, Eq)]
pub struct Registry
{
    commands: Vec<Command>,
    api_interface_definitions: Vec<APIInterfaceDefinition>,
}

impl Registry
{
    /// Retrieves the OpenGL registry from a included XML file.
    ///
    /// # Errors
    /// Returns `Err` if parsing fails in any way.
    #[cfg(feature = "include-xml")]
    #[cfg_attr(doc_cfg, doc(cfg(feature = "include-xml")))]
    pub fn retrieve() -> Result<Registry, RegistryError>
    {
        Self::retrieve_from_bytes(GL_REGISTRY_XML)
    }

    /// Retrieves the OpenGL registry from XML bytes.
    ///
    /// # Errors
    /// Returns `Err` if parsing fails in any way.
    pub fn retrieve_from_bytes(xml_bytes: &[u8]) -> Result<Registry, RegistryError>
    {
        let mut deserializer = BufferDeserializer::new(xml_bytes);

        deserializer.skip_to_tag_start(REGISTRY_TAG_NAME)?;

        let registry =
            deserializer.de_tag::<Registry>(REGISTRY_TAG_NAME, IgnoreEnd::Yes)?;

        Ok(registry)
    }

    /// Retrieves the OpenGL registry from a XML file.
    ///
    /// # Errors
    /// Returns `Err` if:
    /// - Parsing fails in any way.
    /// - An I/O error occurs.
    pub fn retrieve_from_file(xml_file: &mut File) -> Result<Registry, RegistryError>
    {
        let mut buf = Vec::new();

        xml_file.read_to_end(&mut buf)?;

        Self::retrieve_from_bytes(&buf)
    }

    /// Creates a new `Registry`.
    ///
    /// # Note
    /// This will **NOT** use anything from the actual OpenGL registry. Use the
    /// [`Registry::retrieve`] method for that.
    pub fn new(
        commands: impl IntoIterator<Item = Command>,
        api_interface_definitions: impl IntoIterator<Item = APIInterfaceDefinition>,
    ) -> Self
    {
        Self {
            commands: commands.into_iter().collect(),
            api_interface_definitions: api_interface_definitions.into_iter().collect(),
        }
    }

    /// Returns the commands.
    #[must_use]
    pub fn commands(&self) -> &[Command]
    {
        &self.commands
    }

    /// Returns the API interface definitions.
    #[must_use]
    pub fn api_interface_definitions(&self) -> &[APIInterfaceDefinition]
    {
        &self.api_interface_definitions
    }
}

impl Deserialize for Registry
{
    type Error = RegistryError;

    fn deserialize<TDeserializer: Deserializer>(
        _start: &BytesStart,
        deserializer: &mut TDeserializer,
    ) -> Result<Self, Self::Error>
    {
        deserializer.skip_to_tag_start("commands")?;

        let commands =
            deserializer.de_tag_with("commands", IgnoreEnd::No, |_, deserializer| {
                deserializer.de_tag_list::<Command>("command")
            })?;

        deserializer.skip_to_tag_start("feature")?;

        let api_interface_definitions =
            deserializer.de_tag_list::<APIInterfaceDefinition>("feature")?;

        Ok(Self {
            commands,
            api_interface_definitions,
        })
    }
}

/// [`Registry`] error.
#[derive(Debug, thiserror::Error)]
pub enum RegistryError
{
    /// No 'registry' element was found.
    #[error("No 'registry' element was found")]
    MissingRegistryElement,

    /// No 'commands' element was found.
    #[error("No 'commands' element was found")]
    MissingCommandsElement,

    /// A command is invalid.
    #[error("Invalid command")]
    InvalidCommand(#[from] CommandError),

    /// I/O failed.
    #[error("I/O failed")]
    IOFailed(#[from] std::io::Error),

    /// Deserialization failed.
    #[error("Deserialization failed")]
    DeserializationFailed(#[from] DeserializationError),
}

impl From<DeserializerError> for RegistryError
{
    fn from(err: DeserializerError) -> Self
    {
        DeserializationError(err).into()
    }
}

/// Deserialization error.
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct DeserializationError(#[from] DeserializerError);

#[cfg(test)]
mod tests
{
    use super::*;

    #[test]
    fn registry_works()
    {
        let registry = Registry::retrieve().expect("Expected Ok");

        for api_interface_def in registry.api_interface_definitions() {
            println!(
                "{} - {}",
                api_interface_def.api_name(),
                api_interface_def.version()
            );

            println!("Removals:");

            for removal in api_interface_def.removals() {
                for feature in removal.features() {
                    println!("    {:?} - {}", feature.kind(), feature.name());
                }
            }
        }
    }
}