1use std::fmt;
18
19use nadir_platform::PlatformError;
20use nadir_render::RenderError;
21
22#[derive(Clone, Debug, PartialEq, Eq)]
24pub enum Error {
25 Platform(PlatformError),
27 Render(RenderError),
30}
31
32impl fmt::Display for Error {
33 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34 match self {
35 Self::Platform(error) => write!(f, "could not open the window: {error}"),
36 Self::Render(error) => write!(f, "could not draw: {error}"),
37 }
38 }
39}
40
41impl std::error::Error for Error {
42 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
43 match self {
44 Self::Platform(error) => Some(error),
45 Self::Render(error) => Some(error),
46 }
47 }
48}
49
50impl From<RenderError> for Error {
51 fn from(error: RenderError) -> Self {
52 Self::Render(error)
53 }
54}
55
56impl From<nadir_gfx::GfxError> for Error {
57 fn from(error: nadir_gfx::GfxError) -> Self {
58 Self::Render(RenderError::Gfx(error))
59 }
60}
61
62impl From<PlatformError> for Error {
63 fn from(error: PlatformError) -> Self {
64 Self::Platform(error)
65 }
66}
67
68#[cfg(test)]
69mod tests {
70 use std::error::Error as _;
71
72 use super::*;
73
74 #[test]
75 fn a_platform_error_says_what_failed_and_why() {
76 let error = Error::from(PlatformError::Unsupported);
77 assert_eq!(
78 error.to_string(),
79 "could not open the window: this operating system has no backend yet"
80 );
81 let source = error.source().map(ToString::to_string);
82 assert_eq!(
83 source.as_deref(),
84 Some("this operating system has no backend yet")
85 );
86 }
87
88 #[test]
89 fn a_render_error_says_it_could_not_draw() {
90 let error = Error::from(nadir_gfx::GfxError::ContextLost);
91 assert!(error.to_string().starts_with("could not draw: "), "{error}");
92 assert!(error.source().is_some());
93 }
94}