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
use std::{any::TypeId, fmt::Debug};

use fn_graph::{
    resman::{BorrowFail, Ref},
    DataAccess, DataAccessDyn, Resources, TypeIds,
};
use peace_core::ItemId;

use crate::Data;

/// A resource that may or may not exist.
///
/// For a mutable version of this, see [`WMaybe`].
///
/// [`WMaybe`]: crate::WMaybe
#[derive(Clone, Debug, PartialEq)]
pub struct RMaybe<'borrow, T>(Option<Ref<'borrow, T>>)
where
    T: Debug + Send + Sync + 'static;

impl<'borrow, T> From<Option<Ref<'borrow, T>>> for RMaybe<'borrow, T>
where
    T: Debug + Send + Sync + 'static,
{
    fn from(opt: Option<Ref<'borrow, T>>) -> Self {
        Self(opt)
    }
}

impl<'borrow, T> std::ops::Deref for RMaybe<'borrow, T>
where
    T: Debug + Send + Sync + 'static,
{
    type Target = Option<Ref<'borrow, T>>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'borrow, T> Data<'borrow> for RMaybe<'borrow, T>
where
    T: Debug + Send + Sync + 'static,
{
    fn borrow(_item_id: &'borrow ItemId, resources: &'borrow Resources) -> Self {
        resources
            .try_borrow::<T>()
            .map_err(|borrow_fail| match borrow_fail {
                e @ BorrowFail::ValueNotFound => e,
                BorrowFail::BorrowConflictImm | BorrowFail::BorrowConflictMut => {
                    panic!("Encountered {borrow_fail:?}")
                }
            })
            .ok()
            .into()
    }
}

impl<'borrow, T> DataAccess for RMaybe<'borrow, T>
where
    T: Debug + Send + Sync + 'static,
{
    fn borrows() -> TypeIds
    where
        Self: Sized,
    {
        let mut type_ids = TypeIds::new();
        type_ids.push(TypeId::of::<T>());
        type_ids
    }

    fn borrow_muts() -> TypeIds
    where
        Self: Sized,
    {
        TypeIds::new()
    }
}

impl<'borrow, T> DataAccessDyn for RMaybe<'borrow, T>
where
    T: Debug + Send + Sync + 'static,
{
    fn borrows(&self) -> TypeIds
    where
        Self: Sized,
    {
        let mut type_ids = TypeIds::new();
        type_ids.push(TypeId::of::<T>());
        type_ids
    }

    fn borrow_muts(&self) -> TypeIds
    where
        Self: Sized,
    {
        TypeIds::new()
    }
}