ioc/
common.rs

1use std::error::{self, Error as StdError};
2use std::fmt;
3use std::sync::Arc;
4use downcast::{AnySync, TypeMismatch};
5
6pub use anyhow::{Result, Error};
7
8// errors --------------------------------------------------
9
10#[derive(Debug)]
11pub struct InstancerNotFoundError {
12    pub service_name: String
13}
14
15impl InstancerNotFoundError {
16    pub fn new(service_name: String) -> Self {
17        Self{ service_name }
18    }
19}
20
21impl fmt::Display for InstancerNotFoundError {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        write!(f, "instancer for {} not found", self.service_name)
24    }
25}
26
27impl error::Error for InstancerNotFoundError {}
28
29#[derive(Debug)]
30pub struct InstanceCreationError {
31    pub service_name: String,
32    pub creation_error: Error,
33}
34
35impl InstanceCreationError {
36    pub fn new(service_name: String, creation_error: Error) -> Self {
37        Self{ service_name, creation_error }
38    }
39}
40
41impl fmt::Display for InstanceCreationError {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        write!(f, "instance creation for {} failed: {}", self.service_name, self.creation_error)
44    }
45}
46
47impl error::Error for InstanceCreationError {
48    fn source(&self) -> Option<&(dyn StdError + 'static)> {
49       Some(&*self.creation_error)
50    }
51}
52
53#[derive(Debug)]
54pub struct InstanceTypeError {
55    pub service_name: String,
56    pub type_mismatch: TypeMismatch,
57}
58
59impl InstanceTypeError {
60    pub fn new(service_name: String, type_mismatch: TypeMismatch) -> Self {
61        Self{ service_name, type_mismatch }
62    }
63}
64
65impl fmt::Display for InstanceTypeError {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        write!(f, "wrong type for instance of {}: {}", self.service_name, self.type_mismatch)
68    }
69}
70
71impl error::Error for InstanceTypeError {
72    fn source(&self) -> Option<&(dyn StdError + 'static)> {
73       Some(&self.type_mismatch)
74    }
75}
76
77// Service --------------------------------------------------
78
79pub trait Service: Send + Sync + 'static {
80    fn service_name() -> String {
81        std::any::type_name::<Self>()
82            .replace("dyn ", "")
83            .replace("::", ".")
84    }
85}
86
87// InstanceRef & TypedInstanceRef --------------------------------------------------
88
89pub type InstanceRef = Arc<dyn AnySync>;
90
91#[allow(type_alias_bounds)]
92pub type TypedInstanceRef<S: ?Sized> = Arc<Box<S>>;
93
94pub use TypedInstanceRef as I;