1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
    Appellation: error <mod>
    Contrib: FL03 <jo3mccain@icloud.com>
*/
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use strum::{Display, EnumCount, EnumIs, EnumIter, EnumString, VariantNames};

#[derive(Clone, Debug, Display, EnumCount, EnumIs, VariantNames)]
#[cfg_attr(
    feature = "serde",
    derive(Deserialize, Serialize),
    serde(rename_all = "snake_case", untagged)
)]
#[repr(usize)]
#[strum(serialize_all = "snake_case")]
pub enum GraphError {
    Cycle(CycleError),
    Unknown(String),
}

unsafe impl Send for GraphError {}

unsafe impl Sync for GraphError {}

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

impl From<&str> for GraphError {
    fn from(error: &str) -> Self {
        GraphError::Unknown(error.to_string())
    }
}

impl From<String> for GraphError {
    fn from(error: String) -> Self {
        GraphError::Unknown(error)
    }
}

impl<Idx> From<petgraph::algo::Cycle<Idx>> for GraphError
where
    Idx: Copy + std::fmt::Debug,
{
    fn from(error: petgraph::algo::Cycle<Idx>) -> Self {
        GraphError::Cycle(CycleError::Cycle {
            id: format!("{:?}", error.node_id()),
        })
    }
}

impl From<petgraph::algo::NegativeCycle> for GraphError {
    fn from(_error: petgraph::algo::NegativeCycle) -> Self {
        GraphError::Cycle(CycleError::NegativeCylce)
    }
}

#[derive(Clone, Debug, Display, EnumCount, EnumIs, EnumIter, EnumString, VariantNames)]
#[cfg_attr(
    feature = "serde",
    derive(Deserialize, Serialize),
    serde(rename_all = "snake_case", untagged)
)]
#[repr(usize)]
#[strum(serialize_all = "snake_case")]
pub enum CycleError {
    Cycle { id: String },
    NegativeCylce,
}

macro_rules! into_error {
    ($error:ident, $kind:ident) => {
        impl From<$error> for GraphError {
            fn from(error: $error) -> Self {
                GraphError::$kind(error)
            }
        }
    };
}

into_error!(CycleError, Cycle);