Skip to main content

navree_kernel/
key.rs

1//! Identities used by the container: modules, providers and scopes.
2
3use std::any::TypeId;
4use std::borrow::Cow;
5use std::fmt;
6use std::hash::{Hash, Hasher};
7
8/// Identity of a module: its Rust type plus a readable name.
9///
10/// Two module values with the same `ModuleId` are the same module: the kernel
11/// registers each id once (see [`Module::is_configured`](crate::Module::is_configured)).
12#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
13pub struct ModuleId {
14    type_id: TypeId,
15    name: &'static str,
16}
17
18impl ModuleId {
19    /// The id of module type `M`, named after the short type name of `M`.
20    pub fn of<M: ?Sized + 'static>() -> Self {
21        Self {
22            type_id: TypeId::of::<M>(),
23            name: short_type_name(std::any::type_name::<M>()),
24        }
25    }
26
27    /// A module id for type `M` with an explicit display name.
28    pub(crate) fn with_name<M: ?Sized + 'static>(name: &'static str) -> Self {
29        Self {
30            type_id: TypeId::of::<M>(),
31            name,
32        }
33    }
34
35    /// The readable module name (the short type name, e.g. `UsersModule`).
36    pub fn name(&self) -> &'static str {
37        self.name
38    }
39}
40
41impl fmt::Display for ModuleId {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        f.write_str(self.name)
44    }
45}
46
47/// Key of a provider in the container: a type plus an optional name, so
48/// `Db` and `Db("analytics")` can coexist.
49#[derive(Clone, Debug)]
50pub struct ProviderKey {
51    type_id: TypeId,
52    type_name: &'static str,
53    name: Option<Cow<'static, str>>,
54}
55
56impl ProviderKey {
57    /// The unnamed key of type `T` (which may be a trait object such as `dyn Mailer`).
58    pub fn of<T: ?Sized + 'static>() -> Self {
59        Self {
60            type_id: TypeId::of::<T>(),
61            type_name: std::any::type_name::<T>(),
62            name: None,
63        }
64    }
65
66    /// The key of type `T` registered under `name`.
67    pub fn named<T: ?Sized + 'static>(name: impl Into<Cow<'static, str>>) -> Self {
68        Self {
69            name: Some(name.into()),
70            ..Self::of::<T>()
71        }
72    }
73
74    /// The full Rust type name of the provided type (e.g. `navree_db::Db`).
75    pub fn type_name(&self) -> &'static str {
76        self.type_name
77    }
78
79    /// The provider name, if the key is named.
80    pub fn name(&self) -> Option<&str> {
81        self.name.as_deref()
82    }
83
84    pub(crate) fn type_id(&self) -> TypeId {
85        self.type_id
86    }
87}
88
89// `type_name` is derived from `type_id`, so identity is (type, name).
90impl PartialEq for ProviderKey {
91    fn eq(&self, other: &Self) -> bool {
92        self.type_id == other.type_id && self.name == other.name
93    }
94}
95
96impl Eq for ProviderKey {}
97
98impl Hash for ProviderKey {
99    fn hash<H: Hasher>(&self, state: &mut H) {
100        self.type_id.hash(state);
101        self.name.hash(state);
102    }
103}
104
105impl fmt::Display for ProviderKey {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        match &self.name {
108            Some(name) => write!(f, "{}(\"{name}\")", self.type_name),
109            None => f.write_str(self.type_name),
110        }
111    }
112}
113
114/// How long a provided instance lives.
115#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
116#[non_exhaustive]
117pub enum Scope {
118    /// Built once per app (eagerly at boot) and shared as `Arc<T>`.
119    #[default]
120    Singleton,
121    /// Built once per unit of work ([`RequestScope`](crate::RequestScope)).
122    Request,
123    /// Built on every resolution.
124    Transient,
125}
126
127impl fmt::Display for Scope {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        f.write_str(match self {
130            Scope::Singleton => "singleton",
131            Scope::Request => "request",
132            Scope::Transient => "transient",
133        })
134    }
135}
136
137/// Strips the module path from a type name, keeping generic arguments:
138/// `app::users::UsersModule` → `UsersModule`, `a::Wrap<b::C>` → `Wrap<b::C>`.
139pub(crate) fn short_type_name(full: &'static str) -> &'static str {
140    let generics = full.find('<').unwrap_or(full.len());
141    match full[..generics].rfind("::") {
142        Some(pos) => &full[pos + 2..],
143        None => full,
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150
151    #[test]
152    fn short_type_name_strips_paths_but_keeps_generics() {
153        assert_eq!(short_type_name("app::users::UsersModule"), "UsersModule");
154        assert_eq!(short_type_name("Plain"), "Plain");
155        assert_eq!(short_type_name("a::Wrap<b::C>"), "Wrap<b::C>");
156    }
157
158    #[test]
159    fn named_keys_differ_from_unnamed_and_display_their_name() {
160        let plain = ProviderKey::of::<u8>();
161        let named = ProviderKey::named::<u8>("analytics");
162        assert_ne!(plain, named);
163        assert_eq!(named, ProviderKey::named::<u8>(String::from("analytics")));
164        assert_eq!(named.to_string(), "u8(\"analytics\")");
165        assert_eq!(named.name(), Some("analytics"));
166    }
167}