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
use std::{
    any::type_name,
    collections::BTreeMap,
    fmt::{self, Debug},
    ops::{Deref, DerefMut},
    sync::Arc,
};

use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use type_map::TypeMap;

use crate::{
    insert::Insert,
    objects::Objects,
    partial::traits::PartialObject,
    services::Service,
    storage::{Handle, ObjectId},
};

use super::HasPartial;

/// Wrapper around a partial object
///
/// Controls access to the partial object. Can be cloned, to access the same
/// partial object from multiple locations.
pub struct Partial<T: HasPartial> {
    inner: Inner<T>,
}

impl<T: HasPartial + 'static> Partial<T> {
    /// Construct a `Partial` with a default inner partial object
    pub fn new() -> Self {
        Self::from_partial(T::Partial::default())
    }

    /// Construct a `Partial` from a partial object
    pub fn from_partial(partial: T::Partial) -> Self {
        let inner = Inner::new(InnerObject {
            partial,
            full: None,
        });
        Self { inner }
    }

    /// Construct a partial from a full object
    pub fn from_full(full: Handle<T>, cache: &mut FullToPartialCache) -> Self {
        let inner = match cache.get(&full) {
            Some(inner) => inner,
            None => {
                let inner = Inner::new(InnerObject {
                    partial: T::Partial::from_full(&full, cache),
                    full: Some(full.clone()),
                });

                cache.insert(&full, inner.clone());

                inner
            }
        };

        Self { inner }
    }

    /// Access the ID of this partial object
    pub fn id(&self) -> ObjectId {
        self.inner.id()
    }

    /// Access the partial object
    pub fn read(&self) -> impl Deref<Target = T::Partial> + '_ {
        RwLockReadGuard::map(self.inner.read(), |inner| &inner.partial)
    }

    /// Access the partial object mutably
    ///
    /// # Panics
    ///
    /// Panics, if this method is called while the return value from a previous
    /// call to this method of [`Self::read`] is still borrowed.
    pub fn write(&mut self) -> impl DerefMut<Target = T::Partial> + '_ {
        let mut inner = self.inner.write();

        // If we created this partial object from a full one and then modify it,
        // it should not map back to the full object when calling `build`.
        inner.full = None;

        RwLockWriteGuard::map(inner, |inner| &mut inner.partial)
    }

    /// Build a full object from this partial one
    ///
    /// # Panics
    ///
    /// Panics, if a call to [`Self::write`] would panic.
    pub fn build(self, objects: &mut Service<Objects>) -> Handle<T>
    where
        T: Insert,
    {
        let mut inner = self.inner.write();

        // If another instance of this `Partial` has already been built, re-use
        // the resulting full object.
        let partial = inner.partial.clone();
        let full = inner
            .full
            .get_or_insert_with(|| partial.build(objects).insert(objects));

        full.clone()
    }
}

impl<T: HasPartial + 'static> fmt::Debug for Partial<T>
where
    T::Partial: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = {
            let type_name = type_name::<T::Partial>();
            match type_name.rsplit_once("::") {
                Some((_, name)) => name,
                None => type_name,
            }
        };
        let id = self.id().0;
        let object = self.read().clone();

        if f.alternate() {
            write!(f, "{name} @ {id:#x} => {object:#?}")?;
        } else {
            write!(f, "{name} @ {id:#x}")?;
        }

        Ok(())
    }
}

impl<T: HasPartial> Clone for Partial<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<T: HasPartial + 'static> Default for Partial<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: HasPartial + 'static> From<Handle<T>> for Partial<T> {
    fn from(full: Handle<T>) -> Self {
        let mut cache = FullToPartialCache::default();
        Self::from_full(full, &mut cache)
    }
}

#[derive(Debug)]
struct Inner<T: HasPartial>(Arc<RwLock<InnerObject<T>>>);

impl<T: HasPartial> Inner<T> {
    fn new(inner: InnerObject<T>) -> Self {
        Self(Arc::new(RwLock::new(inner)))
    }

    fn id(&self) -> ObjectId {
        ObjectId::from_ptr(Arc::as_ptr(&self.0))
    }

    fn read(&self) -> RwLockReadGuard<InnerObject<T>> {
        self.0
            .try_read()
            .expect("Tried to read `Partial` that is currently being modified")
    }

    fn write(&self) -> RwLockWriteGuard<InnerObject<T>> {
        self.0
            .try_write()
            .expect("Tried to modify `Partial` that is currently locked")
    }
}

impl<T: HasPartial> Clone for Inner<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

#[derive(Debug)]
struct InnerObject<T: HasPartial> {
    partial: T::Partial,
    full: Option<Handle<T>>,
}

/// Caches conversions from full to partial objects
///
/// When creating a whole graph of partial objects from a graph of full ones,
/// the conversions must be cached, to ensure that each full object maps to
/// exactly one partial object.
///
/// Used by [`Partial::from_full`] and [`PartialObject::from_full`].
#[derive(Default)]
pub struct FullToPartialCache(TypeMap);

impl FullToPartialCache {
    fn get<T>(&mut self, handle: &Handle<T>) -> Option<Inner<T>>
    where
        T: HasPartial + 'static,
    {
        self.map().get(&handle.id()).cloned()
    }

    fn insert<T>(&mut self, handle: &Handle<T>, inner: Inner<T>)
    where
        T: HasPartial + 'static,
    {
        self.map().insert(handle.id(), inner);
    }

    fn map<T>(&mut self) -> &mut BTreeMap<ObjectId, Inner<T>>
    where
        T: HasPartial + 'static,
    {
        self.0
            .entry::<BTreeMap<ObjectId, Inner<T>>>()
            .or_insert_with(BTreeMap::new)
    }
}