use std::error::Error;
use std::fmt;
use std::string::String;
use super::*;
#[derive(Clone, Debug)]
pub enum TreeErrorType<Ix = DefaultIndexType> {
InvalidNodeIndex {
node: NodeIndex<Ix>,
},
ExpectedRootNode {
node: NodeIndex<Ix>,
},
ExpectedNonAncestorNode {
new_ancestor: NodeIndex<Ix>,
new_descendant: NodeIndex<Ix>,
},
OtherError {
msg: String,
},
}
#[derive(Clone, Debug)]
pub struct TreeError<Ix = DefaultIndexType> {
context: String,
error: TreeErrorType<Ix>,
}
impl<Ix> TreeError<Ix> {
pub fn invalid_node_index(context: &str, node: NodeIndex<Ix>) -> Self {
TreeError {
context: String::from(context),
error: TreeErrorType::InvalidNodeIndex { node },
}
}
pub fn expected_root_node(context: &str, node: NodeIndex<Ix>) -> Self {
TreeError {
context: String::from(context),
error: TreeErrorType::ExpectedRootNode { node },
}
}
pub fn expected_non_ancestor_node(
context: &str,
new_ancestor: NodeIndex<Ix>,
new_descendant: NodeIndex<Ix>,
) -> Self {
TreeError {
context: String::from(context),
error: TreeErrorType::ExpectedNonAncestorNode {
new_ancestor,
new_descendant,
},
}
}
pub fn other_error(context: &str, msg: &str) -> Self {
TreeError {
context: String::from(context),
error: TreeErrorType::OtherError {
msg: String::from(msg),
},
}
}
}
impl fmt::Display for TreeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.error {
TreeErrorType::InvalidNodeIndex { node } => write!(
f,
"{}: the node index '{}' is invalid",
self.context,
node.index()
),
TreeErrorType::ExpectedRootNode { node } => write!(
f,
"{}: the node '{}' must be a root node",
self.context,
node.index()
),
TreeErrorType::ExpectedNonAncestorNode {
new_ancestor,
new_descendant,
} => write!(
f,
"{}: the new child node '{}' is an ancestor of the new parent node '{}'",
self.context,
new_ancestor.index(),
new_descendant.index()
),
TreeErrorType::OtherError { ref msg } => write!(f, "{}: {}", self.context, msg),
}
}
}
impl Error for TreeError {
fn description(&self) -> &str {
match self.error {
TreeErrorType::InvalidNodeIndex { .. } => "Invalid node index",
TreeErrorType::ExpectedRootNode { .. } => "Expected root node",
TreeErrorType::ExpectedNonAncestorNode { .. } => "Expected non-ancestor node",
TreeErrorType::OtherError { .. } => "Other error",
}
}
fn cause(&self) -> Option<&dyn Error> {
None
}
}