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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
#![feature(fn_traits)]
extern crate uuid;
use std::any::Any;
use std::cell::Cell;
use std::collections::HashMap;
use std::fmt::{Debug, Display, Formatter};
use std::ops::DerefMut;
use std::sync::Once;
use uuid::Uuid;
static mut INSTANCE: Cell<Option<SingletonManager>> = Cell::new(None);
static mut ONCE: Once = Once::new();
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone)]
pub enum Error {
ServiceDoesNotExist(String),
ServiceNotInstantiated(String),
FailedToDowncastRefOfService(String),
FailedToStoreService(String),
NoFactoryFunctionAvailable(String),
SetFailedToReturnAServiceReference(String),
FailedToDowncastFactoryOutput(String),
NoServiceWithStorageRequest,
FailedToStoreServiceAlias,
MutexGotPoison,
ServiceAlreadyExists,
FailedToStoreFactory,
UnknownError(String),
}
impl From<String> for Error {
fn from(s: String) -> Self {
Error::UnknownError(s)
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::ServiceDoesNotExist(ref s) => write!(f, "Service `{}` does not exist", s),
Self::ServiceNotInstantiated(ref s) => write!(f, "Service `{}` is not instantiated", s),
Self::FailedToDowncastRefOfService(ref s) => {
write!(f, "Failed to downcast service {}", s)
}
Self::FailedToStoreService(ref s) => write!(f, "Service `{}` Could not be stored", s),
Self::NoFactoryFunctionAvailable(ref s) => {
write!(f, "Service `{}` Does not contain a Factory function", s)
}
Self::SetFailedToReturnAServiceReference(ref s) => write!(
f,
"Storing the service `{}` failed to return a reference of the service",
s
),
Self::FailedToDowncastFactoryOutput(ref s) => {
write!(f, "Failed to downcast Factory output for service {}", s)
}
Self::NoServiceWithStorageRequest => write!(f, "No service with storage request"),
Self::FailedToStoreServiceAlias => write!(f, "Service Could not be stored"),
Self::MutexGotPoison => write!(f, "Mutex poison"),
Self::ServiceAlreadyExists => write!(f, "Service already exists"),
Self::FailedToStoreFactory => write!(f, "Failed to store factory"),
Self::UnknownError(s) => write!(f, "An unknown error happened: {}", s),
}
}
}
impl std::error::Error for Error {}
pub struct SingletonManager {
singletons: HashMap<Uuid, Box<dyn Any>>,
singleton_factories: HashMap<Uuid, Box<dyn Fn() -> Box<dyn Any>>>,
alias: HashMap<String, Uuid>,
}
impl SingletonManager {
fn new() -> SingletonManager {
SingletonManager {
singletons: HashMap::new(),
singleton_factories: HashMap::new(),
alias: HashMap::new(),
}
}
pub fn instance() -> &'static mut SingletonManager {
unsafe {
ONCE.call_once(|| INSTANCE = Cell::new(Some(SingletonManager::new())));
match *INSTANCE.as_ptr() {
Some(ref mut messenger) => messenger,
None => panic!("Failed to get instance"),
}
}
}
pub fn provide(&'static mut self, sp: impl SingletonProvider) -> Result<()> {
let t = sp.get_service().map_err(|e| e.into())?;
self.set(sp.get_name(), t).map(|_| ())
}
pub fn get_default<T: 'static, F: 'static>(
&self,
service_name: &str,
factory: F,
) -> Result<&'static mut T>
where
F: Fn() -> Box<dyn Any>,
{
if !self.has(service_name) {
SingletonManager::instance()
.set_factory(service_name, factory)
.ok();
}
sm().get::<T>(service_name)
}
pub fn has(&self, service_name: &str) -> bool {
self.alias.contains_key(service_name)
}
pub fn get<T: 'static>(&'static mut self, service_name: &str) -> Result<&'static mut T> {
SingletonManager::instance()
.alias
.get(service_name)
.ok_or_else(|| Error::ServiceDoesNotExist(service_name.to_string()))
.and_then(|id| sm().singleton_get(id))
.and_then(|service_box| {
service_box
.downcast_mut::<T>()
.ok_or_else(|| Error::FailedToDowncastRefOfService(service_name.to_string()))
})
}
pub fn set<T: 'static>(&self, service_name: &str, service: T) -> Result<&'static mut T> {
sm().store_alias(service_name).and_then(|id| {
sm().singleton_set(id, Box::new(service))
.and_then(|service_box| {
service_box.downcast_mut::<T>().ok_or_else(|| {
Error::FailedToDowncastRefOfService(service_name.to_string())
})
})
})
}
pub fn set_factory<F: 'static + Fn() -> Box<dyn Any>>(
&self,
service_name: &str,
factory: F,
) -> Result<&'static mut Box<dyn Fn() -> Box<dyn Any>>> {
sm().store_alias(service_name)
.and_then(|id| sm().singleton_factory_set(&id, Box::new(factory)))
}
fn store_alias(&self, alias: &str) -> Result<Uuid> {
if sm().alias.contains_key(alias) {
Err(Error::ServiceAlreadyExists)
} else {
sm().alias.insert(alias.to_string(), Uuid::new_v4());
if let Some(id) = sm().alias.get(alias) {
Ok(*id)
} else {
Err(Error::FailedToStoreServiceAlias)
}
}
}
fn singleton_get(&'static mut self, alias: &Uuid) -> Result<&mut Box<dyn Any>> {
sm().singletons
.get_mut(alias)
.ok_or_else(|| Error::ServiceDoesNotExist(alias.to_string()))
.or_else(|_| {
if sm().singleton_factories.contains_key(alias) {
sm().factory(alias)
} else {
Err(Error::ServiceDoesNotExist(alias.to_string()))
}
})
}
fn singleton_set(&self, id: Uuid, service: Box<dyn Any>) -> Result<&'static mut Box<dyn Any>> {
sm().singletons.insert(id, service);
if sm().singletons.contains_key(&id) {
sm().singletons
.get_mut(&id)
.ok_or_else(|| Error::FailedToStoreService(id.to_string()))
} else {
Err(Error::ServiceAlreadyExists)
}
}
fn singleton_factory_set<F: 'static + Fn() -> Box<dyn Any>>(
&self,
id: &Uuid,
factory: Box<F>,
) -> Result<&'static mut Box<dyn Fn() -> Box<dyn Any>>> {
sm().singleton_factories.insert(*id, factory);
if self.singleton_factories.contains_key(&id) {
sm().singleton_factories
.get_mut(&id)
.ok_or(Error::FailedToStoreFactory)
} else {
Err(Error::FailedToStoreFactory)
}
}
fn factory(&'static mut self, alias: &Uuid) -> Result<&mut Box<dyn Any>> {
if let Some(box_func) = self.singleton_factories.get_mut(alias) {
sm().execute_factory(box_func)
.map(|service| self.singletons.insert(*alias, service))
.ok();
if self.singletons.contains_key(alias) {
sm().singletons
.get_mut(alias)
.ok_or_else(|| Error::ServiceDoesNotExist(alias.to_string()))
} else {
Err(Error::ServiceDoesNotExist(alias.to_string()))
}
} else {
Err(Error::NoFactoryFunctionAvailable(alias.to_string()))
}
}
fn execute_factory(
&'static mut self,
factory: &mut Box<dyn Fn() -> Box<dyn Any>>,
) -> Result<Box<dyn Any>> {
let func = factory.deref_mut();
let service = func();
Ok(service)
}
}
pub trait SingletonProvider {
type Output: 'static;
type Error: Into<Error>;
fn service() -> std::result::Result<&'static mut Self::Output, Self::Error>;
fn get_name(&self) -> &'static str;
fn get_service(&self) -> std::result::Result<Self::Output, Self::Error>;
}
pub fn sm() -> &'static mut SingletonManager {
SingletonManager::instance()
}
pub fn singleton_manager() -> &'static mut SingletonManager {
SingletonManager::instance()
}
#[cfg(test)]
mod test {
use super::SingletonManager;
use std::ops::Deref;
use std::sync::Mutex;
struct SingletonService1 {
something: String,
}
#[derive(Debug)]
pub struct MyService {
message: String,
guard: Mutex<()>,
}
impl MyService {
pub fn set(&mut self, msg: &str) {
let mut _guard = self.guard.lock().expect("Failed to get guard");
self.message = msg.to_string();
}
pub fn get(&self) -> String {
let _guard = self.guard.lock();
self.message.clone()
}
}
#[test]
pub fn test_instance() {
SingletonManager::instance();
}
#[test]
pub fn set_singleton() {
SingletonManager::instance()
.set(
"my_service_0",
Box::new(SingletonService1 {
something: "hello".to_string(),
}),
)
.unwrap();
}
#[test]
pub fn set_get_singleton() {
SingletonManager::instance()
.set(
"my_service_1",
SingletonService1 {
something: "hello".to_string(),
},
)
.unwrap();
let var = SingletonManager::instance()
.get::<SingletonService1>("my_service_1")
.unwrap()
.something
.clone();
assert_eq!("hello".to_string(), var);
}
#[test]
#[warn(clippy::unnecessary_operation)]
fn test_downcast() {
let instance_name = "MyService";
let service_name = "my_downcast_test";
let my_function = Some(Box::new(|| {
Box::new(MyService {
message: "".to_string(),
guard: Mutex::new(()),
})
}));
my_function
.as_ref()
.ok_or_else(|| super::Error::NoFactoryFunctionAvailable(service_name.to_string()))
.map(|f| (instance_name, f))
.map(|(instance, factory)| {
let func = factory.deref();
let output = func.call(());
(instance, output as Box<MyService>)
})
.map(|(_instance_name, service)| service)
.map(|s| println!("{:?}", s))
.ok();
}
#[test]
fn test_setting_and_getting_from_example() {
SingletonManager::instance()
.set(
"my_service",
MyService {
message: "".to_string(),
guard: Mutex::new(()),
},
)
.ok();
let service = SingletonManager::instance()
.get::<MyService>("my_service")
.expect("Failed to get service");
service.set("My Message");
let different_service = SingletonManager::instance()
.get::<MyService>("my_service")
.expect("Failed to get service");
assert_eq!("My Message".to_string(), different_service.get());
}
#[test]
fn test_setting_and_getting_from_example_factory() {
SingletonManager::instance()
.set_factory("my_service_factory", || {
Box::new(MyService {
message: "".to_string(),
guard: Mutex::new(()),
})
})
.ok();
let service = SingletonManager::instance()
.get::<MyService>("my_service_factory")
.unwrap();
service.set("My Message");
let different_service = SingletonManager::instance()
.get::<MyService>("my_service_factory")
.unwrap();
assert_eq!("My Message".to_string(), different_service.get());
}
#[test]
fn test_setting_and_getting_from_example_default_factory() {
let service: &mut MyService = SingletonManager::instance()
.get_default("my_default_service_factory", || {
Box::new(MyService {
message: "".to_string(),
guard: Mutex::new(()),
})
})
.unwrap();
service.set("My Message");
assert_eq!("My Message".to_string(), service.get());
}
}