di/
keyed.rs

1use crate::{Mut, Ref};
2use std::{any::Any, borrow::Borrow, marker::PhantomData, ops::Deref};
3
4/// Represents a holder for a keyed service.
5#[derive(Debug)]
6pub struct KeyedRef<TKey, TSvc: Any + ?Sized> {
7    service: Ref<TSvc>,
8    _key: PhantomData<TKey>,
9}
10
11/// Represents a holder for a keyed, mutable service.
12pub type KeyedRefMut<TKey, TSvc> = KeyedRef<TKey, Mut<TSvc>>;
13
14impl<TKey, TSvc: Any + ?Sized> KeyedRef<TKey, TSvc> {
15    /// Initializes a new holder for the specified keyed service.
16    ///
17    /// * `service` - The keyed service reference the holder is for
18    pub fn new(service: Ref<TSvc>) -> Self {
19        Self {
20            service,
21            _key: PhantomData,
22        }
23    }
24}
25
26impl<TKey, TSvc: Any + ?Sized> Clone for KeyedRef<TKey, TSvc> {
27    fn clone(&self) -> Self {
28        Self {
29            service: self.service.clone(),
30            _key: PhantomData,
31        }
32    }
33}
34
35impl<TKey, TSvc: Any + ?Sized> From<KeyedRef<TKey, TSvc>> for Ref<TSvc> {
36    fn from(value: KeyedRef<TKey, TSvc>) -> Self {
37        value.service
38    }
39}
40
41impl<TKey, TSvc: Any + ?Sized> AsRef<TSvc> for KeyedRef<TKey, TSvc> {
42    fn as_ref(&self) -> &TSvc {
43        self.service.as_ref()
44    }
45}
46
47impl<TKey, TSvc: Any + ?Sized> Borrow<TSvc> for KeyedRef<TKey, TSvc> {
48    fn borrow(&self) -> &TSvc {
49        self.service.borrow()
50    }
51}
52
53impl<TKey, TSvc: Any + ?Sized> Deref for KeyedRef<TKey, TSvc> {
54    type Target = TSvc;
55
56    fn deref(&self) -> &Self::Target {
57        self.service.deref()
58    }
59}