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
pub mod edge;
pub mod face;
pub mod path;
mod traverse;
pub mod vertex;

use fool::BoolExt;
use std::ops::{Deref, DerefMut};

use crate::graph::borrow::{Reborrow, ReborrowMut};
use crate::graph::core::Bind;
use crate::graph::mutation::Consistent;
use crate::graph::storage::key::OpaqueKey;
use crate::graph::storage::payload::Payload;
use crate::graph::storage::{AsStorage, AsStorageMut};
use crate::graph::GraphError;

pub trait IntoKeyedSource<T>: Sized {
    fn into_keyed_source(self) -> T;
}

pub trait FromKeyedSource<T>: Sized {
    fn from_keyed_source(source: T) -> Option<Self>;
}

pub trait IntoView<T>: Sized {
    fn into_view(self) -> Option<T>;
}

impl<T, U> IntoView<U> for T
where
    T: Sized,
    U: FromKeyedSource<T>,
{
    fn into_view(self) -> Option<U> {
        U::from_keyed_source(self)
    }
}

/// A key paired with storage in a graph.
///
/// This trait is implemented by views over specific structures in a graph,
/// such as a vertex or face. Note that rings and paths are views over various
/// structures, and as such do not implement this trait.
pub trait Entry: Deref<Target = <Self as Entry>::Payload> {
    // This associated type is redundant, but avoids re-exporting the
    // `Payload` trait and simplifies the use of this trait.
    type Key: OpaqueKey;
    type Payload: Payload<Key = Self::Key>;

    /// Gets the key for the view.
    fn key(&self) -> Self::Key;

    /// Rekeys a view into another.
    ///
    /// Rekeying a view allows its underlying storage to be reinterpretted. The
    /// output view must also be bound to a payload.
    ///
    /// # Examples
    ///
    /// Perform a fallible traversal and preserve mutability of the resulting
    /// view:
    ///
    /// ```rust,no_run
    /// # use plexus::graph::{Entry, MeshGraph};
    /// # use plexus::prelude::*;
    /// #
    /// # let mut graph = MeshGraph::<()>::default();
    /// # let key = graph.faces().keys().nth(0).unwrap();
    /// // ...
    /// let face = graph.face_mut(key).unwrap();
    /// // Find a face along a boundary. If no such face is found, continue to use the
    /// // initiating face.
    /// let mut face = {
    ///     let key = face
    ///         .traverse_by_depth()
    ///         .find(|face| {
    ///             face.interior_arcs()
    ///                 .map(|arc| arc.into_opposite_arc())
    ///                 .any(|arc| arc.is_boundary_arc())
    ///         })
    ///         .map(|face| face.key());
    ///     if let Some(key) = key {
    ///         face.rekey(key).unwrap() // Rekey into the boundary face.
    ///     }
    ///     else {
    ///         face
    ///     }
    /// };
    /// ```
    fn rekey<T, M>(self, key: T::Key) -> Result<T, GraphError>
    where
        Self: Into<View<M, <Self as Entry>::Payload>>,
        T: From<View<M, <T as Entry>::Payload>> + Entry,
        M: Reborrow,
        M::Target: AsStorage<Self::Payload> + AsStorage<T::Payload>,
    {
        self.into()
            .rekey_map::<_, T::Payload>(key)
            .ok_or_else(|| GraphError::TopologyNotFound)
    }
}

pub struct View<M, T>
where
    M: Reborrow,
    M::Target: AsStorage<T>,
    T: Payload,
{
    key: T::Key,
    storage: M,
}

impl<M, T> View<M, T>
where
    M: Reborrow,
    M::Target: AsStorage<T>,
    T: Payload,
{
    fn from_keyed_source_unchecked(source: (T::Key, M)) -> Self {
        let (key, storage) = source;
        View { key, storage }
    }

    pub fn key(&self) -> T::Key {
        self.key
    }

    pub fn bind<U, N>(self, storage: N) -> View<<M as Bind<U, N>>::Output, T>
    where
        U: Payload,
        N: AsStorage<U>,
        M: Bind<U, N>,
        M::Output: Reborrow,
        <M::Output as Reborrow>::Target: AsStorage<T>,
    {
        let (key, source) = self.into_keyed_source();
        View::from_keyed_source_unchecked((key, source.bind(storage)))
    }

    pub fn rekey<U>(self, key: U::Key) -> Option<View<M, U>>
    where
        U: Payload,
        M::Target: AsStorage<U>,
    {
        let (_, storage) = self.into_keyed_source();
        (key, storage).into_view()
    }

    pub fn rekey_map<V, U>(self, key: U::Key) -> Option<V>
    where
        V: From<View<M, U>>,
        U: Payload,
        M::Target: AsStorage<U>,
    {
        self.rekey(key).map(V::from)
    }

    pub fn interior_reborrow(&self) -> View<&M::Target, T> {
        View::from_keyed_source_unchecked((self.key, self.storage.reborrow()))
    }
}

