siftgl 0.1.0

Memory-safe, ergonomic, zero-dependency, security-hardened OpenGL 3.3-4.6 Core frontend for Rust
Documentation
//! Error types and `Result` alias for `siftgl`.
//!
//! All fallible operations in `siftgl` return [`Result<T>`] and never panic
//! via `.unwrap()` or `.expect()`.

use std::fmt;

use crate::sys;
use crate::types::{FramebufferStatus, GlVersion, ShaderStage};

/// Convenience result alias used across `siftgl`.
pub type Result<T> = std::result::Result<T, GlError>;

/// Strongly-typed OpenGL `GLenum` error code returned by `glGetError`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GlErrorCode(pub u32);

impl GlErrorCode {
    /// `GL_NO_ERROR` (0x0000)
    pub const NO_ERROR: Self = Self(sys::GL_NO_ERROR);
    /// `GL_INVALID_ENUM` (0x0500)
    pub const INVALID_ENUM: Self = Self(sys::GL_INVALID_ENUM);
    /// `GL_INVALID_VALUE` (0x0501)
    pub const INVALID_VALUE: Self = Self(sys::GL_INVALID_VALUE);
    /// `GL_INVALID_OPERATION` (0x0502)
    pub const INVALID_OPERATION: Self = Self(sys::GL_INVALID_OPERATION);
    /// `GL_STACK_OVERFLOW` (0x0503)
    pub const STACK_OVERFLOW: Self = Self(sys::GL_STACK_OVERFLOW);
    /// `GL_STACK_UNDERFLOW` (0x0504)
    pub const STACK_UNDERFLOW: Self = Self(sys::GL_STACK_UNDERFLOW);
    /// `GL_OUT_OF_MEMORY` (0x0505)
    pub const OUT_OF_MEMORY: Self = Self(sys::GL_OUT_OF_MEMORY);
    /// `GL_INVALID_FRAMEBUFFER_OPERATION` (0x0506)
    pub const INVALID_FRAMEBUFFER_OPERATION: Self = Self(sys::GL_INVALID_FRAMEBUFFER_OPERATION);
    /// `GL_CONTEXT_LOST` (0x0507)
    pub const CONTEXT_LOST: Self = Self(sys::GL_CONTEXT_LOST);

    /// Returns the raw `u32` OpenGL error code.
    #[inline]
    pub const fn raw(self) -> u32 {
        self.0
    }

    /// Returns `true` if this code is `GL_NO_ERROR`.
    #[inline]
    pub const fn is_ok(self) -> bool {
        self.0 == sys::GL_NO_ERROR
    }

    /// Returns a static human-readable name for known OpenGL error codes.
    pub const fn name(self) -> &'static str {
        match self.0 {
            sys::GL_NO_ERROR => "GL_NO_ERROR",
            sys::GL_INVALID_ENUM => "GL_INVALID_ENUM",
            sys::GL_INVALID_VALUE => "GL_INVALID_VALUE",
            sys::GL_INVALID_OPERATION => "GL_INVALID_OPERATION",
            sys::GL_STACK_OVERFLOW => "GL_STACK_OVERFLOW",
            sys::GL_STACK_UNDERFLOW => "GL_STACK_UNDERFLOW",
            sys::GL_OUT_OF_MEMORY => "GL_OUT_OF_MEMORY",
            sys::GL_INVALID_FRAMEBUFFER_OPERATION => "GL_INVALID_FRAMEBUFFER_OPERATION",
            sys::GL_CONTEXT_LOST => "GL_CONTEXT_LOST",
            _ => "GL_ERROR_UNKNOWN",
        }
    }
}

impl fmt::Display for GlErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} (0x{:04X})", self.name(), self.0)
    }
}

