1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
use crate::{ServiceDependency, ServiceProvider, Type};
use spin::Once;
use std::any::Any;
use std::marker::PhantomData;

/// Represents the possible service lifetimes.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum ServiceLifetime {
    /// Indicates that a single instance of the service will be created.
    Singleton,

    /// Indicates that a new instance of the service will be created for each scope.
    Scoped,

    /// Indicates that a new instance of the service will be created every time it is requested.
    Transient,
}

/// Represents the type alias for a service reference.
#[cfg(not(feature = "async"))]
pub type ServiceRef<T> = std::rc::Rc<T>;

/// Represents the type alias for a service reference.
#[cfg(feature = "async")]
pub type ServiceRef<T> = std::sync::Arc<T>;

/// Represents the callback function used to create a service.
pub type ServiceFactory = dyn Fn(&ServiceProvider) -> ServiceRef<dyn Any>;

/// Represents the description of a service with its service type, implementation, and lifetime.
pub struct ServiceDescriptor {
    lifetime: ServiceLifetime,
    service_type: Type,
    implementation_type: Type,
    dependencies: Vec<ServiceDependency>,
    instance: ServiceRef<Once<ServiceRef<dyn Any>>>,
    factory: ServiceRef<ServiceFactory>,
}

impl ServiceDescriptor {
    #[cfg(feature = "builder")]
    pub(crate) fn new(
        lifetime: ServiceLifetime,
        service_type: Type,
        implementation_type: Type,
        instance: Once<ServiceRef<dyn Any>>,
        factory: ServiceRef<ServiceFactory>,
    ) -> Self {
        Self {
            lifetime,
            service_type,
            implementation_type,
            dependencies: Vec::with_capacity(0),
            instance: ServiceRef::new(instance),
            factory,
        }
    }

    /// Gets the [lifetime](enum.ServiceLifetime.html) associated with the service descriptor.
    pub fn lifetime(&self) -> ServiceLifetime {
        self.lifetime
    }

    /// Gets the [service type](struct.Type.html) associated with the service descriptor.
    pub fn service_type(&self) -> &Type {
        &self.service_type
    }

    /// Gets the [implementation type](struct.Type.html) associated with the service descriptor.
    pub fn implementation_type(&self) -> &Type {
        &self.implementation_type
    }

    /// Gets the associated [service dependencies](struct.ServiceDependency.html), if any.
    pub fn dependencies(&self) -> &[ServiceDependency] {
        &self.dependencies
    }

    /// Gets or creates the service defined by the service descriptor.
    ///
    /// # Arguments
    ///
    /// * `services` - The current [service provider](struct.ServiceProvider.html).
    pub fn get(&self, services: &ServiceProvider) -> ServiceRef<dyn Any> {
        if self.lifetime == ServiceLifetime::Transient {
            return (self.factory)(services);
        }

        return self.instance.call_once(|| (self.factory)(services)).clone();
    }

    pub(crate) fn clone_with(&self, dependencies: bool) -> Self {
        Self {
            lifetime: self.lifetime,
            service_type: self.service_type.clone(),
            implementation_type: self.implementation_type.clone(),
            dependencies: if dependencies {
                self.dependencies.clone()
            } else {
                Vec::with_capacity(0)
            },
            instance: if self.lifetime == ServiceLifetime::Singleton {
                self.instance.clone()
            } else {
                ServiceRef::new(Once::new())
            },
            factory: self.factory.clone(),
        }
    }
}

impl Clone for ServiceDescriptor {
    fn clone(&self) -> Self {
        // without context, we don't know if this is 'safe';
        // always copy dependencies here
        self.clone_with(true)
    }
}

/// Represents a builder for [service descriptors](struct.ServiceDescriptor.html).
pub struct ServiceDescriptorBuilder<TSvc: Any + ?Sized, TImpl> {
    lifetime: ServiceLifetime,
    implementation_type: Type,
    dependencies: Vec<ServiceDependency>,
    _marker_svc: PhantomData<TSvc>,
    _marker_impl: PhantomData<TImpl>,
}

impl<TSvc: Any + ?Sized, TImpl> ServiceDescriptorBuilder<TSvc, TImpl> {
    /// Defines the factory method used to activate the service and returns the service descriptor.
    ///
    /// # Arguments
    ///
    /// * `factory` - The factory method used to create the service
    pub fn from<F>(mut self, factory: F) -> ServiceDescriptor
    where
        F: Fn(&ServiceProvider) -> ServiceRef<TSvc> + 'static,
    {
        ServiceDescriptor {
            lifetime: self.lifetime,
            service_type: Type::of::<TSvc>(),
            implementation_type: self.implementation_type,
            dependencies: if self.dependencies.is_empty() {
                Vec::with_capacity(0)
            } else {
                self.dependencies.shrink_to_fit();
                self.dependencies
            },
            instance: ServiceRef::new(Once::new()),
            factory: ServiceRef::new(move |sp| ServiceRef::new(factory(sp))),
        }
    }

    /// Defines a dependency used by the service.
    /// 
    /// # Arguments
    /// 
    /// * `dependency` - The [dependency](struct.ServiceDependency.html) associated with the service
    pub fn depends_on(mut self, dependency: ServiceDependency) -> Self {
        self.dependencies.push(dependency);
        self
    }

    /// Initializes a new service descriptor builder.
    ///
    /// # Arguments
    ///
    /// * `lifetime` - The [lifetime](enum.ServiceLifetime.html) of the service
    pub fn new(lifetime: ServiceLifetime, implementation_type: Type) -> Self {
        Self {
            lifetime,
            implementation_type,
            dependencies: Vec::new(),
            _marker_svc: PhantomData,
            _marker_impl: PhantomData,
        }
    }
}