Skip to main content

mads_core/
registry.rs

1//! Application-scoped provider storage and typed lookup.
2
3use std::any::{Any, TypeId};
4use std::collections::HashMap;
5use std::sync::Arc;
6
7use crate::{Diagnostic, Error, MADS001, MADS003, MADS004, Result};
8
9/// A type-erased application-scoped provider allocation.
10pub type ErasedProvider = Arc<dyn Any + Send + Sync>;
11
12/// Stores at most one application-scoped provider for each concrete type.
13pub struct ProviderRegistry {
14    values: HashMap<TypeId, ErasedProvider>,
15}
16
17impl ProviderRegistry {
18    /// Creates an empty provider registry.
19    pub fn new() -> Self {
20        Self {
21            values: HashMap::new(),
22        }
23    }
24
25    /// Stores a provider under its concrete type.
26    #[allow(clippy::result_large_err)]
27    pub fn insert<T>(&mut self, value: T) -> Result<()>
28    where
29        T: Send + Sync + 'static,
30    {
31        self.insert_erased(
32            TypeId::of::<T>(),
33            std::any::type_name::<T>(),
34            Arc::new(value),
35        )
36    }
37
38    /// Stores an erased provider under an explicit type identifier.
39    #[allow(clippy::result_large_err)]
40    pub fn insert_erased(
41        &mut self,
42        type_id: TypeId,
43        type_name: &'static str,
44        value: ErasedProvider,
45    ) -> Result<()> {
46        if self.values.contains_key(&type_id) {
47            return Err(Error::new(
48                Diagnostic::new(
49                    MADS001,
50                    "duplicate provider",
51                    "an application-scoped provider is already registered for this type",
52                )
53                .with_subject(type_name),
54            ));
55        }
56
57        self.values.insert(type_id, value);
58        Ok(())
59    }
60
61    /// Resolves a provider by its concrete type.
62    #[allow(clippy::result_large_err)]
63    pub fn resolve<T>(&self) -> Result<Arc<T>>
64    where
65        T: Send + Sync + 'static,
66    {
67        let type_name = std::any::type_name::<T>();
68        let provider = self
69            .values
70            .get(&TypeId::of::<T>())
71            .cloned()
72            .ok_or_else(|| {
73                Error::new(
74                    Diagnostic::new(
75                        MADS003,
76                        "missing provider",
77                        "no application-scoped provider is registered for this type",
78                    )
79                    .with_subject(type_name),
80                )
81            })?;
82
83        Arc::downcast::<T>(provider).map_err(|_| {
84            Error::new(
85                Diagnostic::new(
86                    MADS004,
87                    "provider type mismatch",
88                    "the provider registry contains a value that does not match its type identifier",
89                )
90                .with_subject(type_name),
91            )
92        })
93    }
94
95    /// Returns whether a provider is registered for the concrete type.
96    pub fn contains<T>(&self) -> bool
97    where
98        T: Send + Sync + 'static,
99    {
100        self.values.contains_key(&TypeId::of::<T>())
101    }
102
103    /// Returns the number of registered providers.
104    pub fn len(&self) -> usize {
105        self.values.len()
106    }
107
108    /// Returns whether no providers are registered.
109    pub fn is_empty(&self) -> bool {
110        self.values.is_empty()
111    }
112}
113
114impl Default for ProviderRegistry {
115    fn default() -> Self {
116        Self::new()
117    }
118}