Skip to main content

deorbit_core/resolver/
error.rs

1use crate::runtime::{TypeMeta, TypeNameFormat};
2use std::fmt::{Display, Formatter};
3
4#[derive(Debug)]
5pub enum Error {
6    Circular { path: Vec<TypeMeta> },
7    Missing { type_meta: TypeMeta },
8    Duplicated { type_meta: TypeMeta },
9}
10
11impl std::error::Error for Error {}
12
13impl Display for Error {
14    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
15        match self {
16            Error::Circular { path } => {
17                let separator = " -> ";
18
19                let avg_name_len = 8;
20                let est_capacity = size_of_val(separator) + avg_name_len * path.len();
21
22                // Trying to avoid redundant allocs as much as possible
23                let mut buffer = String::with_capacity(est_capacity);
24
25                for (idx, meta) in path.iter().enumerate() {
26                    if idx > 0 {
27                        buffer += separator;
28                    }
29
30                    buffer += meta.type_name(TypeNameFormat::Minimal);
31                }
32
33                write!(
34                    f,
35                    "Failed to resolve the graph due to a circular dependency ({})",
36                    buffer
37                )
38            }
39            Error::Missing { type_meta } => {
40                write!(
41                    f,
42                    "Failed to resolve the graph due to a missing service of type {}",
43                    type_meta.type_name(TypeNameFormat::Minimal)
44                )
45            }
46            Error::Duplicated { type_meta } => {
47                write!(
48                    f,
49                    "Failed to resolve the graph due to a duplicated binding of type {}",
50                    type_meta.type_name(TypeNameFormat::Minimal)
51                )
52            }
53        }
54    }
55}
56
57impl Error {
58    pub fn missing<T: ?Sized + 'static>() -> Self {
59        Error::Missing { type_meta: TypeMeta::of::<T>() }
60    }
61}