use crate::Features;
#[derive(Debug, thiserror::Error)]
pub enum HalError {
#[error("no adapter with index {0}")]
NoSuchAdapter(u32),
#[error("adapter lacks required features: {missing:?}")]
UnsupportedFeatures {
missing: Features,
},
#[error("invalid or stale {kind} handle {bits:#x}")]
InvalidHandle {
kind: &'static str,
bits: u64,
},
#[error("{kind} handle {bits:#x} belongs to a different instance or device")]
ForeignObject {
kind: &'static str,
bits: u64,
},
#[error("out of device memory")]
OutOfDeviceMemory,
#[error("out of host memory")]
OutOfHostMemory,
#[error("device lost: {0}")]
DeviceLost(String),
#[error("shader compilation failed: {0}")]
ShaderCompilation(String),
#[error("pipeline creation failed: {0}")]
PipelineCreation(String),
#[error("invalid descriptor: {0}")]
InvalidDescriptor(String),
#[error("unsupported by the {backend} backend: {what}")]
Unsupported {
backend: crate::BackendKind,
what: &'static str,
},
#[error("{0}")]
Backend(String),
}
#[derive(Debug, thiserror::Error)]
pub enum SurfaceError {
#[error("swapchain out of date; reconfigure and retry")]
OutOfDate,
#[error("surface lost")]
Lost,
#[error("timed out waiting for a swapchain image")]
Timeout,
#[error(transparent)]
Hal(#[from] HalError),
}
impl HalError {
#[must_use]
pub fn invalid_handle<T>(kind: &'static str, handle: crcbl_core::Handle<T>) -> Self {
Self::InvalidHandle {
kind,
bits: handle.to_bits(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{BackendKind, Buffer};
use crcbl_core::{Handle, Pool};
#[test]
fn messages_name_the_specific_problem() {
let missing = Features::DESCRIPTOR_INDEXING | Features::BUFFER_DEVICE_ADDRESS;
let text = HalError::UnsupportedFeatures { missing }.to_string();
assert!(text.contains("DESCRIPTOR_INDEXING"), "{text}");
assert!(text.contains("BUFFER_DEVICE_ADDRESS"), "{text}");
let text = HalError::Unsupported {
backend: BackendKind::WebGpu,
what: "push constants",
}
.to_string();
assert_eq!(text, "unsupported by the webgpu backend: push constants");
}
#[test]
fn invalid_handle_carries_the_handle_bits() {
let mut pool: Pool<u8> = Pool::new();
let handle: Handle<u8> = pool.insert(0);
let typed: Handle<Buffer> = handle.cast();
let error = HalError::invalid_handle("buffer", typed);
let HalError::InvalidHandle { kind, bits } = error else {
panic!("wrong variant");
};
assert_eq!(kind, "buffer");
assert_eq!(bits, typed.to_bits());
assert_ne!(bits, 0, "packed handle bits are never zero");
}
#[test]
fn out_of_date_is_its_own_variant_and_survives_a_hal_error_wrap() {
let wrapped: SurfaceError = HalError::OutOfHostMemory.into();
assert!(matches!(wrapped, SurfaceError::Hal(_)));
assert!(
!matches!(
wrapped,
SurfaceError::OutOfDate | SurfaceError::Lost | SurfaceError::Timeout
),
"and the conversion must not manufacture a presentation variant \
either — a resize is something a backend decides, never something \
a generic error becomes"
);
assert_eq!(wrapped.to_string(), HalError::OutOfHostMemory.to_string());
}
}