summaryrefslogtreecommitdiff
path: root/glfw/src/init.rs
blob: b42bb52914e7a9e11520ac5bf048a2fc003d7873 (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
use crate::util::is_main_thread;
use crate::{get_glfw_error, Error};

/// Initializes GLFW and returns a initialization token.
///
/// # Errors
/// Will return `Err` if
/// - The current thread is not the main thread
/// - A GLFW error occurs
pub fn initialize() -> Result<Glfw, Error>
{
    if !is_main_thread() {
        return Err(Error::NotInMainThread);
    }

    // SAFETY: The current thread is the main thread
    let success = unsafe { crate::ffi::glfwInit() };

    if success == crate::ffi::GLFW_FALSE {
        get_glfw_error()?;
    }

    Ok(Glfw { _priv: &() })
}

/// GLFW initialization token.
#[derive(Debug)]
pub struct Glfw
{
    /// This field has two purposes
    /// - To make the struct not constructable without calling [`initialize`].
    /// - To make the struct `!Send` and `!Sync`.
    _priv: *const (),
}

impl Drop for Glfw
{
    fn drop(&mut self)
    {
        // SAFETY: The current thread cannot be any other thread than the main thread
        // since the initialize function checks it and the GLFW initialization token is
        // neither Send or Sync
        unsafe { crate::ffi::glfwTerminate() };
    }
}