Skip to main content

alpha2_gpu/
error.rs

1use std::fmt;
2
3/// Failure while acquiring a GPU context: which step failed, and the
4/// platform's reason as its [`source`](std::error::Error::source).
5#[derive(Debug)]
6pub struct GpuError(Cause);
7
8/// The step of acquiring a GPU context that failed.
9#[derive(Copy, Clone, Debug, Eq, PartialEq)]
10#[non_exhaustive]
11pub enum GpuAcquisitionStep {
12    /// No suitable adapter was found.
13    Adapter,
14    /// The adapter could not create a device.
15    Device,
16}
17
18#[derive(Debug)]
19enum Cause {
20    Adapter(wgpu::RequestAdapterError),
21    Device(wgpu::RequestDeviceError),
22}
23
24impl GpuError {
25    pub(crate) const fn adapter(error: wgpu::RequestAdapterError) -> Self {
26        Self(Cause::Adapter(error))
27    }
28
29    pub(crate) const fn device(error: wgpu::RequestDeviceError) -> Self {
30        Self(Cause::Device(error))
31    }
32
33    /// The step that failed.
34    #[must_use]
35    pub const fn step(&self) -> GpuAcquisitionStep {
36        match self.0 {
37            Cause::Adapter(_) => GpuAcquisitionStep::Adapter,
38            Cause::Device(_) => GpuAcquisitionStep::Device,
39        }
40    }
41}
42
43impl std::error::Error for GpuError {
44    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
45        match &self.0 {
46            Cause::Adapter(error) => Some(error),
47            Cause::Device(error) => Some(error),
48        }
49    }
50}
51
52impl fmt::Display for GpuError {
53    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
54        match &self.0 {
55            Cause::Adapter(error) => write!(formatter, "could not acquire a GPU adapter: {error}"),
56            Cause::Device(error) => write!(formatter, "could not acquire a GPU device: {error}"),
57        }
58    }
59}