1use std::{fmt::Debug, marker::PhantomData, sync::Arc};
4
5use once_map::OnceMap;
6
7use crate::prelude::*;
8
9pub type AtomicUntypedResource = Arc<UntypedResource>;
11
12pub struct UntypedResource {
17 cell: AtomicCell<Option<SchemaBox>>,
18 schema: &'static Schema,
19}
20
21impl std::fmt::Debug for UntypedResource {
22 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23 f.debug_struct("UntypedResource").finish_non_exhaustive()
24 }
25}
26
27impl UntypedResource {
28 pub fn empty(schema: &'static Schema) -> Self {
30 Self {
31 cell: AtomicCell::new(None),
32 schema,
33 }
34 }
35
36 pub fn new(resource: SchemaBox) -> Self {
38 Self {
39 schema: resource.schema(),
40 cell: AtomicCell::new(Some(resource)),
41 }
42 }
43
44 pub fn from_default(schema: &'static Schema) -> Self {
47 Self {
48 cell: AtomicCell::new(Some(SchemaBox::default(schema))),
49 schema,
50 }
51 }
52
53 pub fn clone_data(&self) -> Option<SchemaBox> {
56 (*self.cell.borrow()).clone()
57 }
58
59 pub fn insert(&self, data: SchemaBox) -> Result<Option<SchemaBox>, SchemaMismatchError> {
63 self.schema.ensure_match(data.schema())?;
64 let mut data = Some(data);
65 std::mem::swap(&mut data, &mut *self.cell.borrow_mut());
66 Ok(data)
67 }
68
69 pub fn remove(&self) -> Option<SchemaBox> {
71 let mut data = None;
72 std::mem::swap(&mut data, &mut *self.cell.borrow_mut());
73 data
74 }
75
76 #[track_caller]
78 pub fn borrow(&self) -> Ref<'_, Option<SchemaBox>> {
79 self.cell.borrow()
80 }
81
82 #[track_caller]
84 pub fn borrow_mut(&self) -> RefMut<'_, Option<SchemaBox>> {
85 self.cell.borrow_mut()
86 }
87
88 pub fn schema(&self) -> &'static Schema {
90 self.schema
91 }
92}
93
94#[derive(Default)]
101pub struct UntypedResources {
102 resources: OnceMap<SchemaId, AtomicUntypedResource>,
103 shared_resources: OnceMap<SchemaId, Box<()>>,
104}
105
106impl Clone for UntypedResources {
107 fn clone(&self) -> Self {
108 let binding = self.resources.read_only_view();
109 let resources = binding.iter().map(|(_, v)| (v.schema, v));
110
111 let new_resources = OnceMap::default();
112 let new_shared_resources = OnceMap::default();
113 for (schema, resource_cell) in resources {
114 let is_shared = self.shared_resources.contains_key(&schema.id());
115
116 if !is_shared {
117 let resource = resource_cell.clone_data();
118 new_resources.map_insert(
119 schema.id(),
120 |_| Arc::new(UntypedResource::empty(schema)),
121 |_, cell| {
122 if let Some(resource) = resource {
123 cell.insert(resource).unwrap();
124 }
125 },
126 );
127 } else {
128 new_shared_resources.insert(schema.id(), |_| Box::new(()));
129 new_resources.insert(schema.id(), |_| resource_cell.clone());
130 }
131 }
132 Self {
133 resources: new_resources,
134 shared_resources: new_shared_resources,
135 }
136 }
137}
138
139#[derive(Debug, Clone, Copy)]
141pub struct CellAlreadyPresentError;
142impl std::fmt::Display for CellAlreadyPresentError {
143 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144 f.write_str("Resource cell already present")
145 }
146}
147impl std::error::Error for CellAlreadyPresentError {}
148
149impl UntypedResources {
150 pub fn new() -> Self {
152 Self::default()
153 }
154
155 pub fn contains_cell(&self, id: SchemaId) -> bool {
157 self.resources.contains_key(&id)
158 }
159
160 pub fn contains(&self, id: SchemaId) -> bool {
162 self.resources
163 .map_get(&id, |_, cell| cell.borrow().is_some())
164 .unwrap_or_default()
165 }
166
167 pub fn insert_cell(&self, cell: AtomicUntypedResource) -> Result<(), CellAlreadyPresentError> {
179 let schema = cell.schema;
180 if self.resources.contains_key(&schema.id()) {
181 Err(CellAlreadyPresentError)
182 } else {
183 self.resources.insert(schema.id(), |_| cell);
184 self.shared_resources.insert(schema.id(), |_| Box::new(()));
185 Ok(())
186 }
187 }
188
189 pub fn get(&self, schema: &'static Schema) -> &UntypedResource {
191 self.resources
192 .insert(schema.id(), |_| Arc::new(UntypedResource::empty(schema)))
193 }
194
195 pub fn get_cell(&self, schema: &'static Schema) -> AtomicUntypedResource {
197 self.resources.map_insert(
198 schema.id(),
199 |_| Arc::new(UntypedResource::empty(schema)),
200 |_, cell| cell.clone(),
201 )
202 }
203
204 pub fn retain_resources<F>(&self, mut predicate: F)
208 where
209 F: FnMut(SchemaId) -> bool,
210 {
211 for (schema_id, resource_cell) in self.resources.read_only_view().iter() {
212 let is_retained = predicate(*schema_id);
213 if !is_retained {
214 resource_cell.remove();
215 }
216 }
217 }
218
219 pub fn retain_owned_resources<F>(&self, mut predicate: F)
223 where
224 F: FnMut(SchemaId) -> bool,
225 {
226 for (schema_id, resource_cell) in self.resources.read_only_view().iter() {
227 let is_shared = self.shared_resources.contains_key(schema_id);
228 let is_retained = predicate(*schema_id);
229 if !is_shared && !is_retained {
230 resource_cell.remove();
231 }
232 }
233 }
234
235 pub fn clear_owned_resources(&self) {
237 for (schema_id, resource_cell) in self.resources.read_only_view().iter() {
238 let is_shared = self.shared_resources.contains_key(schema_id);
239 if !is_shared {
240 resource_cell.remove();
241 }
242 }
243 }
244}
245
246#[derive(Clone, Default)]
250pub struct Resources {
251 untyped: UntypedResources,
252}
253
254impl Resources {
255 pub fn new() -> Self {
257 Self::default()
258 }
259
260 pub fn insert<T: HasSchema>(&self, resource: T) -> Option<T> {
262 self.untyped
263 .get(T::schema())
264 .insert(SchemaBox::new(resource))
265 .unwrap()
266 .map(|x| x.cast_into())
267 }
268
269 pub fn contains<T: HasSchema>(&self) -> bool {
273 self.untyped.contains(T::schema().id())
274 }
275
276 pub fn remove<T: HasSchema>(&self) -> Option<T> {
278 self.untyped
279 .get(T::schema())
280 .remove()
281 .map(|x| unsafe { x.cast_into_unchecked() })
283 }
284
285 #[track_caller]
287 pub fn get<T: HasSchema>(&self) -> Option<Ref<'_, T>> {
288 let b = self.untyped.get(T::schema()).borrow();
289 if b.is_some() {
290 Some(Ref::map(b, |b| unsafe {
291 b.as_ref().unwrap().as_ref().cast_into_unchecked()
292 }))
293 } else {
294 None
295 }
296 }
297
298 #[track_caller]
300 pub fn get_mut<T: HasSchema>(&self) -> Option<RefMut<'_, T>> {
301 let b = self.untyped.get(T::schema()).borrow_mut();
302 if b.is_some() {
303 Some(RefMut::map(b, |b| unsafe {
304 b.as_mut().unwrap().as_mut().cast_into_mut_unchecked()
305 }))
306 } else {
307 None
308 }
309 }
310
311 pub fn get_cell<T: HasSchema>(&self) -> AtomicResource<T> {
313 let untyped = self.untyped.get_cell(T::schema()).clone();
314 AtomicResource {
315 untyped,
316 _phantom: PhantomData,
317 }
318 }
319
320 pub fn untyped(&self) -> &UntypedResources {
322 &self.untyped
323 }
324
325 pub fn into_untyped(self) -> UntypedResources {
327 self.untyped
328 }
329
330 pub fn clear_owned_resources(&self) {
332 self.untyped().clear_owned_resources();
333 }
334}
335
336#[derive(Clone)]
343pub struct AtomicResource<T: HasSchema> {
344 untyped: AtomicUntypedResource,
345 _phantom: PhantomData<T>,
346}
347impl<T: HasSchema + Debug> Debug for AtomicResource<T> {
348 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
349 f.write_str("AtomicResource(")?;
350 self.untyped
351 .cell
352 .borrow()
353 .as_ref()
354 .map(|x| x.cast_ref::<T>())
355 .fmt(f)?;
356 f.write_str(")")?;
357 Ok(())
358 }
359}
360
361impl<T: HasSchema + Default> Default for AtomicResource<T> {
362 fn default() -> Self {
363 Self {
364 untyped: Arc::new(UntypedResource::new(SchemaBox::new(T::default()))),
365 _phantom: Default::default(),
366 }
367 }
368}
369
370impl<T: HasSchema> AtomicResource<T> {
371 pub fn empty() -> Self {
373 Self {
374 untyped: Arc::new(UntypedResource::empty(T::schema())),
375 _phantom: PhantomData,
376 }
377 }
378
379 pub fn new(data: T) -> Self {
381 AtomicResource {
382 untyped: Arc::new(UntypedResource::new(SchemaBox::new(data))),
383 _phantom: PhantomData,
384 }
385 }
386
387 pub fn from_untyped(untyped: AtomicUntypedResource) -> Result<Self, SchemaMismatchError> {
389 T::schema().ensure_match(untyped.schema)?;
390 Ok(AtomicResource {
391 untyped,
392 _phantom: PhantomData,
393 })
394 }
395
396 pub fn remove(&self) -> Option<T> {
398 self.untyped
399 .remove()
400 .map(|x| unsafe { x.cast_into_unchecked() })
402 }
403
404 pub fn borrow(&self) -> Option<Ref<'_, T>> {
408 let borrow = self.untyped.borrow();
409 if borrow.is_some() {
410 Some(Ref::map(borrow, |r| unsafe {
411 r.as_ref().unwrap().as_ref().cast_into_unchecked()
412 }))
413 } else {
414 None
415 }
416 }
417
418 pub fn borrow_mut(&self) -> Option<RefMut<'_, T>> {
422 let borrow = self.untyped.borrow_mut();
423 if borrow.is_some() {
424 Some(RefMut::map(borrow, |r| unsafe {
425 r.as_mut().unwrap().as_mut().cast_into_mut_unchecked()
426 }))
427 } else {
428 None
429 }
430 }
431
432 pub fn into_untyped(self) -> AtomicUntypedResource {
434 self.untyped
435 }
436}
437
438impl<T: HasSchema + FromWorld> AtomicResource<T> {
439 pub fn init(&self, world: &World) {
441 let mut borrow = self.untyped.borrow_mut();
442 if unlikely(borrow.is_none()) {
443 *borrow = Some(SchemaBox::new(T::from_world(world)))
444 }
445 }
446
447 #[track_caller]
449 pub fn init_borrow(&self, world: &World) -> Ref<'_, T> {
450 let map_borrow = |borrow| {
451 Ref::map(borrow, |b: &Option<SchemaBox>| unsafe {
453 b.as_ref().unwrap().as_ref().cast_into_unchecked()
454 })
455 };
456 let borrow = self.untyped.borrow();
457 if unlikely(borrow.is_none()) {
458 drop(borrow);
459 {
460 let mut borrow_mut = self.untyped.borrow_mut();
461 *borrow_mut = Some(SchemaBox::new(T::from_world(world)));
462 }
463
464 map_borrow(self.untyped.borrow())
465 } else {
466 map_borrow(borrow)
467 }
468 }
469
470 #[track_caller]
472 pub fn init_borrow_mut(&self, world: &World) -> RefMut<'_, T> {
473 let mut borrow = self.untyped.borrow_mut();
474 if unlikely(borrow.is_none()) {
475 *borrow = Some(SchemaBox::new(T::from_world(world)));
476 }
477 RefMut::map(borrow, |b| unsafe {
478 b.as_mut().unwrap().as_mut().cast_into_mut_unchecked()
479 })
480 }
481}
482
483#[derive(Default)]
486pub struct UntypedResourceSet {
487 resources: Vec<UntypedResource>,
488}
489
490impl Clone for UntypedResourceSet {
491 fn clone(&self) -> Self {
492 Self {
493 resources: self
494 .resources
495 .iter()
496 .map(|res| {
497 if let Some(clone) = res.clone_data() {
498 UntypedResource::new(clone)
499 } else {
500 UntypedResource::empty(res.schema())
501 }
502 })
503 .collect(),
504 }
505 }
506}
507
508impl UntypedResourceSet {
509 pub fn insert_resource<T: HasSchema>(&mut self, resource: T) {
513 for r in &mut self.resources {
515 if r.schema() == T::schema() {
516 let mut borrow = r.borrow_mut();
517
518 if let Some(b) = borrow.as_mut() {
519 *b.cast_mut() = resource;
520 } else {
521 *borrow = Some(SchemaBox::new(resource))
522 }
523 return;
524 }
525 }
526
527 self.resources
529 .push(UntypedResource::new(SchemaBox::new(resource)))
530 }
531
532 pub fn init_resource<T: HasSchema + Default>(&mut self) -> RefMut<'_, T> {
535 if !self.resources.iter().any(|x| x.schema() == T::schema()) {
536 self.insert_resource(T::default());
537 }
538 self.resource_mut::<T>().unwrap()
539 }
540
541 #[track_caller]
543 pub fn resource_mut<T: HasSchema>(&self) -> Option<RefMut<'_, T>> {
544 let res = self.resources.iter().find(|x| x.schema() == T::schema())?;
545 let borrow = res.borrow_mut();
546
547 if borrow.is_some() {
548 Some(RefMut::map(borrow, |b| unsafe {
550 b.as_mut().unwrap().as_mut().cast_into_mut_unchecked()
551 }))
552 } else {
553 None
554 }
555 }
556
557 pub fn insert_empty<T: HasSchema>(&mut self) {
560 for r in &mut self.resources {
561 if r.schema() == T::schema() {
562 let mut borrow = r.borrow_mut();
563 *borrow = None;
564 return;
565 }
566 }
567
568 self.resources.push(UntypedResource::empty(T::schema()));
570 }
571
572 pub fn resources(&self) -> &Vec<UntypedResource> {
574 &self.resources
575 }
576
577 pub fn insert_on_world(&self, world: &World, remove_empty: bool) {
582 for resource in self.resources.iter() {
583 let resource_cell = world.resources.untyped().get_cell(resource.schema());
584
585 if let Some(resource_copy) = resource.clone_data() {
587 resource_cell
588 .insert(resource_copy)
589 .expect("Schema mismatch error");
590 } else if remove_empty {
591 resource_cell.remove();
593 }
594 }
595 }
596}
597
598#[cfg(test)]
599mod test {
600 use std::sync::Arc;
601
602 use crate::prelude::*;
603 #[derive(HasSchema, Clone, Debug, Default)]
604 #[repr(C)]
605 struct A(String);
606
607 #[derive(HasSchema, Clone, Debug, Default)]
608 #[repr(C)]
609 struct B(u32);
610
611 #[test]
612 fn sanity_check() {
613 let r1 = Resources::new();
614
615 r1.insert(A(String::from("hi")));
616 let r1a = r1.get_cell::<A>();
617 assert_eq!(r1a.borrow().unwrap().0, "hi");
618
619 let r2 = r1.clone();
620
621 r1.insert(A(String::from("bye")));
622 r1.insert(A(String::from("world")));
623 assert_eq!(r1a.borrow().unwrap().0, "world");
624
625 let r2a = r2.get_cell::<A>();
626 assert_eq!(r2a.borrow().unwrap().0, "hi");
627
628 r1.insert(B(1));
629 let r1b = r1.get_cell::<B>();
630 assert_eq!(r1b.borrow().unwrap().0, 1);
631 r1.insert(B(2));
632 assert_eq!(r1b.borrow().unwrap().0, 2);
633 assert_eq!(r1a.borrow().unwrap().0, "world");
634 }
635
636 #[test]
637 fn resources_clear_owned_values() {
638 let r = Resources::new();
639
640 r.insert(A(String::from("foo")));
642
643 r.untyped
645 .insert_cell(Arc::new(UntypedResource::new(SchemaBox::new(B(1)))))
646 .unwrap();
647
648 r.clear_owned_resources();
650
651 let res_a = r.get::<A>();
653 assert!(res_a.is_none());
654
655 let res_b = r.get::<B>().unwrap();
657 assert_eq!(res_b.0, 1);
658 }
659}