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
use std::{
    hash::{Hash, Hasher},
    sync::Arc,
};

use anymap::AnyMap;
use fj_math::Point;
use parking_lot::{RwLock, RwLockReadGuard};
use slotmap::{DefaultKey, SlotMap};

use crate::{
    geometry::{Curve, Surface},
    topology::{Cycle, Edge, Face, Vertex},
};

use super::Object;

#[derive(Clone, Debug)]
pub struct Stores {
    pub points: Points,
    pub curves: Curves,
    pub surfaces: Surfaces,

    pub vertices: Vertices,
    pub edges: Edges,
    pub cycles: Cycles,
    pub faces: Faces,
}

impl Stores {
    pub fn get<T>(&self) -> Store<T>
    where
        T: Object,
    {
        let mut stores = AnyMap::new();

        stores.insert(self.points.clone());
        stores.insert(self.curves.clone());
        stores.insert(self.surfaces.clone());

        stores.insert(self.vertices.clone());
        stores.insert(self.edges.clone());
        stores.insert(self.cycles.clone());
        stores.insert(self.faces.clone());

        stores
            .remove::<Store<T>>()
            // Can't panic, as `T` is bound by `Object`, and we added the stores
            // for all types of objects above.
            .expect("Invalid object type")
    }
}

pub type Points = Store<Point<3>>;
pub type Curves = Store<Curve>;
pub type Surfaces = Store<Surface>;

pub type Vertices = Store<Vertex>;
pub type Edges = Store<Edge>;
pub type Cycles = Store<Cycle>;
pub type Faces = Store<Face>;

#[derive(Debug)]
pub struct Store<T> {
    objects: Arc<RwLock<Objects<T>>>,
}

impl<T> Store<T> {
    pub fn new() -> Self {
        Self {
            objects: Arc::new(RwLock::new(SlotMap::new())),
        }
    }

    pub fn insert(&mut self, object: T) -> Handle<T> {
        let key = self.objects.write().insert(object);
        Handle::new(key, self.clone())
    }

    pub fn contains(&self, object: &Handle<T>) -> bool {
        object.store() == self && self.objects.read().contains_key(object.key())
    }

    pub fn read(&self) -> RwLockReadGuard<Objects<T>> {
        self.objects.read()
    }

    pub fn iter(&self) -> Iter<T> {
        // The allocation here is unfortunate, but I think it's fine for now. If
        // this turns into a performance issue, it should be possible to avoid
        // it by adding methods to `Store`, that are geared towards implementing
        // iterators.
        Iter {
            elements: self
                .objects
                .read()
                .iter()
                .map(|(key, _)| Handle::new(key, self.clone()))
                .collect(),
        }
    }

    pub fn update<F>(&mut self, mut f: F)
    where
        F: FnMut(&mut T),
    {
        for (_, object) in self.objects.write().iter_mut() {
            f(object);
        }
    }

    fn ptr(&self) -> *const () {
        Arc::as_ptr(&self.objects) as _
    }
}

// Deriving `Clone` would only derive `Clone` where `T: Clone`. This
// implementation doesn't have that limitation, providing `Clone` for all
// `Store`s instead.
impl<T> Clone for Store<T> {
    fn clone(&self) -> Self {
        Self {
            objects: self.objects.clone(),
        }
    }
}

impl<T> Default for Store<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> PartialEq for Store<T> {
    fn eq(&self, other: &Self) -> bool {
        self.ptr().eq(&other.ptr())
    }
}

impl<T> Eq for Store<T> {}

impl<T> Ord for Store<T> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.ptr().cmp(&other.ptr())
    }
}

impl<T> PartialOrd for Store<T> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<T> Hash for Store<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.ptr().hash(state);
    }
}

pub type Objects<T> = SlotMap<DefaultKey, T>;

/// A handle to an object stored within [`Shape`]
///
/// If an object of type `T` (this could be `Curve`, `Vertex`, etc.) is added to
/// `Shape`, a `Handle<T>` is returned. This handle is then used in topological
/// types to refer to the object, instead of having those types own an instance
/// of the object.
///
/// This approach has two advantages:
///
/// 1. The object can't be mutated through the handle. Since an object can be
///    referred to by multiple other objects, mutating it locally would have no
///    effect on those other references. `Handle` preventing that removes this
///    source of errors.
/// 2. The object is guaranteed to be in `Shape`, as `Handle`s can't be created
///    any other way. This means that if the `Shape` needs to be modified, any
///    objects can be updated once, without requiring an update of all the other
///    objects that reference it.
///
/// # Equality
///
/// The equality of [`Handle`] is very strictly defined in terms of identity.
/// Two [`Handle`]s are considered equal, if they refer to objects in the same
/// memory location.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct Handle<T> {
    key: DefaultKey,
    store: Store<T>,
}

impl<T> Handle<T> {
    pub(super) fn new(key: DefaultKey, store: Store<T>) -> Self {
        Self { key, store }
    }

    pub(super) fn key(&self) -> DefaultKey {
        self.key
    }

    pub(super) fn store(&self) -> &Store<T> {
        &self.store
    }

    /// Access the object that the handle references
    pub fn get(&self) -> T
    where
        T: Clone,
    {
        self.store
            .read()
            .get(self.key)
            // Can't panic, unless the handle was invalid in the first place.
            // Objects are never removed from `Store`, so if we have a handle
            // pointing to it, it should be there.
            .unwrap()
            .clone()
    }
}

/// An iterator over geometric or topological objects
///
/// Returned by various methods of the [`Shape`] API.
pub struct Iter<T> {
    elements: Vec<Handle<T>>,
}

impl<T> Iter<T> {
    /// Convert this iterator over handles into an iterator over values
    ///
    /// This is a convenience method, for cases where no `Handle` is needed.
    pub fn values(self) -> impl Iterator<Item = T>
    where
        T: Clone,
    {
        self.elements.into_iter().map(|handle| handle.get())
    }
}

impl<T> Iterator for Iter<T> {
    type Item = Handle<T>;

    fn next(&mut self) -> Option<Self::Item> {
        self.elements.pop()
    }
}