sgf_parser/
error.rs

1use derive_more::*;
2
3use std::error::Error;
4
5/// SGF parsing, or traversal, related errors
6#[derive(Debug, Display)]
7#[display(fmt = "{}", kind)]
8pub struct SgfError {
9    pub kind: SgfErrorKind,
10    source: Option<Box<dyn Error + Send + Sync + 'static>>,
11}
12
13/// Describes what kind of error we're dealing with
14#[derive(Debug, Display, Eq, PartialEq)]
15pub enum SgfErrorKind {
16    #[display(fmt = "Error parsing SGF file")]
17    ParseError,
18    #[display(fmt = "Variation not found")]
19    VariationNotFound,
20    #[display(fmt = "Root token found in a non root node")]
21    InvalidRootTokenPlacement,
22}
23
24impl Error for SgfError {
25    fn source(&self) -> Option<&(dyn Error + 'static)> {
26        self.source
27            .as_ref()
28            .map(|boxed| boxed.as_ref() as &(dyn Error + 'static))
29    }
30}
31
32impl From<SgfErrorKind> for SgfError {
33    fn from(kind: SgfErrorKind) -> SgfError {
34        SgfError { kind, source: None }
35    }
36}
37
38impl SgfError {
39    pub fn parse_error(err: impl Error + Send + Sync + 'static) -> Self {
40        SgfError {
41            kind: SgfErrorKind::ParseError,
42            source: Some(Box::new(err)),
43        }
44    }
45
46    pub fn variation_not_found(err: impl Error + Send + Sync + 'static) -> Self {
47        SgfError {
48            kind: SgfErrorKind::VariationNotFound,
49            source: Some(Box::new(err)),
50        }
51    }
52
53    pub fn invalid_root_token_placment(err: impl Error + Send + Sync + 'static) -> Self {
54        SgfError {
55            kind: SgfErrorKind::InvalidRootTokenPlacement,
56            source: Some(Box::new(err)),
57        }
58    }
59}