impl<M, T> View<M, T>
where
    M: ReborrowMut,
    M::Target: AsStorage<T>,
    T: Payload,
{
    pub fn interior_reborrow_mut(&mut self) -> View<&mut M::Target, T> {
        View::from_keyed_source_unchecked((self.key, self.storage.reborrow_mut()))
    }
}

impl<'a, M, T> View<&'a mut M, T>
where
    M: 'a + AsStorageMut<T>,
    T: 'a + Payload,
{
    pub fn into_orphan(self) -> Orphan<'a, T> {
        let (key, storage) = self.into_keyed_source();
        (key, storage).into_view().unwrap()
    }

    pub fn into_ref(self) -> View<&'a M, T> {
        let (key, storage) = self.into_keyed_source();
        (key, &*storage).into_view().unwrap()
    }
}

impl<M, T> Clone for View<M, T>
where
    M: Clone + Reborrow,
    M::Target: AsStorage<T>,
    T: Payload,
{
    fn clone(&self) -> Self {
        View {
            storage: self.storage.clone(),
            key: self.key,
        }
    }
}

impl<M, T> Copy for View<M, T>
where
    M: Copy + Reborrow,
    M::Target: AsStorage<T>,
    T: Payload,
{
}

impl<M, T> Deref for View<M, T>
where
    M: Reborrow,
    M::Target: AsStorage<T>,
    T: Payload,
{
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.storage
            .reborrow()
            .as_storage()
            .get(&self.key)
            .expect("view key invalidated")
    }
}

impl<M, T> DerefMut for View<M, T>
where
    M: ReborrowMut,
    M::Target: AsStorageMut<T>,
    T: Payload,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.storage
            .reborrow_mut()
            .as_storage_mut()
            .get_mut(&self.key)
            .expect("view key invalidated")
    }
}

impl<M, T> FromKeyedSource<(T::Key, M)> for View<M, T>
where
    M: Reborrow,
    M::Target: AsStorage<T>,
    T: Payload,
{
    fn from_keyed_source(source: (T::Key, M)) -> Option<Self> {
        let (key, storage) = source;
        storage
            .reborrow()
            .as_storage()
            .contains_key(&key)
            .some(View::from_keyed_source_unchecked((key, storage)))
    }
}

impl<M, T> IntoKeyedSource<(T::Key, M)> for View<M, T>
where
    M: Reborrow,
    M::Target: AsStorage<T>,
    T: Payload,
{
    fn into_keyed_source(self) -> (T::Key, M) {
        let View { key, storage, .. } = self;
        (key, storage)
    }
}

// TODO: Consider implementing `Eq` for views.
impl<M, T> PartialEq for View<M, T>
where
    M: Reborrow,
    M::Target: AsStorage<T> + Consistent,
    T: Payload,
{
    fn eq(&self, other: &Self) -> bool {
        self.key == other.key
    }
}

pub struct Orphan<'a, T>
where
    T: Payload,
{
    key: T::Key,
    payload: &'a mut T,
}

impl<'a, T> Orphan<'a, T>
where
    T: 'a + Payload,
{
    pub fn from_keyed_source_unchecked(source: (T::Key, &'a mut T)) -> Self {
        let (key, payload) = source;
        Orphan { key, payload }
    }

    pub fn key(&self) -> T::Key {
        self.key
    }
}

impl<'a, T> Deref for Orphan<'a, T>
where
    T: 'a + Payload,
{
    type Target = T;

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

impl<'a, T> DerefMut for Orphan<'a, T>
where
    T: 'a + Payload,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.payload
    }
}

impl<'a, M, T> FromKeyedSource<(T::Key, &'a mut M)> for Orphan<'a, T>
where
    M: AsStorageMut<T>,
    T: 'a + Payload,
{
    fn from_keyed_source(source: (T::Key, &'a mut M)) -> Option<Self> {
        let (key, storage) = source;
        storage
            .as_storage_mut()
            .get_mut(&key)
            .map(|payload| Orphan { key, payload })
    }
}