1use std::any::TypeId;
4use std::borrow::Cow;
5use std::fmt;
6use std::hash::{Hash, Hasher};
7
8#[derive(Clone, Copy, Debug)]
13pub struct ModuleId {
14 type_id: TypeId,
15 name: &'static str,
16 type_name: &'static str,
17}
18
19impl ModuleId {
20 pub fn of<M: ?Sized + 'static>() -> Self {
22 let type_name = std::any::type_name::<M>();
23 Self {
24 type_id: TypeId::of::<M>(),
25 name: short_type_name(type_name),
26 type_name,
27 }
28 }
29
30 pub fn named<M: ?Sized + 'static>(name: &'static str) -> ModuleId {
44 Self {
45 type_id: TypeId::of::<M>(),
46 name,
47 type_name: std::any::type_name::<M>(),
48 }
49 }
50
51 pub fn name(&self) -> &'static str {
53 self.name
54 }
55
56 pub fn type_name(&self) -> &'static str {
69 self.type_name
70 }
71}
72
73impl PartialEq for ModuleId {
75 fn eq(&self, other: &Self) -> bool {
76 self.type_id == other.type_id && self.name == other.name
77 }
78}
79
80impl Eq for ModuleId {}
81
82impl Hash for ModuleId {
83 fn hash<H: Hasher>(&self, state: &mut H) {
84 self.type_id.hash(state);
85 self.name.hash(state);
86 }
87}
88
89impl fmt::Display for ModuleId {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 f.write_str(self.name)
92 }
93}
94
95#[derive(Clone, Debug)]
98pub struct ProviderKey {
99 type_id: TypeId,
100 type_name: &'static str,
101 name: Option<Cow<'static, str>>,
102}
103
104impl ProviderKey {
105 pub fn of<T: ?Sized + 'static>() -> Self {
107 Self {
108 type_id: TypeId::of::<T>(),
109 type_name: std::any::type_name::<T>(),
110 name: None,
111 }
112 }
113
114 pub fn named<T: ?Sized + 'static>(name: impl Into<Cow<'static, str>>) -> Self {
116 Self {
117 name: Some(name.into()),
118 ..Self::of::<T>()
119 }
120 }
121
122 pub fn type_name(&self) -> &'static str {
124 self.type_name
125 }
126
127 pub fn name(&self) -> Option<&str> {
129 self.name.as_deref()
130 }
131
132 pub(crate) fn type_id(&self) -> TypeId {
133 self.type_id
134 }
135}
136
137impl PartialEq for ProviderKey {
139 fn eq(&self, other: &Self) -> bool {
140 self.type_id == other.type_id && self.name == other.name
141 }
142}
143
144impl Eq for ProviderKey {}
145
146impl Hash for ProviderKey {
147 fn hash<H: Hasher>(&self, state: &mut H) {
148 self.type_id.hash(state);
149 self.name.hash(state);
150 }
151}
152
153impl fmt::Display for ProviderKey {
154 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155 match &self.name {
156 Some(name) => write!(f, "{}(\"{name}\")", self.type_name),
157 None => f.write_str(self.type_name),
158 }
159 }
160}
161
162#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
164#[non_exhaustive]
165pub enum Scope {
166 #[default]
168 Singleton,
169 Request,
171 Transient,
173}
174
175impl fmt::Display for Scope {
176 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177 f.write_str(match self {
178 Scope::Singleton => "singleton",
179 Scope::Request => "request",
180 Scope::Transient => "transient",
181 })
182 }
183}
184
185pub(crate) fn short_type_name(full: &'static str) -> &'static str {
188 let generics = full.find('<').unwrap_or(full.len());
189 match full[..generics].rfind("::") {
190 Some(pos) => &full[pos + 2..],
191 None => full,
192 }
193}
194
195#[cfg(test)]
196mod tests {
197 use super::*;
198
199 #[test]
200 fn short_type_name_strips_paths_but_keeps_generics() {
201 assert_eq!(short_type_name("app::users::UsersModule"), "UsersModule");
202 assert_eq!(short_type_name("Plain"), "Plain");
203 assert_eq!(short_type_name("a::Wrap<b::C>"), "Wrap<b::C>");
204 }
205
206 #[test]
207 fn named_keys_differ_from_unnamed_and_display_their_name() {
208 let plain = ProviderKey::of::<u8>();
209 let named = ProviderKey::named::<u8>("analytics");
210 assert_ne!(plain, named);
211 assert_eq!(named, ProviderKey::named::<u8>(String::from("analytics")));
212 assert_eq!(named.to_string(), "u8(\"analytics\")");
213 assert_eq!(named.name(), Some("analytics"));
214 }
215
216 struct Plain;
217 struct Wrap<T>(T);
218 struct Pair<A, B>(A, B);
219
220 #[test]
221 fn module_ids_carry_the_full_type_path_and_compare_as_before() {
222 let plain = ModuleId::of::<Plain>();
223 assert_eq!(plain.type_name(), "navree_kernel::key::tests::Plain");
224 assert_eq!(plain.name(), "Plain");
225 assert_eq!(plain, ModuleId::of::<Plain>());
226 assert_eq!(
228 ModuleId::of::<Wrap<Plain>>().type_name(),
229 "navree_kernel::key::tests::Wrap<navree_kernel::key::tests::Plain>"
230 );
231 assert_eq!(
232 ModuleId::of::<Pair<Plain, String>>().type_name(),
233 "navree_kernel::key::tests::Pair<navree_kernel::key::tests::Plain, alloc::string::String>"
234 );
235 assert_eq!(
236 ModuleId::of::<&'static Plain>().type_name(),
237 "&navree_kernel::key::tests::Plain"
238 );
239 assert_eq!(
240 ModuleId::of::<(Plain, u8)>().type_name(),
241 "(navree_kernel::key::tests::Plain, u8)"
242 );
243 assert_eq!(
244 ModuleId::of::<[Plain; 1]>().type_name(),
245 "[navree_kernel::key::tests::Plain; 1]"
246 );
247 let mut ids = std::collections::HashSet::new();
249 ids.insert(ModuleId::of::<Plain>());
250 assert!(ids.contains(&ModuleId::named::<Plain>("Plain")));
251 }
252
253 #[test]
254 fn module_ids_named_differently_are_two_modules() {
255 assert_ne!(
256 ModuleId::named::<Plain>("upi"),
257 ModuleId::named::<Plain>("cards")
258 );
259 assert_eq!(
260 ModuleId::named::<Plain>("upi").type_name(),
261 ModuleId::of::<Plain>().type_name()
262 );
263 struct Payments(&'static str);
264 impl crate::Module for Payments {
265 fn id(&self) -> ModuleId {
266 ModuleId::named::<Payments>(self.0)
267 }
268 fn register(&self, _: &mut crate::ModuleBuilder) {}
269 }
270 let report = crate::Navree::app()
271 .module(Payments("upi"))
272 .module(Payments("cards"))
273 .validate()
274 .expect("two modules of one type");
275 let names: Vec<&str> = report.modules.iter().map(|m| m.name).collect();
276 assert_eq!(names, ["upi", "cards", "App"]);
277 }
278}