/// Comprehensive error type for all `siftgl` operations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GlError {
    /// Failed to load the system OpenGL dynamic library.
    LibraryLoadFailed {
        /// Diagnostic reason explaining why loading failed.
        reason: String,
    },
    /// A required OpenGL function pointer could not be resolved.
    MissingFunction {
        /// Exact OpenGL symbol name (e.g. `"glBufferStorage"`).
        name: &'static str,
    },
    /// Failed to create or activate a native OpenGL context.
    ContextCreationFailed {
        /// Diagnostic reason from the platform windowing/context API.
        reason: String,
    },
    /// The active OpenGL context version is lower than required.
    UnsupportedVersion {
        /// Minimum version required by the operation.
        required: GlVersion,
        /// Actual version reported by the active context.
        actual: GlVersion,
    },
    /// An OpenGL API call reported an error via `glGetError`.
    GlCallFailed {
        /// The operation or GL entry point that failed.
        operation: &'static str,
        /// The OpenGL error code returned by `glGetError`.
        code: GlErrorCode,
    },
    /// GLSL shader compilation failed.
    ShaderCompileFailed {
        /// Shader stage that failed to compile.
        stage: ShaderStage,
        /// Driver compiler info log.
        log: String,
    },
    /// Shader program linking failed.
    ProgramLinkFailed {
        /// Driver linker info log.
        log: String,
    },
    /// Shader program validation failed.
    ProgramValidateFailed {
        /// Driver validation info log.
        log: String,
    },
    /// Framebuffer completeness check returned an incomplete status.
    FramebufferIncomplete {
        /// Reported framebuffer status.
        status: FramebufferStatus,
    },
    /// A Rust string could not be safely converted to a NUL-terminated C string.
    InvalidString {
        /// Name of the parameter containing an interior NUL byte.
        parameter: &'static str,
    },
    /// A caller-supplied argument violated an API precondition.
    InvalidParameter {
        /// Parameter name.
        parameter: &'static str,
        /// Human-readable validation message.
        reason: &'static str,
    },
    /// A byte offset, length, or index was out of bounds.
    OutOfBounds {
        /// Context describing which resource or slice was indexed.
        context: &'static str,
        /// Requested end offset or index.
        requested: usize,
        /// Available capacity or length.
        available: usize,
    },
    /// Checked integer arithmetic overflowed or a cast exceeded GL limits (`GLsizei` / `GLsizeiptr`).
    IntegerOverflow {
        /// Description of the calculation that overflowed.
        context: &'static str,
    },
    /// Attempted to map a buffer that is already mapped.
    AlreadyMapped,
    /// OpenGL returned a null pointer when mapping a buffer or allocating an object.
    MapFailed {
        /// Operation that failed to map.
        operation: &'static str,
    },
    /// GPU object creation returned handle `0`.
    ObjectCreationFailed {
        /// Object kind (e.g., `"Buffer"`, `"Shader"`, `"Texture"`).
        object: &'static str,
    },
    /// A pixel buffer's byte length did not match the expected dimensions and format.
    BufferSizeMismatch {
        /// Minimum required byte count.
        expected: usize,
        /// Actual slice byte length provided.
        actual: usize,
    },
    /// Waiting on a GPU sync fence returned `GL_WAIT_FAILED`.
    SyncWaitFailed,
}

impl fmt::Display for GlError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::LibraryLoadFailed { reason } => {
                write!(f, "failed to load OpenGL library: {reason}")
            }
            Self::MissingFunction { name } => {
                write!(f, "required OpenGL function `{name}` is not available")
            }
            Self::ContextCreationFailed { reason } => {
                write!(f, "failed to create OpenGL context: {reason}")
            }
            Self::UnsupportedVersion { required, actual } => {
                write!(
                    f,
                    "unsupported OpenGL version: required {required}, found {actual}"
                )
            }
            Self::GlCallFailed { operation, code } => {
                write!(f, "OpenGL call `{operation}` failed with {code}")
            }
            Self::ShaderCompileFailed { stage, log } => {
                write!(f, "{stage:?} shader compilation failed:\n{log}")
            }
            Self::ProgramLinkFailed { log } => {
                write!(f, "shader program linking failed:\n{log}")
            }
            Self::ProgramValidateFailed { log } => {
                write!(f, "shader program validation failed:\n{log}")
            }
            Self::FramebufferIncomplete { status } => {
                write!(f, "framebuffer is incomplete: {status:?}")
            }
            Self::InvalidString { parameter } => {
                write!(f, "parameter `{parameter}` contains an interior NUL byte")
            }
            Self::InvalidParameter { parameter, reason } => {
                write!(f, "invalid parameter `{parameter}`: {reason}")
            }
            Self::OutOfBounds {
                context,
                requested,
                available,
            } => {
                write!(
                    f,
                    "out of bounds in {context}: requested {requested}, available {available}"
                )
            }
            Self::IntegerOverflow { context } => {
                write!(f, "integer overflow in {context}")
            }
            Self::AlreadyMapped => write!(f, "buffer is already mapped"),
            Self::MapFailed { operation } => write!(f, "{operation} returned a null pointer"),
            Self::ObjectCreationFailed { object } => {
                write!(f, "OpenGL failed to allocate {object} object (handle 0)")
            }
            Self::BufferSizeMismatch { expected, actual } => {
                write!(
                    f,
                    "buffer size mismatch: expected at least {expected} bytes, got {actual} bytes"
                )
            }
            Self::SyncWaitFailed => write!(f, "glClientWaitSync returned GL_WAIT_FAILED"),
        }
    }
}

impl std::error::Error for GlError {}

/// Safely converts a `usize` to `GLsizei` (`i32`), returning [`GlError::IntegerOverflow`] on overflow.
#[inline]
pub(crate) fn checked_sizei(value: usize, context: &'static str) -> Result<sys::GLsizei> {
    sys::GLsizei::try_from(value).map_err(|_| GlError::IntegerOverflow { context })
}

/// Safely converts a `usize` to `GLsizeiptr` (`isize`), returning [`GlError::IntegerOverflow`] on overflow.
#[inline]
pub(crate) fn checked_sizeiptr(value: usize, context: &'static str) -> Result<sys::GLsizeiptr> {
    sys::GLsizeiptr::try_from(value).map_err(|_| GlError::IntegerOverflow { context })
}

/// Safely converts a `usize` to `GLintptr` (`isize`), returning [`GlError::IntegerOverflow`] on overflow.
#[inline]
pub(crate) fn checked_intptr(value: usize, context: &'static str) -> Result<sys::GLintptr> {
    sys::GLintptr::try_from(value).map_err(|_| GlError::IntegerOverflow { context })
}