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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
|
use std::{
any::{Any, TypeId},
collections::HashMap,
sync::{Arc, Mutex},
};
use crate::{ChainProcess, Program, ProgramCollect, this};
/// A standalone, thread-safe container for storing global resources keyed by their type.
///
/// This is the resource store behind [`Program`]'s resource API: every `Program`
/// owns one of these containers and all of its resource operations delegate to it.
///
/// Unlike the resource API on [`Program`], this container is **not** coupled to a
/// program instance nor to the global `this::<C>()` context, so any number of
/// containers can be created and used at the same time — each with fully
/// independent storage.
///
/// Each resource is stored behind its **own** [`Mutex`]. The container lock is
/// only held for the brief lookup/clone of the entry, so two nested
/// `modify_res` calls (e.g. two `&mut` resource parameters generated by
/// `#[chain]`) lock **different** mutexes and cannot deadlock against each other.
pub struct GlobalResContainer {
/// Thread-safe storage for resources, keyed by their `TypeId` and protected by a `Mutex`.
///
/// Each entry is a `Box<dyn Any>` holding an `Arc<Mutex<Arc<Res>>>`: the outer
/// `Mutex` guards the entry itself (so a resource can be locked without
/// holding the container lock), and the inner `Arc<Res>` is the shared
/// immutable snapshot returned by `res()`.
map: Mutex<HashMap<TypeId, Box<dyn Any + Send + Sync>>>,
}
impl GlobalResContainer {
/// Creates an empty resource container.
///
/// Usage:
///
/// ```
/// # use mingling_core::GlobalResContainer;
/// let container = GlobalResContainer::new();
/// ```
#[must_use]
pub fn new() -> Self {
Self {
map: Mutex::new(HashMap::new()),
}
}
/// Clones the per-resource entry out from under the container lock.
///
/// The container lock is released as soon as the entry `Arc` is cloned,
/// so all subsequent operations lock only the resource's own mutex.
fn res_entry<Res: 'static>(&self) -> Option<Arc<Mutex<Arc<Res>>>> {
let guard = self.map.lock().ok()?;
let entry = guard
.get(&TypeId::of::<Res>())?
.as_ref()
.downcast_ref::<Arc<Mutex<Arc<Res>>>>()
.map(Arc::clone);
drop(guard);
entry
}
/// Inserts (or overwrites) a resource into the [`GlobalResContainer`].
///
/// # Behavior
///
/// - The resource is stored bound to the `TypeId` of its type. That is, **the same type**
/// can only have one resource instance — a later inserted resource of the same type will
/// **overwrite** the previously inserted old value.
/// - Different `Res` types are **completely independent** of each other in the container.
/// - Resources are stored as `Arc<Mutex<Arc<Res>>>`: the outer `Mutex` guarantees that
/// only one caller can modify the resource at a time (but holding that lock does not
/// block the container's global lock); the inner `Arc<Res>` is used to provide immutable
/// shared snapshots for read-only APIs such as `res()` / `res_or_default()`.
/// - `Res` must satisfy `'static + Send + Sync` (for thread-safe sharing) as well as the
/// [`ResourceMarker`] trait (providing default values, cloning, etc.).
///
/// # Return Value
///
/// Returns `&mut self` for chained calls, for example:
///
/// ```
/// # use mingling_core::GlobalResContainer;
/// let mut container = GlobalResContainer::new();
/// container
/// .with_resource(42i32)
/// .with_resource(String::from("hello"));
/// ```
pub fn with_resource<Res: 'static + Send + Sync + ResourceMarker>(
&mut self,
res: Res,
) -> &mut Self {
if let Ok(mut guard) = self.map.lock() {
guard.insert(
TypeId::of::<Res>(),
Box::new(Arc::new(Mutex::new(Arc::new(res)))),
);
}
self
}
/// Performs a **read-modify-write** operation on an existing resource in the container
/// and returns the closure's return value.
///
/// # Behavior
///
/// 1. First, looks up the resource entry corresponding to the `Res` type in the container.
/// 2. If the entry **does not exist** (has not been inserted via [`with_resource`] or
/// [`__store_res`]), returns `Return::default()` directly, **without** calling `f`,
/// and without inserting any new resource.
/// 3. If the entry exists, locks the resource's own mutex (note: this lock is **separate**
/// from the container's global lock, so nested calls will not deadlock).
/// 4. Takes the resource **out** of the container (attempting to take ownership directly
/// via `Arc::try_unwrap`):
/// - If the `Arc` has no other holders (i.e., no `GlobalResource` snapshot references it),
/// the original value is taken directly, without cloning.
/// - If the `Arc` has other holders (e.g., `res()` was called elsewhere and holds a
/// shared snapshot), a **clone** is made via `__resource_marker_clone()` for
/// modification; the original snapshot is unaffected.
/// 5. Passes the cloned/taken value to the closure `f(&mut new_res)` for modification and
/// collects the closure's return value `r`.
/// 6. Writes the modified new value **back** into the resource slot, then releases the
/// resource lock.
/// 7. Returns the closure's result `r`.
///
/// # Constraints
///
/// - `Res` must satisfy `'static + Default + ResourceMarker + Send + Sync`.
/// `ResourceMarker` guarantees the resource can be cloned (when a shared snapshot exists)
/// and can be default-instantiated.
/// - `Return` must implement `Default`, because when the resource does not exist or the
/// lock is poisoned, this method returns `Return::default()` as a fallback value.
///
/// # Example
///
/// ```
/// # use mingling_core::GlobalResContainer;
/// let mut container = GlobalResContainer::new();
/// container.with_resource(10i32);
///
/// // Resource exists: modify and return the value
/// let double = container.modify_res(|v: &mut i32| { *v *= 2; *v });
/// assert_eq!(double, 20);
/// assert_eq!(*container.res::<i32>().unwrap(), 20);
///
/// // Resource does not exist: returns Default, closure is not called
/// let missing = container.modify_res::<String, i32>(|_| 42);
/// assert_eq!(missing, 0);
/// ```
///
/// [`with_resource`]: Self::with_resource
/// [`__store_res`]: Self::__store_res
/// [`res()`]: Self::res
pub fn modify_res<Res, Return>(&self, f: impl FnOnce(&mut Res) -> Return) -> Return
where
Res: 'static + Default + ResourceMarker + Send + Sync,
Return: Default,
{
let Some(entry) = self.res_entry::<Res>() else {
return Return::default();
};
let Ok(mut guard) = entry.lock() else {
return Return::default();
};
let mut new_res = match Arc::try_unwrap(std::mem::take(&mut *guard)) {
Ok(val) => val,
Err(arc) => (*arc).__resource_marker_clone(),
};
let r = f(&mut new_res);
*guard = Arc::new(new_res);
r
}
/// Performs a **read-modify-write** operation on an existing resource in the container
/// and directly passes the closure's [`ChainProcess<C>`] routing result to the caller.
///
/// # Purpose
///
/// This is an internal method used by `#[chain]`, `#[resource]`, and similar macros;
/// it typically does not appear directly in user business code.
///
/// This method behaves very similarly to [`modify_res`](Self::modify_res), with the
/// only differences being:
///
/// - The closure `f`'s return type is [`ChainProcess<C>`], rather than an arbitrary generic
/// `Return`. This means it is designed for **chained program routing/jumping**
/// scenarios — the closure can return `ChainProcess::Ok(...)` /
/// `ChainProcess::Err(...)` / jump targets, etc., to route program execution to the
/// next stage.
/// - When the resource does not exist or the container/resource lock is poisoned,
/// `modify_res` returns `Return::default()`, whereas this method constructs a
/// **default resource** (via `ResourceMarker::__resource_marker_default()`),
/// still calls `f`, and returns the `ChainProcess<C>` produced by `f` directly.
/// That is, this method **always** calls the closure `f` and returns its routing result.
///
/// # Execution Steps
///
/// 1. Looks up the resource entry by `Res` type in the container.
/// - If the entry **does not exist**, constructs a **temporary default resource**
/// via `ResourceMarker::__resource_marker_default()`, directly calls
/// `f(&mut default_res)`, and returns its result.
/// - If the entry exists, continues to step 2.
/// 2. Locks the resource's **own** `Mutex` (independent of the container's global lock;
/// nested calls will not deadlock).
/// - If the lock is poisoned, also goes down the "default resource" branch:
/// constructs a default instance and calls `f`.
/// 3. Attempts to take the resource's **ownership** via `Arc::try_unwrap`:
/// - If the `Arc` has no other holders (no shared snapshots), takes the original value;
/// - If there are other holders (e.g., a [`GlobalResource`] snapshot exists elsewhere),
/// calls `ResourceMarker::__resource_marker_clone()` to **clone** a copy for
/// modification; the original snapshot is unaffected.
/// 4. Passes the taken value to the closure `f(&mut new_res)` to execute the modification
/// logic, obtaining the routing result `r`.
/// 5. Writes the modified new value **back** into the resource slot, releases the
/// resource lock.
/// 6. Returns `r` to the caller.
///
/// # Constraints
///
/// - `Res` must satisfy `'static + Default + ResourceMarker + Send + Sync`.
/// `ResourceMarker` provides cloning and default instantiation capabilities;
/// `Default` is used to construct fallback values.
/// - `C` must implement `ProgramCollect<Enum = C>`, i.e., the current program's
/// collector type.
/// - `ChainProcess<C>` represents an intermediate/terminal state of chained program
/// execution, decoded by macro-expanded code to determine the next step.
///
/// # Role as a Macro-Expansion Internal Method
///
/// In code generated by `#[chain]` and similar macros, when a resource needs to be
/// injected as a **mutable reference** (`&mut Res`) into a procedure/step, while also
/// ensuring that the procedure can return a `ChainProcess<C>` to drive program-flow
/// routing, the macro expansion generates a call to `__modify_res_and_return_route`.
/// This ensures:
///
/// - The resource modification and the `ChainProcess` routing result are completed in
/// **one atomic operation**;
/// - Regardless of whether the resource exists, macro-expanded code can obtain a
/// `ChainProcess<C>` to continue program execution flow;
/// - Macro-generated code does not need to worry about internal locking, `Arc`
/// ownership, or cloning details, all encapsulated by this method.
///
/// # Example
///
/// ```
/// # use mingling_core::{GlobalResContainer, ChainProcess, error::ChainProcessError};
/// # use mingling_core::MockProgramCollect;
/// let mut container = GlobalResContainer::new();
/// container.with_resource(1i32);
///
/// // After macro expansion, this is equivalent to: take out the i32 resource,
/// // modify it, and return the routing result
/// let route: ChainProcess<MockProgramCollect> =
/// container.__modify_res_and_return_route(|v: &mut i32| {
/// *v += 1;
/// ChainProcess::Err(ChainProcessError::Other("done".into()))
/// });
/// assert!(matches!(route, ChainProcess::Err(_)));
/// assert_eq!(*container.res::<i32>().unwrap(), 2);
/// ```
///
/// [`ChainProcess<C>`]: crate::ChainProcess
/// [`Program::__modify_res_and_return_route`]: crate::Program::__modify_res_and_return_route
///
/// # Note
///
/// This method is **`#[doc(hidden)]`**, and the API will not be publicly exposed in
/// stable documentation. Do not call it directly in business code; use public macros or
/// the public [`Program`] methods to operate on resources.
#[doc(hidden)]
pub fn __modify_res_and_return_route<Res, C>(
&self,
f: impl FnOnce(&mut Res) -> ChainProcess<C>,
) -> ChainProcess<C>
where
Res: 'static + Default + ResourceMarker + Send + Sync,
C: ProgramCollect<Enum = C>,
{
let Some(entry) = self.res_entry::<Res>() else {
let mut default_res = Res::__resource_marker_default();
return f(&mut default_res);
};
let Ok(mut guard) = entry.lock() else {
let mut default_res = Res::__resource_marker_default();
return f(&mut default_res);
};
let mut new_res = match Arc::try_unwrap(std::mem::take(&mut *guard)) {
Ok(val) => val,
Err(arc) => (*arc).__resource_marker_clone(),
};
let r = f(&mut new_res);
*guard = Arc::new(new_res);
r
}
/// **Takes** a `Res`-typed resource value **out** of the container and returns its
/// ownership.
///
/// # Purpose
///
/// This is an internal method used by `#[chain]`, `#[resource]`, and similar macros;
/// it typically does not appear directly in user business code.
///
/// This method differs from the public [`modify_res`](Self::modify_res):
///
/// - `modify_res` is a **modify-and-write-back** operation, where the value modified by
/// the closure is **written back** into the container's resource slot;
/// - This method performs a **take-and-return** operation — it requires no closure and
/// does not write the modified value back into the container. It **moves** the resource
/// **out of** the container into the caller's hands, granting the caller full ownership
/// (or an independent copy) of the resource, so it can be used independently of the
/// container.
///
/// # Execution Steps
///
/// 1. Looks up the resource entry by `Res` type in the container:
/// - If the entry **does not exist**, constructs and returns a default instance via
/// `ResourceMarker::__resource_marker_default()`.
/// - If the entry exists, continues to step 2.
/// 2. Locks the resource's **own** `Mutex`. If the lock is poisoned, also returns a
/// default instance.
/// 3. Attempts to take the resource's **ownership** via `Arc::try_unwrap`:
/// - If the `Arc` has no other holders (no shared snapshots), returns the original
/// value directly;
/// - If there are other holders (e.g., a [`GlobalResource`] shared snapshot exists),
/// calls `ResourceMarker::__resource_marker_clone()` to **clone** a copy and returns
/// it; the original value in the container is unaffected (not written back).
/// 4. Returns the taken `Res` value.
///
/// # Resource Slot State
///
/// This method does **not** write a new value back into the container, so the resource
/// slot is **cleared** after being taken (since it internally uses `mem::take`, the
/// slot is emptied). Subsequent calls to [`res()`](Self::res) /
/// [`modify_res`](Self::modify_res) for the same resource will find that the entry
/// **still exists** (the `TypeId` key is still present), but the `Arc` inside the slot
/// has been emptied and replaced with a `Default::default()`-typed empty value — the
/// exact behavior depends on internal implementation details, and macro-expanded code
/// should not rely on the precise state of the slot after extraction.
///
/// # Constraints
///
/// - `Res` must satisfy `'static + Default + ResourceMarker + Send + Sync`.
///
/// # Role as a Macro-Expansion Internal Method
///
/// In macro-generated code, when a resource needs to be **taken out at once** from the
/// container and handed to an operation that requires ownership (rather than borrowing)
/// — e.g., moving the resource to another container, passing it to an
/// `impl FnOnce(Res)`-style closure, or participating in special `Arc::try_unwrap`
/// semantics — the macro expansion calls this method. It avoids borrow-lifetime
/// entanglement and delivers ownership of the value directly.
///
/// # Example (simulating macro-expansion internal calls)
///
/// ```
/// # use mingling_core::GlobalResContainer;
/// let mut container = GlobalResContainer::new();
/// container.with_resource(3i32);
///
/// let extracted: i32 = container.__extract_res_mut();
/// assert_eq!(extracted, 3);
/// ```
///
/// [`Program::__extract_res_mut`]: crate::Program::__extract_res_mut
///
/// # Note
///
/// This method is **`#[doc(hidden)]`**, and the API will not be publicly exposed in
/// stable documentation. Do not call it directly in business code.
#[doc(hidden)]
#[must_use]
pub fn __extract_res_mut<Res: 'static + Default + ResourceMarker + Send + Sync>(&self) -> Res {
let Some(entry) = self.res_entry::<Res>() else {
return Res::__resource_marker_default();
};
let Ok(mut guard) = entry.lock() else {
return Res::__resource_marker_default();
};
match Arc::try_unwrap(std::mem::take(&mut *guard)) {
Ok(val) => val,
Err(arc) => (*arc).__resource_marker_clone(),
}
}
/// **Overwrites** a resource value into the container.
///
/// # Purpose
///
/// This is an internal method used by `#[chain]`, `#[resource]`, and similar macros;
/// it typically does not appear directly in user business code.
///
/// This method behaves **almost identically** to the public
/// [`with_resource`](Self::with_resource) (both store/overwrite a resource by type), but
/// the two differ in their method signatures:
///
/// - [`with_resource`](Self::with_resource) takes `&mut self` and returns `&mut Self`,
/// suitable for chained **initialization** scenarios (e.g., registering multiple
/// resources at once during `Program` construction);
/// - `__store_res` takes `&self` and returns no value, suitable for **runtime**
/// dynamic overwrite/update of a resource's value (e.g., macro-expanded code already
/// holding an immutable reference).
///
/// # Execution Steps
///
/// 1. Acquires the container's global lock. If the lock is poisoned, returns directly
/// without doing anything.
/// 2. Looks up the existing entry by `Res` type in the container:
/// - If the entry **does not exist**, creates a new `Arc<Mutex<Arc<Res>>>` wrapper
/// under the `TypeId::of::<Res>()` key and inserts it into the container.
/// - If the entry **already exists**, attempts to downcast `boxed_any` to
/// `Arc<Mutex<Arc<Res>>>` and attempts to lock the resource's own `Mutex`:
/// * If downcasting succeeds and locking succeeds, writes the new `Arc::new(val)`
/// directly into that slot, completing the overwrite update;
/// * If downcasting fails (which should not happen in theory, since the type is
/// guaranteed by `TypeId`) or the lock is poisoned, **replaces the entire entry**
/// (constructs a new `Arc<Mutex<Arc<Res>>>` and inserts it).
/// 3. Releases the container's global lock; the operation is complete.
///
/// # Concurrency Semantics
///
/// - The container's global lock and the resource's own lock are **two independent
/// locks**. This method briefly holds the container's global lock to locate the
/// entry, then writes the new value **only** under the protection of the resource's
/// own lock — other threads calling `res()` / `modify_res()` for the same resource
/// will not see intermediate states.
/// - If the container's global lock is poisoned, this method silently returns; if the
/// resource's own lock is poisoned, this method **replaces the entire entry** (discard
/// the old lock state), ensuring the new value can still be written successfully.
///
/// # Constraints
///
/// - `Res` must satisfy `'static + Send + Sync + ResourceMarker`.
///
/// # Role as a Macro-Expansion Internal Method
///
/// In macro-generated code, when a resource of a certain type needs to be **overwritten
/// at runtime** (e.g., writing a `&mut Res` parameter back into the container after a
/// procedure ends, or committing a newly computed resource snapshot back to the
/// container), the macro expansion calls this method. It allows updating a resource's
/// value in an environment where only `&self` (an immutable reference) is available,
/// decoupling the resource's lifetime from the caller's borrow of the container.
///
/// # Example (simulating macro-expansion internal calls)
///
/// ```
/// # use mingling_core::GlobalResContainer;
/// let container = GlobalResContainer::new();
///
/// // Runtime write
/// container.__store_res(8i32);
/// assert_eq!(*container.res::<i32>().unwrap(), 8);
///
/// // Overwrite
/// container.__store_res(9i32);
/// assert_eq!(*container.res::<i32>().unwrap(), 9);
/// ```
///
/// [`Program::__store_res`]: crate::Program::__store_res
///
/// # Note
///
/// This method is **`#[doc(hidden)]`**, and the API will not be publicly exposed in
/// stable documentation. Do not call it directly in business code; use the public
/// [`with_resource`](Self::with_resource) or [`modify_res`](Self::modify_res) public
/// methods instead.
#[doc(hidden)]
pub fn __store_res<Res: 'static + Send + Sync + ResourceMarker>(&self, val: Res) {
let Ok(mut guard) = self.map.lock() else {
return;
};
let Some(boxed_any) = guard.get_mut(&TypeId::of::<Res>()) else {
guard.insert(
TypeId::of::<Res>(),
Box::new(Arc::new(Mutex::new(Arc::new(val)))),
);
return;
};
if let Some(entry) = boxed_any.downcast_mut::<Arc<Mutex<Arc<Res>>>>()
&& let Ok(mut entry_guard) = entry.lock()
{
*entry_guard = Arc::new(val);
return;
}
// The entry exists but cannot be updated (type mismatch or poisoned
// lock): replace it wholesale.
guard.insert(
TypeId::of::<Res>(),
Box::new(Arc::new(Mutex::new(Arc::new(val)))),
);
}
/// Retrieves an **immutable shared snapshot** of a `Res`-typed resource from the container.
///
/// # Behavior
///
/// 1. Looks up the resource entry by `Res` type in the container:
/// - If the entry **does not exist** (has not been inserted via
/// [`with_resource`](Self::with_resource) or [`__store_res`](Self::__store_res)),
/// returns `None`.
/// - If the entry exists, continues to step 2.
/// 2. Locks the resource's **own** `Mutex` (independent of the container's global lock;
/// nested calls will not deadlock).
/// 3. If locking succeeds, clones the resource's internal `Arc<Res>` and wraps it as a
/// [`GlobalResource<Res>`] to return.
///
/// The returned [`GlobalResource<Res>`] can be dereferenced like `&Res` via `Deref`.
/// When multiple callers each hold their own returned [`GlobalResource<Res>`], they share
/// the same underlying `Arc<Res>` data, maintaining **read-only consistency** with each
/// other.
///
/// # Relationship with Modification Operations
///
/// - This method returns an **immutable snapshot** (`Arc<Res>`) of the resource and does
/// not block or wait for other threads to modify the resource (modification operations
/// lock the resource's own `Mutex`).
/// - When a [`GlobalResource<Res>`] snapshot is held externally (`Arc` strong reference
/// count > 1), subsequent [`modify_res`](Self::modify_res) operations on the same
/// resource will **clone** a copy for modification, without affecting the snapshot
/// obtained here.
///
/// # Return Value
///
/// Returns `Option<GlobalResource<Res>>`:
/// - If the resource exists and the lock can be acquired normally, returns
/// `Some(GlobalResource<Res>)`;
/// - If the resource does not exist or the resource lock is poisoned, returns `None`.
///
/// # Constraints
///
/// - `Res` must satisfy `'static + Send + Sync`.
///
/// # Example
///
/// ```
/// # use mingling_core::GlobalResContainer;
/// let mut container = GlobalResContainer::new();
/// container.with_resource(10i32);
///
/// let res = container.res::<i32>();
/// assert_eq!(*res.unwrap(), 10);
///
/// // Resource does not exist: returns None
/// assert!(container.res::<String>().is_none());
/// ```
///
/// If you want a default value when the entry does not exist, use
/// [`res_or_default`](Self::res_or_default); if you need to route to a specific path
/// when the resource is missing, use [`res_or_route`](Self::res_or_route).
#[must_use]
pub fn res<Res: 'static + Send + Sync>(&self) -> Option<GlobalResource<Res>> {
let entry = self.res_entry::<Res>()?;
let guard = entry.lock().ok()?;
Some(GlobalResource::from(Arc::clone(&*guard)))
}
/// Retrieves an **immutable shared snapshot** of a `Res`-typed resource from the container;
/// returns the provided routing result if the resource does not exist.
///
/// # Behavior
///
/// 1. Looks up the resource entry by `Res` type in the container:
/// - If the entry **exists** and the resource lock can be acquired normally, clones
/// the resource's internal `Arc<Res>` (wrapped via [`GlobalResource`]) and returns
/// it as `Ok(...)`.
/// - If the entry **does not exist** (has not been inserted via
/// [`with_resource`](Self::with_resource) or [`__store_res`](Self::__store_res)),
/// returns `Err(route)` directly — the caller-provided `ChainProcess<C>` is
/// returned as-is, without calling any closure.
/// 2. A poisoned lock is treated the same as a missing resource: returns `Err(route)`.
///
/// # Return Value
///
/// Returns `Result<GlobalResource<Res>, ChainProcess<C>>`:
/// - When the resource exists, returns `Ok(GlobalResource<Res>)` (a shared immutable
/// snapshot);
/// - When the resource does not exist or the resource lock is poisoned, returns
/// `Err(route)` (the provided routing result is returned as-is).
///
/// # Purpose
///
/// In chained program-routing (`#[chain]` and similar macros) scenarios, when a resource
/// is missing, it is usually desirable to route the program flow to some error-handling
/// branch or default path. This method allows the caller to pre-construct a
/// [`ChainProcess<C>`] route: when the resource exists, processing continues normally;
/// when the resource is missing, routing jumps to that path in place, avoiding
/// additional nested checks.
///
/// # Errors
///
/// Returns `Err(route)` (the provided `ChainProcess<C>` is returned as-is) when:
/// - The resource entry does not exist in the container;
/// - The resource's own lock is poisoned.
///
/// # Constraints
///
/// - `Res` must satisfy `'static + Send + Sync`.
/// - `C` must implement `ProgramCollect<Enum = C>`.
///
/// # Example
///
/// ```
/// # use mingling_core::{GlobalResContainer, ChainProcess, error::ChainProcessError};
/// # use mingling_core::MockProgramCollect;
/// let container = GlobalResContainer::new();
/// let route: ChainProcess<MockProgramCollect> =
/// ChainProcess::Err(ChainProcessError::Other("missing".into()));
///
/// // Resource missing: returns Err(route)
/// // Note: ChainProcess is not Clone, so pass each route by value.
/// assert!(container.res_or_route::<i32, MockProgramCollect>(route).is_err());
///
/// let mut container = GlobalResContainer::new();
/// container.with_resource(42i32);
/// // Resource exists: returns Ok(GlobalResource)
/// let route: ChainProcess<MockProgramCollect> =
/// ChainProcess::Err(ChainProcessError::Other("missing".into()));
/// match container.res_or_route::<i32, MockProgramCollect>(route) {
/// Ok(res) => assert_eq!(*res, 42),
/// Err(_) => panic!("expected Ok"),
/// }
/// ```
///
/// [`ChainProcess<C>`]: crate::ChainProcess
/// [`GlobalResource`]: crate::GlobalResource
pub fn res_or_route<Res, C>(
&self,
route: ChainProcess<C>,
) -> Result<GlobalResource<Res>, ChainProcess<C>>
where
Res: 'static + Send + Sync,
C: ProgramCollect<Enum = C>,
{
self.res().map_or_else(|| Err(route), Ok)
}
/// Retrieves an **immutable shared snapshot** of a `Res`-typed resource from the container;
/// returns a default instance if the resource does not exist.
///
/// # Behavior
///
/// 1. Looks up the resource entry by `Res` type in the container:
/// - If the entry **exists** and the resource lock can be acquired normally, clones
/// the resource's internal `Arc<Res>`, wraps it as a [`GlobalResource<Res>`], and
/// returns it.
/// - If the entry **does not exist** (has not been inserted via
/// [`with_resource`](Self::with_resource) or [`__store_res`](Self::__store_res)),
/// constructs a **default instance** via
/// `ResourceMarker::__resource_marker_default()`, wraps it as a
/// [`GlobalResource<Res>`], and returns it.
/// 2. A poisoned lock is treated the same as a missing resource: it also returns a
/// default instance.
///
/// The returned [`GlobalResource<Res>`] can be dereferenced like `&Res` via `Deref`.
/// When multiple callers each hold their own returned [`GlobalResource<Res>`], they share
/// the same underlying `Arc<Res>` data, maintaining **read-only consistency** with each
/// other.
///
/// # Difference from [`res()`](Self::res)
///
/// - [`res()`](Self::res) returns `None` when the resource is missing or the lock is
/// poisoned, requiring the caller to handle the `Option` themselves;
/// - This method returns a default value constructed by
/// `ResourceMarker::__resource_marker_default()` in the same scenario, so the caller
/// does not need to handle the missing branch and can use the return value directly.
///
/// If you need to route to a specific path (rather than return a default value) when the
/// resource is missing, use [`res_or_route`](Self::res_or_route).
///
/// # Constraints
///
/// - `Res` must satisfy `'static + Send + Sync + ResourceMarker` (`ResourceMarker`
/// provides default instantiation capability).
///
/// # Example
///
/// ```
/// # use mingling_core::GlobalResContainer;
/// let mut container = GlobalResContainer::new();
/// container.with_resource(10i32);
///
/// // Resource exists: returns the actual value
/// assert_eq!(*container.res_or_default::<i32>(), 10);
///
/// // Resource does not exist: returns the default value (i32::default() == 0)
/// assert_eq!(*container.res_or_default::<String>(), "");
/// ```
///
/// [`GlobalResource<Res>`]: crate::GlobalResource
/// [`with_resource`]: Self::with_resource
/// [`__store_res`]: Self::__store_res
#[must_use]
pub fn res_or_default<Res: 'static + Send + Sync + ResourceMarker>(
&self,
) -> GlobalResource<Res> {
self.res()
.unwrap_or_else(|| GlobalResource::from(Arc::new(Res::__resource_marker_default())))
}
}
impl Default for GlobalResContainer {
fn default() -> Self {
Self::new()
}
}
impl<C> Program<C>
where
C: ProgramCollect<Enum = C>,
{
/// Inserts (or overwrites) a resource into the program's global resource container.
///
/// This is a convenience wrapper around [`GlobalResContainer::with_resource`] that
/// delegates to the `Program`'s internal `resources` container. The resource is stored
/// keyed by its type with the same semantics as [`GlobalResContainer::with_resource`]:
/// the same `Res` type can only hold one instance, and inserting the same type twice
/// overwrites the previous value.
///
/// # Parameters
///
/// - `res`: The resource value to store. It must satisfy:
/// - `'static` — the value cannot contain borrowed data tied to a temporary lifetime.
/// - `Send + Sync` — it must be safe to share across threads.
/// - [`ResourceMarker`] — providing default value, clone, and modify capabilities.
///
/// # Return Value
///
/// Returns `&mut self` to allow method chaining, e.g.:
///
/// ```
/// # use mingling_core::Program;
/// use mingling_core::MockProgramCollect as ThisProgram;
/// let mut program = Program::<ThisProgram>::new_with_args(Vec::<String>::new());
/// program
/// .with_resource(42i32)
/// .with_resource(String::from("hello"));
/// ```
///
/// # See Also
///
/// - [`Self::res`] — read a shared immutable snapshot of a resource.
/// - [`Self::modify_res`] — read-modify-write a resource in place.
/// - [`GlobalResContainer::with_resource`] — the underlying implementation.
pub fn with_resource<Res: 'static + Send + Sync + ResourceMarker>(
&mut self,
res: Res,
) -> &mut Self {
self.resources.with_resource(res);
self
}
/// Performs a **read-modify-write** operation on a resource stored in the program's
/// resource container and returns the closure's return value.
///
/// This method delegates to [`GlobalResContainer::modify_res`], which provides the
/// full semantics of the read-modify-write operation. In summary:
///
/// 1. Looks up the resource entry by `Res` type in the program's resource container.
/// 2. If the entry does **not** exist (has not been inserted via [`with_resource`] or
/// [`__store_res`]), returns `Return::default()` immediately **without** calling `f`.
/// 3. If the entry exists, locks the resource's **own** mutex (distinct from the
/// container's global lock, so nested `modify_res` calls do not deadlock).
/// 4. Attempts to take ownership of the value via `Arc::try_unwrap`:
/// - If no other shared snapshot exists, the original value is taken directly.
/// - If another `GlobalResource` holds a snapshot, a **clone** is made via
/// `ResourceMarker::__resource_marker_clone()` for modification.
/// 5. Calls the closure `f(&mut res)` with the available (`&mut`) reference.
/// 6. Writes the modified value back into the resource slot and releases the lock.
/// 7. Returns the closure's return value `r`.
///
/// # Type Parameters
///
/// - `Res`: The resource type to modify. Must satisfy
/// `'static + Default + ResourceMarker + Send + Sync`.
/// - `Return`: The closure's return type. Must implement [`Default`] since a fallback
/// value is returned when the resource does not exist.
///
/// # Example
///
/// ```
/// # use mingling_core::Program;
/// use mingling_core::MockProgramCollect as ThisProgram;
/// let mut program = Program::<ThisProgram>::new_with_args(Vec::<String>::new());
/// program.with_resource(10i32);
///
/// let doubled = program.modify_res(|v: &mut i32| { *v *= 2; *v });
/// assert_eq!(doubled, 20);
/// assert_eq!(*program.res::<i32>().unwrap(), 20);
///
/// // Resource does not exist: returns Default without invoking the closure.
/// let missing = program.modify_res::<String, i32>(|_| 42);
/// assert_eq!(missing, 0);
/// ```
///
/// [`with_resource`]: Self::with_resource
/// [`__store_res`]: Self::__store_res
pub fn modify_res<Res, Return>(&self, f: impl FnOnce(&mut Res) -> Return) -> Return
where
Res: 'static + Default + ResourceMarker + Send + Sync,
Return: Default,
{
self.resources.modify_res(f)
}
/// Performs a **read-modify-write** operation on a resource and returns a
/// [`ChainProcess<C>`] routing result.
///
/// # Purpose
///
/// This is an internal method primarily used by `#[chain]` and related macros. It
/// behaves similarly to [`modify_res`](Self::modify_res) but is designed for
/// **chained program-routing** scenarios: the closure returns a [`ChainProcess<C>`]
/// that drives program execution to the next stage. Unlike `modify_res`, this method
/// **always** invokes the closure `f`, even when the resource does not exist or the
/// lock is poisoned (in those cases it constructs a temporary default resource via
/// `ResourceMarker::__resource_marker_default()`).
///
/// # Execution Steps
///
/// 1. Looks up the resource entry by `Res` type in the program's resource container.
/// - If missing, constructs a **default resource**, calls `f(&mut def)`, and returns
/// its [`ChainProcess<C>`] result.
/// - If present, continues to step 2.
/// 2. Locks the resource's **own** mutex (independent of the container's global lock,
/// so nested calls do not deadlock). If the lock is poisoned, also goes down the
/// default-resource branch above.
/// 3. Attempts to take ownership via `Arc::try_unwrap`; otherwise clones a copy for
/// modification using `ResourceMarker::__resource_marker_clone()`.
/// 4. Calls `f(&mut new_res)`, obtains the routing result `r`, and writes the modified
/// value back into the resource slot.
/// 5. Returns `r`.
///
/// # Type Parameters
///
/// - `Res`: The resource type. Must satisfy
/// `'static + Default + ResourceMarker + Send + Sync`.
/// - `C`: The program collector type, constrained by the outer `impl` block to
/// `ProgramCollect<Enum = C>`.
///
/// # Example
///
/// ```
/// # use mingling_core::{Program, ChainProcess, error::ChainProcessError};
/// use mingling_core::MockProgramCollect as ThisProgram;
/// let mut program = Program::<ThisProgram>::new_with_args(Vec::<String>::new());
/// program.with_resource(1i32);
///
/// let route: ChainProcess<ThisProgram> =
/// program.__modify_res_and_return_route(|v: &mut i32| {
/// *v += 1;
/// ChainProcess::Err(ChainProcessError::Other("done".into()))
/// });
/// assert!(matches!(route, ChainProcess::Err(_)));
/// assert_eq!(*program.res::<i32>().unwrap(), 2);
/// ```
///
/// # Note
///
/// This method is **`#[doc(hidden)]`** and is not intended for direct use in
/// business code. Use public macro-generated code or public APIs (e.g.
/// [`modify_res`](Self::modify_res)) instead.
#[doc(hidden)]
pub fn __modify_res_and_return_route<Res>(
&self,
f: impl FnOnce(&mut Res) -> ChainProcess<C>,
) -> ChainProcess<C>
where
Res: 'static + Default + ResourceMarker + Send + Sync,
{
self.resources.__modify_res_and_return_route(f)
}
/// **Takes** a `Res`-typed resource value **out** of the program's resource container
/// and returns its ownership.
///
/// # Purpose
///
/// This is an internal method used by `#[chain]`, `#[resource]`, and similar macros.
/// Unlike [`modify_res`](Self::modify_res), which modifies a resource in place and
/// writes it back, this method **moves** the resource out of the container (or clones
/// an independent copy when shared snapshots exist) and returns it to the caller.
///
/// # Execution Steps
///
/// 1. Looks up the resource entry by `Res` type.
/// - If missing, constructs and returns a **default instance** via
/// `ResourceMarker::__resource_marker_default()`.
/// 2. Locks the resource's own mutex. If poisoned, also returns a default instance.
/// 3. Tries `Arc::try_unwrap` to move the original value out; otherwise clones a copy
/// via `ResourceMarker::__resource_marker_clone()`.
/// 4. Returns the taken `Res` value. Note that the resource slot is **cleared** by
/// this operation; subsequent calls to [`res`](Self::res) for the same resource may
/// observe an emptied/default-valued slot.
///
/// # Type Parameters
///
/// - `Res`: The resource type to extract. Must satisfy
/// `'static + Default + ResourceMarker + Send + Sync`.
///
/// # Example
///
/// ```
/// # use mingling_core::Program;
/// use mingling_core::MockProgramCollect as ThisProgram;
/// let mut program = Program::<ThisProgram>::new_with_args(Vec::<String>::new());
/// program.with_resource(3i32);
/// let extracted: i32 = program.__extract_res_mut();
/// assert_eq!(extracted, 3);
/// ```
///
/// # Note
///
/// This method is **`#[doc(hidden)]`** and is not intended for direct use in
/// business code.
#[doc(hidden)]
#[must_use]
pub fn __extract_res_mut<Res: 'static + Default + ResourceMarker + Send + Sync>(&self) -> Res {
self.resources.__extract_res_mut()
}
/// **Overwrites** a resource value into the program's resource container.
///
/// # Purpose
///
/// This is an internal method used by `#[chain]`, `#[resource]`, and similar macros.
/// It behaves almost identically to [`with_resource`](Self::with_resource) (both
/// store/overwrite a resource by type), but differs in signature:
///
/// - [`with_resource`](Self::with_resource) takes `&mut self` and returns `&mut Self`,
/// suitable for chained initialization.
/// - `__store_res` takes `&self` and returns no value, suitable for **runtime**
/// dynamic overwrite/update when only an immutable reference is available.
///
/// # Execution Steps
///
/// 1. Acquires the container's global lock (silently returns if poisoned).
/// 2. Looks up the existing entry by `Res` type:
/// - If the entry does **not** exist, creates a new `Arc<Mutex<Arc<Res>>>` wrapper
/// under `TypeId::of::<Res>()` and inserts it.
/// - If it already exists, attempts to update it in place under the resource's own
/// lock. If that fails (type mismatch or poisoned lock), replaces the entire entry.
/// 3. Releases the container's global lock.
///
/// # Type Parameters
///
/// - `Res`: The resource type. Must satisfy
/// `'static + Send + Sync + ResourceMarker`.
///
/// # Example
///
/// ```
/// # use mingling_core::Program;
/// use mingling_core::MockProgramCollect as ThisProgram;
/// let program = Program::<ThisProgram>::new_with_args(Vec::<String>::new());
///
/// // Runtime write
/// program.__store_res(8i32);
/// assert_eq!(*program.res::<i32>().unwrap(), 8);
///
/// // Overwrite
/// program.__store_res(9i32);
/// assert_eq!(*program.res::<i32>().unwrap(), 9);
/// ```
///
/// # Note
///
/// This method is **`#[doc(hidden)]`** and is not intended for direct use in
/// business code. Use [`with_resource`](Self::with_resource) or
/// [`modify_res`](Self::modify_res) instead.
#[doc(hidden)]
pub fn __store_res<Res: 'static + Send + Sync + ResourceMarker>(&self, val: Res) {
self.resources.__store_res(val);
}
/// Retrieves an **immutable shared snapshot** of a `Res`-typed resource from the
/// program's resource container.
///
/// # Behavior
///
/// 1. Looks up the resource entry by `Res` type:
/// - If the entry **does not exist** (has not been inserted via
/// [`with_resource`](Self::with_resource) or [`__store_res`](Self::__store_res)),
/// returns `None`.
/// - If the entry exists, continues to step 2.
/// 2. Locks the resource's **own** mutex (independent of the container's global lock,
/// so nested calls do not deadlock).
/// 3. On success, clones the internal `Arc<Res>` and wraps it as a
/// [`GlobalResource<Res>`] to return.
///
/// The returned [`GlobalResource<Res>`] can be dereferenced like `&Res` via `Deref`.
/// Multiple callers holding their own [`GlobalResource<Res>`] share the same underlying
/// `Arc<Res>` data, providing **read-only consistency**.
///
/// # Return Value
///
/// Returns `Option<GlobalResource<Res>>`:
/// - `Some(GlobalResource<Res>)` when the resource exists and the lock can be acquired;
/// - `None` when the resource does not exist or its lock is poisoned.
///
/// If you want a default value in the missing case, use [`res_or_default`](Self::res_or_default);
/// if you need to route to a specific path, use [`res_or_route`](Self::res_or_route).
///
/// # Type Parameters
///
/// - `Res`: The resource type to read. Must satisfy `'static + Send + Sync`.
///
/// # Example
///
/// ```
/// # use mingling_core::Program;
/// use mingling_core::MockProgramCollect as ThisProgram;
/// let mut program = Program::<ThisProgram>::new_with_args(Vec::<String>::new());
/// program.with_resource(10i32);
///
/// let res = program.res::<i32>();
/// assert_eq!(*res.unwrap(), 10);
///
/// // Resource does not exist: returns None
/// assert!(program.res::<String>().is_none());
/// ```
#[must_use]
pub fn res<Res: 'static + Send + Sync>(&self) -> Option<GlobalResource<Res>> {
self.resources.res()
}
/// Retrieves an **immutable shared snapshot** of a `Res`-typed resource from the
/// program's resource container; returns the provided routing result if the resource
/// does not exist.
///
/// # Behavior
///
/// 1. Looks up the resource entry by `Res` type:
/// - If the entry **exists** and the resource lock can be acquired, clones the
/// internal `Arc<Res>` and returns it as `Ok(GlobalResource<Res>)`.
/// - If the entry **does not exist** (or its lock is poisoned), returns
/// `Err(route)` — the caller-provided [`ChainProcess<C>`] is returned as-is,
/// without calling any closure.
///
/// # Purpose
///
/// In chained program-routing scenarios (e.g. `#[chain]`), when a resource is missing
/// it is desirable to route program flow to an error-handling branch or default path.
/// This method allows the caller to pre-construct a [`ChainProcess<C>`] route so that
/// missing-resource handling is encapsulated in a single call.
///
/// # Errors
///
/// Returns `Err(route)` (the provided [`ChainProcess<C>`] as-is) when:
/// - The resource entry does not exist in the container.
/// - The resource's own lock is poisoned.
///
/// # Type Parameters
///
/// - `Res`: The resource type to read. Must satisfy `'static + Send + Sync`.
/// - `C`: The program collector type, constrained by the outer `impl` block to
/// `ProgramCollect<Enum = C>`.
///
/// # Example
///
/// ```
/// # use mingling_core::{Program, ChainProcess, error::ChainProcessError};
/// use mingling_core::MockProgramCollect as ThisProgram;
/// let program = Program::<ThisProgram>::new_with_args(Vec::<String>::new());
/// let route: ChainProcess<ThisProgram> =
/// ChainProcess::Err(ChainProcessError::Other("missing".into()));
///
/// // Resource missing: returns Err(route)
/// // Note: ChainProcess is not Clone, so pass the route by value.
/// assert!(program.res_or_route::<i32>(route).is_err());
///
/// let mut program = Program::<ThisProgram>::new_with_args(Vec::<String>::new());
/// program.with_resource(42i32);
/// // Resource exists: returns Ok(GlobalResource)
/// let route: ChainProcess<ThisProgram> =
/// ChainProcess::Err(ChainProcessError::Other("missing".into()));
/// match program.res_or_route::<i32>(route) {
/// Ok(res) => assert_eq!(*res, 42),
/// Err(_) => panic!("expected Ok"),
/// }
/// ```
pub fn res_or_route<Res: 'static + Send + Sync>(
&self,
route: ChainProcess<C>,
) -> Result<GlobalResource<Res>, ChainProcess<C>> {
self.resources.res_or_route(route)
}
/// Retrieves an **immutable shared snapshot** of a `Res`-typed resource from the
/// program's resource container; returns a default instance if the resource does not
/// exist.
///
/// # Behavior
///
/// 1. Looks up the resource entry by `Res` type:
/// - If the entry **exists** and the resource lock can be acquired, clones the
/// internal `Arc<Res>`, wraps it as a [`GlobalResource<Res>`], and returns it.
/// - If the entry **does not exist** (or its lock is poisoned), constructs a
/// default instance via `ResourceMarker::__resource_marker_default()`, wraps it
/// as a [`GlobalResource<Res>`], and returns it.
///
/// # Difference from [`res`](Self::res)
///
/// - [`res`](Self::res) returns `None` when the resource is missing or the lock is
/// poisoned, requiring the caller to handle the `Option` themselves.
/// - This method returns a default value in the same scenario, so the caller does not
/// need to handle the missing branch.
///
/// If you need to route to a specific path (rather than return a default value) when
/// the resource is missing, use [`res_or_route`](Self::res_or_route).
///
/// # Type Parameters
///
/// - `Res`: The resource type to read. Must satisfy
/// `'static + Send + Sync + ResourceMarker` (the latter provides default
/// instantiation capability).
///
/// # Example
///
/// ```
/// # use mingling_core::Program;
/// use mingling_core::MockProgramCollect as ThisProgram;
/// let mut program = Program::<ThisProgram>::new_with_args(Vec::<String>::new());
/// program.with_resource(10i32);
///
/// // Resource exists: returns the actual value
/// assert_eq!(*program.res_or_default::<i32>(), 10);
///
/// // Resource does not exist: returns the default value (i32::default() == 0)
/// assert_eq!(*program.res_or_default::<String>(), "");
/// ```
#[must_use]
pub fn res_or_default<Res: 'static + Send + Sync + ResourceMarker>(
&self,
) -> GlobalResource<Res> {
self.resources.res_or_default()
}
}
/// Global type wrapper.
///
/// `GlobalResource` is a **thread-safe shared immutable snapshot** wrapper around a resource value.
/// It internally holds an `Arc<ResType>`, allowing multiple callers to simultaneously hold read-only
/// access to the same underlying data without worrying about ownership transfer or lifetime entanglement.
///
/// # Why `GlobalResource` is Needed
///
/// In the [`GlobalResContainer`] (global resource container), resources are stored in a three-layer
/// `Arc<Mutex<Arc<Res>>>` structure:
///
/// - The outer `Mutex` ensures that only one modifier can exclusively access the resource at a time;
/// - The innermost `Arc<Res>` provides an **immutable shared snapshot**;
/// - `GlobalResource` is the safe exposure wrapper around that innermost `Arc<Res>`.
///
/// When multiple callers each obtain a `GlobalResource` via [`GlobalResContainer::res`], they share
/// the same underlying `Arc<Res>`, thus guaranteeing consistency of data between them (all being the
/// same snapshot).
///
/// # Usage
///
/// `GlobalResource<ResType>` implements [`Deref`](https://doc.rust-lang.org/stable/core/ops/trait.Deref.html) (with target type `ResType`), so it can be
/// dereferenced directly like `&ResType` to access the underlying value:
///
/// ```
/// # use mingling_core::GlobalResource;
/// let res = GlobalResource::new(42i32);
/// assert_eq!(*res, 42);
/// ```
///
/// It can also be used with [`AsRef`] to obtain a `&ResType` reference:
///
/// ```
/// # use mingling_core::GlobalResource;
/// let res = GlobalResource::new(String::from("hello"));
/// assert_eq!(res.as_ref(), "hello");
/// ```
///
/// # Relationship with Modification Operations
///
/// - `GlobalResource` provides **read-only** access only; the underlying data is immutable.
/// - When an external caller holds a `GlobalResource` (causing the `Arc` strong reference count
/// to be > 1), subsequent [`modify_res`](GlobalResContainer::modify_res) operations on the same
/// resource will **clone** a copy for modification and **will not affect** the snapshot held here.
/// - This means that `GlobalResource` can serve as a stable view of the resource, retaining the
/// data content as of the initial read even after modification operations occur.
///
/// # Type Constraints
///
/// - `ResType` must satisfy `'static + Send + Sync` to ensure safe sharing across threads.
/// - The resource itself typically also needs to implement [`ResourceMarker`] (providing default
/// values, cloning, etc.) so that the container can perform default instantiation and
/// clone-based modification.
///
/// # See Also
///
/// - [`GlobalResContainer::res`] — obtain a `GlobalResource` snapshot from the container.
/// - [`GlobalResContainer::res_or_default`] — obtain a snapshot, or return a default value when missing.
/// - [`GlobalResContainer::res_or_route`] — obtain a snapshot, or route to a specified path when missing.
///
/// [`GlobalResContainer`]: crate::GlobalResContainer
/// [`GlobalResContainer::res`]: crate::GlobalResContainer::res
/// [`GlobalResContainer::res_or_default`]: crate::GlobalResContainer::res_or_default
/// [`GlobalResContainer::res_or_route`]: crate::GlobalResContainer::res_or_route
/// [`ResourceMarker`]: crate::ResourceMarker
pub struct GlobalResource<ResType: 'static + Send + Sync> {
res_arc: Arc<ResType>,
}
impl<ResType: 'static + Send + Sync> GlobalResource<ResType> {
/// Creates a new [`GlobalResource`], wrapping the given value directly.
///
/// # Parameters
///
/// - `res`: The resource value to wrap. The value must be of a `'static + Send + Sync` type
/// to ensure it can be safely shared across threads.
///
/// # Return Value
///
/// Returns a [`GlobalResource<ResType>`] holding `Arc::new(res)`, which can be dereferenced
/// via [`Deref`] or [`AsRef`] to access the underlying value.
///
/// # Difference from `From<Arc<ResType>>`
///
/// - `new` accepts an **owned value** `ResType`, automatically wrapping it into `Arc<ResType>`;
/// - `From<Arc<ResType>>` accepts an **already-wrapped `Arc`**, reusing it directly without an
/// additional heap allocation.
///
/// # Example
///
/// ```
/// # use mingling_core::GlobalResource;
/// let res = GlobalResource::new(42i32);
/// assert_eq!(*res, 42);
/// ```
///
/// # See Also
///
/// - [`GlobalResource::from`] (`From<Arc<ResType>>`) — construct from an existing `Arc`.
/// - [`Deref`] — dereference to access the underlying value.
///
/// [`Deref`]: std::ops::Deref
/// [`AsRef`]: std::convert::AsRef
pub fn new(res: ResType) -> Self {
Self {
res_arc: Arc::new(res),
}
}
}
impl<ResType: 'static + Send + Sync> From<Arc<ResType>> for GlobalResource<ResType> {
fn from(arc: Arc<ResType>) -> Self {
Self { res_arc: arc }
}
}
impl<ResType: 'static + Send + Sync> std::ops::Deref for GlobalResource<ResType> {
type Target = ResType;
fn deref(&self) -> &Self::Target {
&self.res_arc
}
}
impl<ResType: 'static + Send + Sync> AsRef<ResType> for GlobalResource<ResType> {
fn as_ref(&self) -> &ResType {
&self.res_arc
}
}
/// Marks a type as a **program global resource** (`Res`) that can be stored in the
/// [`GlobalResContainer`].
///
/// # Purpose
///
/// `ResourceMarker` is a marker trait that resource types must implement, providing three fundamental
/// capabilities:
///
/// 1. **Cloning** (`__resource_marker_clone`) — when a resource in the container is held by an external
/// shared snapshot (such as a [`GlobalResource`]), modification operations need to clone an independent
/// copy for modification, to avoid affecting the external snapshot.
/// 2. **Default instantiation** (`__resource_marker_default`) — when a resource entry is missing, or the
/// lock is poisoned, the container needs a default instance as a fallback value.
/// 3. **Modification through the global program container** (`__resource_marker_modify`) — locates the
/// currently active [`Program<C>`] via the type parameter `C` and performs a read-modify-write
/// operation on the `&mut Self` resource within it.
///
/// # Relationship with `Default + Clone`
///
/// This trait provides an **automatic blanket implementation** for all types satisfying
/// `T: Default + Clone + Send + Sync + 'static`, so ordinary user-defined data types do not need to
/// manually implement `ResourceMarker`. If a type has custom "default value" or "cloning" semantics
/// (for example, if the resource internally contains `Arc`, `Rc`, singleton references, etc.), users may
/// also **manually implement** this trait to override the default behavior.
///
/// # Comparison of the Three Methods' Uses
///
/// | Method | Invocation Scenario | Corresponding Blanket Implementation |
/// |--------|-------------------|--------------------------------------|
/// | `__resource_marker_clone` | When the resource is held by a shared snapshot, clone a copy before modification | `Clone::clone` |
/// | `__resource_marker_default` | Fallback value when the resource is missing or the lock is poisoned | `Default::default` |
/// | `__resource_marker_modify` | Perform a read-modify-write on `&mut Self` in the global program container | Calls `this::<C>().modify_res(f)` |
///
/// # Role in Macro Expansion
///
/// In code expanded from `#[chain]`, `#[resource]`, and similar macros, wherever a type needs to be
/// treated as a resource for injection, modification, extraction, or storage, this trait's constraint
/// (`Res: ResourceMarker`) is implicitly relied upon. The macro code itself does not care about the
/// specific type of the resource; it only requires that the type implements the three capabilities
/// of this trait.
///
/// # Constraints
///
/// Types implementing this trait must simultaneously satisfy `'static + Send + Sync`, to ensure
/// that the resource can be safely shared across threads and does not carry a non-static lifetime.
///
/// # Note
///
/// All methods of this trait are **`#[doc(hidden)]`** internal methods and should not be called directly
/// in business code. The public APIs exposed are [`GlobalResContainer::with_resource`],
/// [`GlobalResContainer::modify_res`], [`GlobalResContainer::res`], etc.
///
/// [`GlobalResContainer`]: crate::GlobalResContainer
/// [`GlobalResource`]: crate::GlobalResource
/// [`Program<C>`]: crate::Program
/// [`this`]: crate::this
/// [`GlobalResContainer::with_resource`]: crate::GlobalResContainer::with_resource
/// [`GlobalResContainer::modify_res`]: crate::GlobalResContainer::modify_res
/// [`GlobalResContainer::res`]: crate::GlobalResContainer::res
pub trait ResourceMarker {
/// Clones the current resource value and returns an independent new instance.
///
/// # Invocation Scenario
///
/// When an external caller holds a shared snapshot of the resource (with an `Arc` strong reference
/// count > 1), the container's modification operation (such as [`modify_res`](GlobalResContainer::modify_res))
/// cannot directly take ownership of the resource, so this method is called to **clone a copy**
/// for modification, ensuring the external snapshot is not affected.
///
/// # Implementation Conventions
///
/// - Must return an independent instance that is logically equivalent (with the same value) to
/// `self`; modifying the return value must not affect the original value.
/// - The blanket implementation directly delegates to `Clone::clone(self)`.
/// - For types containing reference-counted structures such as `Arc` or `Rc`, the underlying data
/// should be deep-cloned rather than merely copying the reference, unless sharing is explicitly
/// the intended semantics.
#[must_use]
#[doc(hidden)]
fn __resource_marker_clone(&self) -> Self;
/// Constructs a default instance of the type, used as a fallback value when the resource is missing
/// or the lock is poisoned.
///
/// # Invocation Scenario
///
/// This method is called in the following scenarios:
/// - When obtaining a resource snapshot via [`res_or_default`](GlobalResContainer::res_or_default),
/// but the resource entry does not exist in the container or the lock is poisoned;
/// - When performing a read-modify-write via
/// [`__modify_res_and_return_route`](GlobalResContainer::__modify_res_and_return_route),
/// if the resource entry does not exist or the lock is poisoned, a temporary default instance
/// needs to be constructed for use by the closure;
/// - When extracting a resource via [`__extract_res_mut`](GlobalResContainer::__extract_res_mut),
/// if the resource entry does not exist or the lock is poisoned.
///
/// # Implementation Conventions
///
/// - Each call should return a **brand new** default instance and accept no parameters.
/// - The blanket implementation directly delegates to `Default::default()`.
/// - If the type's default value has special semantics (for example, default configuration,
/// empty collection, zero value, etc.), this should be reflected here.
#[doc(hidden)]
fn __resource_marker_default() -> Self;
/// Performs a **read-modify-write** operation on a resource of type `Self` in the currently active
/// global program container.
///
/// # Generic Parameters
///
/// - `C`: The program collector type. Must satisfy `ProgramCollect<Enum = C> + 'static`,
/// used to locate the currently active [`Program<C>`](crate::Program).
///
/// # Parameters
///
/// - `f`: A closure receiving `&mut Self`, within which the resource value is modified. The closure's
/// return value is not used (returns `()`).
///
/// # Behavior
///
/// This method is internally equivalent to calling:
///
/// ```text
/// this::<C>().modify_res(f)
/// ```
///
/// where `this::<C>()` obtains the thread-bound global [`Program<C>`](crate::Program) instance,
/// and then calls its [`modify_res`](crate::Program::modify_res) method to complete the
/// read-modify-write. If the resource does not exist, `modify_res` returns `()` (the `Default`
/// value of `Return`) without calling `f`.
///
/// # Role in Macro Expansion
///
/// In code expanded from `#[chain]` and similar macros, when a resource needs to be modified via
/// the global program container without explicitly obtaining a container reference, this method is
/// called. It automatically locates the correct program instance via the type parameter `C`,
/// simplifying code generation logic.
#[doc(hidden)]
fn __resource_marker_modify<C>(f: impl FnOnce(&mut Self))
where
C: ProgramCollect<Enum = C> + 'static;
}
impl<T> ResourceMarker for T
where
T: Default + Clone + Send + Sync + 'static,
{
fn __resource_marker_clone(&self) -> Self {
Clone::clone(self)
}
fn __resource_marker_default() -> Self {
Default::default()
}
fn __resource_marker_modify<C>(f: impl FnOnce(&mut Self))
where
C: ProgramCollect<Enum = C> + 'static,
{
this::<C>().modify_res(f);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::MockProgramCollect;
use crate::error::ChainProcessError;
#[test]
fn global_resource_new_and_deref() {
let res = GlobalResource::new(42i32);
assert_eq!(*res, 42);
}
#[test]
fn global_resource_from_arc() {
let arc = Arc::new(42i32);
let res = GlobalResource::from(arc);
assert_eq!(*res, 42);
}
#[test]
fn global_resource_as_ref() {
let res = GlobalResource::new(42i32);
assert_eq!(res.as_ref(), &42);
}
#[test]
fn resource_marker_i32_res_clone() {
let val = 42i32;
let cloned = val.__resource_marker_clone();
assert_eq!(cloned, 42);
}
#[test]
fn resource_marker_i32_res_default() {
assert_eq!(<i32 as ResourceMarker>::__resource_marker_default(), 0i32);
}
#[test]
fn resource_marker_string_res_clone() {
let val = "hello".to_string();
let cloned = val.__resource_marker_clone();
assert_eq!(cloned, "hello");
}
#[test]
fn resource_marker_string_res_default() {
assert_eq!(<String as ResourceMarker>::__resource_marker_default(), "");
}
#[test]
fn resource_marker_vec_res_clone() {
let val = vec![1, 2, 3];
let cloned = val.__resource_marker_clone();
assert_eq!(cloned, vec![1, 2, 3]);
}
#[test]
fn resource_marker_vec_res_default() {
let empty: Vec<i32> = vec![];
assert_eq!(
<Vec<i32> as ResourceMarker>::__resource_marker_default(),
empty
);
}
#[test]
fn container_new_creates_empty_store() {
let container = GlobalResContainer::new();
assert!(container.res::<i32>().is_none());
}
#[test]
fn container_insert_then_res() {
let mut container = GlobalResContainer::new();
container.with_resource(42i32);
let res = container.res::<i32>();
assert_eq!(*res.unwrap(), 42);
}
#[test]
fn container_missing_res_returns_none() {
let container = GlobalResContainer::new();
assert!(container.res::<String>().is_none());
}
#[test]
fn container_res_or_default_creates_default() {
let container = GlobalResContainer::new();
assert_eq!(*container.res_or_default::<i32>(), 0);
}
#[test]
fn container_res_or_default_returns_existing() {
let mut container = GlobalResContainer::new();
container.with_resource(7i32);
assert_eq!(*container.res_or_default::<i32>(), 7);
}
#[test]
fn container_modify_res_updates_value() {
let mut container = GlobalResContainer::new();
container.with_resource(1i32);
let doubled = container.modify_res(|v: &mut i32| {
*v *= 2;
*v
});
assert_eq!(doubled, 2);
assert_eq!(*container.res::<i32>().unwrap(), 2);
}
#[test]
fn container_modify_res_missing_returns_default() {
let container = GlobalResContainer::new();
let value: i32 = container.modify_res(|v: &mut i32| *v);
assert_eq!(value, 0);
}
#[test]
fn container_modify_res_through_shared_reference() {
let mut container = GlobalResContainer::new();
container.with_resource(10i32);
let shared = &container;
shared.modify_res(|v: &mut i32| *v += 5);
assert_eq!(*container.res::<i32>().unwrap(), 15);
}
#[test]
fn container_modify_res_clones_when_shared() {
let mut container = GlobalResContainer::new();
container.with_resource(10i32);
// Hold a shared handle so `Arc::try_unwrap` fails and the resource is cloned out
let handle = container.res::<i32>().unwrap();
container.modify_res(|v: &mut i32| *v += 5);
assert_eq!(*container.res::<i32>().unwrap(), 15);
assert_eq!(*handle, 10);
}
#[test]
fn container_extract_res_mut_takes_value_out() {
let mut container = GlobalResContainer::new();
container.with_resource(3i32);
let extracted: i32 = container.__extract_res_mut();
assert_eq!(extracted, 3);
// The slot is reset to a default value after the extraction
assert_eq!(*container.res::<i32>().unwrap(), 0);
}
#[test]
fn container_extract_res_mut_clones_when_shared() {
let mut container = GlobalResContainer::new();
container.with_resource(3i32);
// Hold a shared handle so `Arc::try_unwrap` fails and the resource is cloned out
let _handle = container.res::<i32>().unwrap();
let extracted: i32 = container.__extract_res_mut();
assert_eq!(extracted, 3);
// The slot is reset to a default value after the extraction
assert_eq!(*container.res::<i32>().unwrap(), 0);
}
#[test]
fn container_store_res_inserts_value() {
let container = GlobalResContainer::new();
container.__store_res(8i32);
assert_eq!(*container.res::<i32>().unwrap(), 8);
}
#[test]
fn container_extract_store_roundtrip() {
let mut container = GlobalResContainer::new();
container.with_resource(7i32);
let value: i32 = container.__extract_res_mut();
container.__store_res(value + 1);
assert_eq!(*container.res::<i32>().unwrap(), 8);
}
#[test]
fn container_res_shared_handles_share_the_arc() {
let mut container = GlobalResContainer::new();
container.with_resource(String::from("hello"));
let handle_a = container.res::<String>().unwrap();
let handle_b = container.res::<String>().unwrap();
assert_eq!(*handle_a, "hello");
assert_eq!(*handle_b, "hello");
assert!(Arc::ptr_eq(&handle_a.res_arc, &handle_b.res_arc));
}
#[test]
fn container_res_or_route_missing_returns_route() {
let container = GlobalResContainer::new();
let route: ChainProcess<MockProgramCollect> =
ChainProcess::Err(ChainProcessError::Other("missing".into()));
let result = container.res_or_route::<i32, MockProgramCollect>(route);
assert!(result.is_err());
}
#[test]
fn container_res_or_route_present_returns_resource() {
let mut container = GlobalResContainer::new();
container.with_resource(5i32);
let route: ChainProcess<MockProgramCollect> =
ChainProcess::Err(ChainProcessError::Other("missing".into()));
let Ok(resource) = container.res_or_route::<i32, MockProgramCollect>(route) else {
panic!("expected the resource to be present");
};
assert_eq!(*resource, 5);
}
#[test]
fn container_modify_res_and_return_route_works() {
let mut container = GlobalResContainer::new();
container.with_resource(1i32);
let route: ChainProcess<MockProgramCollect> =
container.__modify_res_and_return_route(|v: &mut i32| {
*v += 1;
ChainProcess::Err(ChainProcessError::Other("done".into()))
});
assert!(matches!(route, ChainProcess::Err(_)));
assert_eq!(*container.res::<i32>().unwrap(), 2);
}
#[test]
fn container_nested_modify_res_different_types_do_not_deadlock() {
let mut container = GlobalResContainer::new();
container.with_resource(1i32).with_resource("a".to_string());
// Two `&mut` injections nest `modify_res` calls; each resource has its
// own mutex, so the inner call must not deadlock against the outer one.
container.modify_res(|count: &mut i32| {
*count += 10;
container.modify_res(|text: &mut String| {
text.push('b');
});
});
assert_eq!(*container.res::<i32>().unwrap(), 11);
assert_eq!(*container.res::<String>().unwrap(), "ab");
}
#[test]
fn container_nested_modify_res_and_return_route_no_deadlock() {
let mut container = GlobalResContainer::new();
container.with_resource(1i32).with_resource("a".to_string());
let route: ChainProcess<MockProgramCollect> =
container.__modify_res_and_return_route(|count: &mut i32| {
*count += 10;
container.__modify_res_and_return_route(|text: &mut String| {
text.push('b');
ChainProcess::Err(ChainProcessError::Other("done".into()))
})
});
assert!(matches!(route, ChainProcess::Err(_)));
assert_eq!(*container.res::<i32>().unwrap(), 11);
assert_eq!(*container.res::<String>().unwrap(), "ab");
}
#[test]
fn container_res_inside_modify_of_another_resource() {
let mut container = GlobalResContainer::new();
container.with_resource(1i32).with_resource("a".to_string());
container.modify_res(|count: &mut i32| {
// Reading a different resource while holding this one's lock must
// not deadlock either.
assert_eq!(*container.res::<String>().unwrap(), "a");
*count += 10;
});
assert_eq!(*container.res::<i32>().unwrap(), 11);
}
#[test]
fn container_multiple_instances_are_independent() {
let mut first = GlobalResContainer::new();
let mut second = GlobalResContainer::new();
first.with_resource(1i32);
second.with_resource(2i32);
first.modify_res(|v: &mut i32| *v += 10);
assert_eq!(*first.res::<i32>().unwrap(), 11);
assert_eq!(*second.res::<i32>().unwrap(), 2);
// A resource present in one container is invisible to the other
assert!(first.res::<String>().is_none());
assert!(second.res::<String>().is_none());
}
#[test]
fn program_resource_methods_delegate_to_container() {
let mut program = crate::Program::<MockProgramCollect>::new_with_args(Vec::<String>::new());
program.with_resource(1i32);
assert_eq!(*program.res::<i32>().unwrap(), 1);
program.modify_res(|v: &mut i32| *v += 1);
assert_eq!(*program.res::<i32>().unwrap(), 2);
assert_eq!(*program.res_or_default::<i32>(), 2);
assert_eq!(*program.res_or_default::<String>(), "");
}
}
|