|
1 | | -use crate::export::NativeClass; |
| 1 | +use std::any::TypeId; |
| 2 | +use std::borrow::Cow; |
| 3 | +use std::collections::HashMap; |
| 4 | + |
2 | 5 | use once_cell::sync::Lazy; |
3 | 6 | use parking_lot::RwLock; |
4 | | -use std::any::TypeId; |
5 | | -use std::collections::HashSet; |
6 | 7 |
|
7 | | -static CLASS_REGISTRY: Lazy<RwLock<HashSet<TypeId>>> = Lazy::new(|| RwLock::new(HashSet::new())); |
| 8 | +use crate::export::NativeClass; |
| 9 | + |
| 10 | +static CLASS_REGISTRY: Lazy<RwLock<HashMap<TypeId, ClassInfo>>> = |
| 11 | + Lazy::new(|| RwLock::new(HashMap::new())); |
| 12 | + |
| 13 | +pub(crate) struct ClassInfo { |
| 14 | + pub name: Cow<'static, str>, |
| 15 | +} |
8 | 16 |
|
9 | 17 | /// Can be used to validate whether or not `C` has been added using `InitHandle::add_class<C>()` |
10 | 18 | /// Returns true if added otherwise false. |
11 | 19 | #[inline] |
12 | 20 | pub(crate) fn is_class_registered<C: NativeClass>() -> bool { |
13 | 21 | let type_id = TypeId::of::<C>(); |
14 | | - CLASS_REGISTRY.read().contains(&type_id) |
| 22 | + CLASS_REGISTRY.read().contains_key(&type_id) |
| 23 | +} |
| 24 | + |
| 25 | +/// Access the [`ClassInfo`] of the class `C`. |
| 26 | +#[inline] |
| 27 | +pub(crate) fn with_class_info<C: NativeClass, F, R>(f: F) -> Option<R> |
| 28 | +where |
| 29 | + F: FnOnce(&ClassInfo) -> R, |
| 30 | +{ |
| 31 | + CLASS_REGISTRY.read().get(&TypeId::of::<C>()).map(f) |
| 32 | +} |
| 33 | + |
| 34 | +/// Returns the NativeScript name of the class `C` if it is registered. Returns a best-effort |
| 35 | +/// description of the type for error reporting otherwise. |
| 36 | +#[inline] |
| 37 | +pub(crate) fn class_name_or_default<C: NativeClass>() -> Cow<'static, str> { |
| 38 | + with_class_info::<C, _, _>(|i| i.name.clone()) |
| 39 | + .unwrap_or_else(|| Cow::Borrowed(std::any::type_name::<C>())) |
15 | 40 | } |
16 | 41 |
|
17 | | -/// Registers the class `C` in the class registry. |
18 | | -/// Returns `true` if `C` was not already present in the list. |
19 | | -/// Returns `false` if `C` was already added. |
| 42 | +/// Registers the class `C` in the class registry, using a custom name. |
| 43 | +/// Returns the old `ClassInfo` if `C` was already added. |
20 | 44 | #[inline] |
21 | | -pub(crate) fn register_class<C: NativeClass>() -> bool { |
| 45 | +pub(crate) fn register_class_as<C: NativeClass>(name: Cow<'static, str>) -> Option<ClassInfo> { |
22 | 46 | let type_id = TypeId::of::<C>(); |
23 | | - CLASS_REGISTRY.write().insert(type_id) |
| 47 | + CLASS_REGISTRY.write().insert(type_id, ClassInfo { name }) |
24 | 48 | } |
25 | 49 |
|
26 | 50 | /// Clears the registry |
|
0 commit comments