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
use std::{
any::TypeId,
fmt,
ops::{Deref, DerefMut},
};
use rt_map::{BorrowFail, Cell, RtMap};
use crate::{Entry, Ref, RefMut, Resource};
/// Map from `TypeId` to type.
#[derive(Default)]
pub struct Resources(RtMap<TypeId, Box<dyn Resource>>);
/// A [Resource] container, which provides methods to insert, access and manage
/// the contained resources.
///
/// Many methods take `&self` which works because everything
/// is stored with **interior mutability**. In case you violate
/// the borrowing rules of Rust (multiple reads xor one write),
/// you will get a panic.
///
/// # Resource Ids
///
/// Resources are identified by `TypeId`s, which consist of a `TypeId`.
impl Resources {
/// Creates an empty `Resources` map.
///
/// The map is initially created with a capacity of 0, so it will not
/// allocate until it is first inserted into.
///
/// # Examples
///
/// ```rust
/// use resman::Resources;
/// let mut resources = Resources::new();
/// ```
pub fn new() -> Self {
Self::default()
}
/// Creates an empty `Resources` map with the specified capacity.
///
/// The map will be able to hold at least capacity elements without
/// reallocating. If capacity is 0, the map will not allocate.
///
/// # Examples
///
/// ```rust
/// use resman::Resources;
/// let resources: Resources = Resources::with_capacity(10);
/// ```
pub fn with_capacity(capacity: usize) -> Self {
Self(RtMap::with_capacity(capacity))
}
/// Returns the number of elements the map can hold without reallocating.
///
/// This number is a lower bound; the `Resources<K, V>` might be able to
/// hold more, but is guaranteed to be able to hold at least this many.
///
/// # Examples
///
/// ```rust
/// use resman::Resources;
/// let resources: Resources = Resources::with_capacity(100);
/// assert!(resources.capacity() >= 100);
/// ```
pub fn capacity(&self) -> usize {
self.0.capacity()
}
/// Returns an entry for the resource with type `R`.
pub fn entry<R>(&mut self) -> Entry<R>
where
R: Resource,
{
Entry::new(self.0.entry(TypeId::of::<R>()))
}
/// Inserts a resource into the map. If the resource existed before,
/// it will be overwritten.
///
/// # Examples
///
/// Every type satisfying `Any + Send + Sync` automatically
/// implements `Resource`, thus can be added:
///
/// ```rust
/// # #![allow(dead_code)]
/// struct MyRes(i32);
/// ```
///
/// When you have a resource, simply insert it like this:
///
/// ```rust
/// # #[derive(Debug)]
/// # struct MyRes(i32);
/// use resman::Resources;
///
/// let mut resources = Resources::default();
/// resources.insert(MyRes(5));
/// ```
pub fn insert<R>(&mut self, r: R)
where
R: Resource,
{
self.0.insert(TypeId::of::<R>(), Box::new(r));
}
/// Inserts an already boxed resource into the map.
pub fn insert_raw(&mut self, type_id: TypeId, resource: Box<dyn Resource>) {
self.0.insert(type_id, resource);
}
/// Removes a resource of type `R` from this container and returns its
/// ownership to the caller. In case there is no such resource in this,
/// container, `None` will be returned.
///
/// Use this method with caution; other functions and systems might assume
/// this resource still exists. Thus, only use this if you're sure no
/// system will try to access this resource after you removed it (or else
/// you will get a panic).
pub fn remove<R>(&mut self) -> Option<R>
where
R: Resource,
{
self.0
.remove(&TypeId::of::<R>())
.map(|x: Box<dyn Resource>| x.downcast())
.map(|x: Result<Box<R>, _>| x.ok().unwrap())
.map(|x| *x)
}
/// Returns true if the specified resource type `R` exists in `self`.
pub fn contains<R>(&self) -> bool
where
R: Resource,
{
self.0.contains_key(&TypeId::of::<R>())
}
/// Returns the `R` resource in the resource map.
///
/// See [`try_borrow`] for a non-panicking version of this function.
///
/// # Panics
///
/// Panics if the resource doesn't exist.
/// Panics if the resource is being accessed mutably.
///
/// [`try_borrow`]: Self::try_borrow
pub fn borrow<R>(&self) -> Ref<R>
where
R: Resource,
{
self.try_borrow::<R>()
.unwrap_or_else(Self::borrow_panic::<R, _>)
}
/// Returns an immutable reference to `R` if it exists, `None` otherwise.
pub fn try_borrow<R>(&self) -> Result<Ref<R>, BorrowFail>
where
R: Resource,
{
self.0.try_borrow(&TypeId::of::<R>()).map(Ref::new)
}
/// Returns a mutable reference to `R` if it exists, `None` otherwise.
///
/// # Panics
///
/// Panics if the resource doesn't exist.
/// Panics if the resource is already accessed.
pub fn borrow_mut<R>(&self) -> RefMut<R>
where
R: Resource,
{
self.try_borrow_mut::<R>()
.unwrap_or_else(Self::borrow_panic::<R, _>)
}
/// Returns a mutable reference to `R` if it exists, `None` otherwise.
pub fn try_borrow_mut<R>(&self) -> Result<RefMut<R>, BorrowFail>
where
R: Resource,
{
self.0.try_borrow_mut(&TypeId::of::<R>()).map(RefMut::new)
}
/// Retrieves a resource without fetching, which is cheaper, but only
/// available with `&mut self`.
pub fn get_mut<R: Resource>(&mut self) -> Option<&mut R> {
self.get_resource_mut(TypeId::of::<R>())
.map(|res| res.downcast_mut().unwrap())
}
/// Retrieves a resource without fetching, which is cheaper, but only
/// available with `&mut self`.
pub fn get_resource_mut(&mut self, id: TypeId) -> Option<&mut dyn Resource> {
self.0.get_resource_mut(&id).map(|resource| &mut **resource)
}
/// Get raw access to the underlying cell.
pub fn get_raw(&self, id: &TypeId) -> Option<&Cell<Box<dyn Resource>>> {
self.0.get_raw(id)
}
fn borrow_panic<R, Ret>(borrow_fail: BorrowFail) -> Ret {
let type_name = std::any::type_name::<R>();
match borrow_fail {
BorrowFail::ValueNotFound => {
panic!("Expected to borrow `{type_name}`, but it does not exist.")
}
BorrowFail::BorrowConflictImm => panic!(
"Expected to borrow `{type_name}` immutably, but it was already borrowed mutably."
),
BorrowFail::BorrowConflictMut => panic!(
"Expected to borrow `{type_name}` mutably, but it was already borrowed mutably."
),
}
}
}
#[cfg(not(feature = "debug"))]
impl fmt::Debug for Resources {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut debug_map = f.debug_map();
self.0.keys().for_each(|type_id| {
let resource = &*self.0.borrow(type_id);
let type_name = resource.as_ref().type_name();
// At runtime, we are unable to determine if the resource is `Debug`.
debug_map.entry(&type_name, &"..");
});
debug_map.finish()
}
}
#[cfg(feature = "debug")]
impl fmt::Debug for Resources {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut debug_map = f.debug_map();
self.0.keys().for_each(|type_id| {
let resource = &*self.0.borrow(type_id);
let type_name = resource.as_ref().type_name();
debug_map.entry(&type_name, resource);
});
debug_map.finish()
}
}
impl Deref for Resources {
type Target = RtMap<TypeId, Box<dyn Resource>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for Resources {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(test)]
mod tests {
use std::any::TypeId;
use super::Resources;
use crate::BorrowFail;
#[test]
fn entry_or_insert_inserts_value() {
#[derive(Debug, PartialEq)]
struct A(usize);
let mut resources = Resources::new();
let mut a_ref = resources.entry::<A>().or_insert(A(1));
assert_eq!(&A(1), &*a_ref);
*a_ref = A(2);
drop(a_ref);
assert_eq!(&A(2), &*resources.borrow::<A>());
}
#[cfg(not(feature = "debug"))]
#[test]
fn debug_uses_placeholder_for_values() {
let mut resources = Resources::new();
resources.insert(1u32);
resources.insert(2u64);
let resources_dbg = format!("{:?}", resources);
assert!(
resources_dbg.contains(r#"u32: "..""#),
r#"Expected `{}` to contain `u32: ".."`"#,
resources_dbg
);
assert!(
resources_dbg.contains(r#"u64: "..""#),
r#"Expected `{}` to contain `u64: ".."`"#,
resources_dbg
);
}
#[cfg(feature = "debug")]
#[test]
fn debug_uses_debug_implementation_for_values() {
let mut resources = Resources::new();
resources.insert(1u32);
resources.insert(2u64);
let resources_dbg = format!("{:?}", resources);
assert!(
resources_dbg.contains(r#"u32: 1"#),
r#"Expected `{}` to contain `u32: 1`"#,
resources_dbg
);
assert!(
resources_dbg.contains(r#"u64: 2"#),
r#"Expected `{}` to contain `u64: 2`"#,
resources_dbg
);
}
#[test]
fn with_capacity_reserves_enough_capacity() {
let map = Resources::with_capacity(100);
assert!(map.capacity() >= 100);
}
#[test]
fn insert() {
#[cfg_attr(feature = "debug", derive(Debug))]
struct Foo;
let mut resources = Resources::default();
resources.insert(Res);
assert!(resources.contains::<Res>());
assert!(!resources.contains::<Foo>());
}
#[test]
fn insert_raw() {
#[cfg_attr(feature = "debug", derive(Debug))]
struct Foo;
let mut resources = Resources::default();
resources.insert_raw(TypeId::of::<Res>(), Box::new(Res));
assert!(resources.contains::<Res>());
assert!(!resources.contains::<Foo>());
}
#[test]
#[should_panic(
expected = "Expected to borrow `resman::resources::tests::Res` mutably, but it was already borrowed mutably."
)]
fn read_write_fails() {
let mut resources = Resources::default();
resources.insert(Res);
let _read = resources.borrow::<Res>();
let _write = resources.borrow_mut::<Res>();
}
#[test]
#[should_panic(expected = "but it was already borrowed mutably")]
fn write_read_fails() {
let mut resources = Resources::default();
resources.insert(Res);
let _write = resources.borrow_mut::<Res>();
let _read = resources.borrow::<Res>();
}
#[test]
fn remove_insert() {
let mut resources = Resources::default();
resources.insert(Res);
assert!(resources.contains::<Res>());
resources.remove::<Res>().unwrap();
assert!(!resources.contains::<Res>());
resources.insert(Res);
assert!(resources.contains::<Res>());
}
#[test]
#[should_panic(
expected = "Expected to borrow `resman::resources::tests::Res`, but it does not exist."
)]
fn borrow_before_insert_panics() {
let resources = Resources::default();
resources.borrow::<Res>();
}
#[test]
#[should_panic(
expected = "Expected to borrow `resman::resources::tests::Res`, but it does not exist."
)]
fn borrow_mut_before_insert_panics() {
let resources = Resources::default();
resources.borrow_mut::<Res>();
}
#[test]
fn borrow_mut_try_borrow_returns_err() {
let mut resources = Resources::default();
resources.insert(Res);
let _res = resources.borrow_mut::<Res>();
assert_eq!(
Err(BorrowFail::BorrowConflictImm),
resources.try_borrow::<Res>()
);
}
#[test]
fn borrow_try_borrow_mut_returns_err() {
let mut resources = Resources::default();
resources.insert(Res);
let _res = resources.borrow::<Res>();
assert_eq!(
Err(BorrowFail::BorrowConflictMut),
resources.try_borrow_mut::<Res>()
);
}
#[test]
fn borrow_mut_borrow_mut_returns_err() {
let mut resources = Resources::default();
resources.insert(Res);
let _res = resources.borrow_mut::<Res>();
assert_eq!(
Err(BorrowFail::BorrowConflictMut),
resources.try_borrow_mut::<Res>()
);
}
#[test]
fn get_mut_returns_ok() {
let mut resources = Resources::default();
resources.insert(Res);
let _res = resources.get_mut::<Res>();
assert!(resources.try_borrow_mut::<Res>().is_ok());
}
#[test]
fn get_resource_mut_returns_some() {
let mut resources = Resources::default();
resources.insert(Res);
assert!(resources.get_resource_mut(TypeId::of::<Res>()).is_some());
}
#[test]
fn get_raw_returns_some() {
let mut resources = Resources::default();
resources.insert(Res);
assert!(resources.get_raw(&TypeId::of::<Res>()).is_some());
}
#[derive(Debug, Default, PartialEq)]
struct Res;
}