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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
use std::mem;
use crate::idtree;
use densevec::DenseVec;
use crate::sync::{ReadGuardRef, WriteGuardRef, Lock};
use crate::storage::{
    Storage, IntoIter, IntoIterMut, HierarchicalStorage,
    IntoOrderedIter, IntoOrderedIterMut, IntoIdedIterMut, IntoOrderedIdedIterMut,
    OrderedId,
};
use crate::utils::*;
use std::slice;

pub struct Forest<T>{
    arena: idtree::Arena<T>,
    roots: Vec<idtree::NodeId>,
    index: DenseVec<idtree::NodeId>,
    reverse_index: DenseVec<usize>,
    ordered_ids: Lock<Vec<OrderedId<idtree::NodeId>>>,
}

// Is this actually Send + Sync?
// Only needed for Mutcell in Lock which should be safe?
unsafe impl<T: Send> Send for Forest<T>{}
unsafe impl<T: Sync> Sync for Forest<T>{}

impl<'a, T: 'a> Storage<'a, T> for Forest<T>{
    type Get = &'a T;
    type GetMut = &'a mut T;
    type DerefTarget = T;
    type IdedIter = idtree::AllIdedData<'a,T>;
    type Iter = idtree::AllData<'a, T>;
    type IterMut = idtree::AllDataMut<'a, T>;

    fn new() -> Forest<T>{
        Forest{
            arena: idtree::Arena::new(),
            roots: Vec::new(),
            index: DenseVec::new(),
            reverse_index: DenseVec::new(),
            ordered_ids: Lock::new(vec![]),
        }
    }

    fn with_capacity(capacity: usize) -> Forest<T>{
        Forest{
            arena: idtree::Arena::with_capacity(capacity),
            roots: Vec::with_capacity(capacity),
            index: DenseVec::with_capacity(capacity),
            reverse_index: DenseVec::with_capacity(capacity),
            ordered_ids: Lock::new(Vec::with_capacity(capacity)),
        }
    }

    fn insert(&mut self, guid: usize, t: T){
        let node_id = self.arena.new_node(t);
        self.index.insert(guid, node_id.id());
        self.reverse_index.insert(node_id.id().id(), guid);
        self.roots.push(node_id.id());
        self.ordered_ids.get_mut().clear();
    }

    fn remove(&mut self, guid: usize){
        {
            let id = unsafe{ self.index.get_unchecked(guid) };
            self.arena.remove(*id);
            if let Some(pos) = self.roots.iter().position(|i| i == id){
                self.roots.remove(pos);
            }
            self.reverse_index.remove(id.id());
        }
        self.index.remove(guid);
        self.ordered_ids.get_mut().clear();
    }

    unsafe fn get(&self, guid: usize) -> &'a T{
        let node_id = self.index.get_unchecked(guid);
        delete_lifetime(&self.arena[*node_id])
    }

    unsafe fn get_mut(&mut self, guid: usize) -> &'a mut T{
        let node_id = self.index.get_unchecked(guid);
        delete_lifetime_mut(&mut self.arena[*node_id])
    }

    unsafe fn fast_get(&self, guid: usize) -> &'a T{
        let node_id = self.index.get_fast_unchecked(guid);
        delete_lifetime(&self.arena[*node_id])
    }

    unsafe fn fast_get_mut(&mut self, guid: usize) -> &'a mut T{
        let node_id = self.index.get_fast_unchecked(guid);
        delete_lifetime_mut(&mut self.arena[*node_id])
    }

    fn fast_index(&self, guid: usize) -> usize{
        self.index.fast_index(guid)
    }

    fn guid_from_fast_index(&self, idx: usize) -> usize{
        unsafe{ self.index.unchecked_guid_from_fast_index(idx) }
    }

    fn contains(&self, guid: usize) -> bool{
        self.index.contains(guid)
    }

    fn ided_iter(&self) -> Self::IdedIter{
        unsafe{ mem::transmute(self.arena.all_ided_data()) }
    }

    fn iter(&self) -> Self::Iter{
        unsafe{ mem::transmute(self.arena.all_data()) }
    }

    fn iter_mut(&mut self) -> Self::IterMut{
        unsafe{ mem::transmute(self.arena.all_data_mut()) }
    }
}

pub struct Iter<'a, T: 'a>{
    _guard: ReadGuardRef<'a, Forest<T>>,
    it: idtree::AllNodes<'a, T>,
}

impl<'a, T: 'a> Iterator for Iter<'a, T>{
    type Item = &'a T;
    #[inline]
    fn next(&mut self) -> Option<&'a T>{
        self.it.next().map(|node| &node.data)
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.it.size_hint()
    }
}

impl<'a, T: 'a> ExactSizeIterator for Iter<'a, T>{
    #[inline]
    fn len(&self) -> usize {
        self.it.len()
    }
}

impl<'a, T> IntoIter for ReadGuardRef<'a, Forest<T>>{
    type Iter = Iter<'a, T>;
    fn into_iter(self) -> Iter<'a, T>{
        Iter{
            it: unsafe{mem::transmute::<idtree::AllNodes<T>, idtree::AllNodes<T>>(self.arena.all_nodes())},
            _guard: self,
        }
    }
}

pub struct IterMut<'a, T: 'a>{
    _guard: WriteGuardRef<'a, Forest<T>>,
    it: idtree::AllNodesMut<'a, T>
}

impl<'a, T: 'a> Iterator for IterMut<'a, T>{
    type Item = &'a mut T;
    #[inline]
    fn next(&mut self) -> Option<&'a mut T>{
        self.it.next().map(|node| &mut node.data)
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.it.size_hint()
    }
}

impl<'a, T: 'a> ExactSizeIterator for IterMut<'a, T>{
    #[inline]
    fn len(&self) -> usize {
        self.it.len()
    }
}

impl<'a, T> IntoIterMut for WriteGuardRef<'a, Forest<T>>{
    type IterMut = IterMut<'a, T>;
    fn into_iter_mut(mut self) -> IterMut<'a, T>{
        IterMut{
            it: unsafe{mem::transmute::<idtree::AllNodesMut<T>, idtree::AllNodesMut<T>>(self.arena.all_nodes_mut())},
            _guard: self,
        }
    }
}

pub struct IdedIterMut<'a, T: 'a>{
    _guard: WriteGuardRef<'a, Forest<T>>,
    iter: densevec::IterMut<'a, usize, idtree::Node<T>>,
}

impl<'a, T: 'a> Iterator for IdedIterMut<'a, T>{
    type Item = (usize, &'a mut T);
    #[inline]
    fn next(&mut self) -> Option<(usize, &'a mut T)>{
        self.iter.next().map(|(id, node)| (id, &mut node.data))
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<'a, T: 'a> ExactSizeIterator for IdedIterMut<'a, T>{
    #[inline]
    fn len(&self) -> usize {
        self.iter.len()
    }
}

impl<'a, T> IntoIdedIterMut for WriteGuardRef<'a, Forest<T>>{
    type IdedIterMut = IdedIterMut<'a, T>;
    fn into_ided_iter_mut(mut self) -> IdedIterMut<'a, T>{
        IdedIterMut{
            iter: unsafe{mem::transmute(self.arena.all_nodes_ided_mut())},
            _guard: self,
        }
    }
}

impl<'a,T: 'a> HierarchicalStorage<'a,T> for Forest<T>{
    unsafe fn insert_child(&mut self, parent_guid: usize, guid: usize, value: T){
        let parent_id = *self.index.get_unchecked(parent_guid);
        let node_id = self.arena.get_mut(parent_id).append_new(value);
        self.index.insert(guid, node_id.id());
        self.reverse_index.insert(node_id.id().id(), guid);
        self.ordered_ids.get_mut().clear();
    }

    unsafe fn get_node(&self, guid: usize) -> idtree::NodeRef<T>{
        let node_id = self.index.get_unchecked(guid);
        self.arena.get(*node_id)
    }

    unsafe fn get_node_mut(&mut self, guid: usize) -> idtree::NodeRefMut<T>{
        let node_id = self.index.get_unchecked(guid);
        self.arena.get_mut(*node_id)
    }

    unsafe fn fast_get_node(&self, idx: idtree::NodeId) -> idtree::NodeRef<T>{
        self.arena.get(idx)
    }

    unsafe fn fast_get_node_mut(&mut self, idx: idtree::NodeId) -> idtree::NodeRefMut<T>{
        self.arena.get_mut(idx)
    }

    //TODO: this is terribly unoptimized
    fn ordered_ids(&self) -> ReadGuardRef<Vec<OrderedId<idtree::NodeId>>>{
        if self.ordered_ids.read().is_empty() {
            let iter_tree = ForestHierarchicalIdsIter{
                forest: self,
                current: if self.roots.is_empty(){ None } else { Some(0) },
                iter: if self.roots.is_empty(){ None } else { Some(self.roots[0].descendants(&self.arena)) }
            };
            self.ordered_ids
                .write()
                .extend(iter_tree
                    .map(|id| OrderedId{
                        guid: unsafe{ *self.reverse_index.get_unchecked(id.id()) },
                        fast: id,
                    })
                );
        }
        ReadGuardRef::new(self.ordered_ids.read())
    }

    unsafe fn guid_for(&self, nodeid: idtree::NodeId) -> usize{
        *self.reverse_index.get_unchecked(nodeid.id())
    }

    unsafe fn ordered_fast_index(&self, guid: usize) -> idtree::NodeId{
        *self.index.get_unchecked(guid)
    }
}

impl<'a, T> IntoOrderedIter for ReadGuardRef<'a, Forest<T>>{
    type OrderedIter = ForestHierarchicalIter<'a,T>;
    fn into_ordered_iter(self) -> Self::OrderedIter{
        // We need this cause there's no way to split a Send Lock, should be safe
        // since we are holding a read reference to the storage and we fill the ids
        // here so no one will modify it while we iterate and no one will need
        // to fill the ordered ids cache either
        let ordered_ids = {
            let ordered_ids = self.ordered_ids();
            let ptr = ordered_ids.as_ptr();
            let len = ordered_ids.len();
            unsafe{ slice::from_raw_parts(ptr, len) }
        };
        ForestHierarchicalIter{
            ordered_ids,
            forest: self,
            next: 0,
        }
    }
}

struct ForestHierarchicalIdsIter<'a, T: 'a>{
    forest: &'a Forest<T>,
    current: Option<usize>,
    iter: Option<idtree::Descendants<'a, T>>,
}

impl<'a, T: 'a> Iterator for ForestHierarchicalIdsIter<'a, T>{
    type Item = idtree::NodeId;
    fn next(&mut self) -> Option<idtree::NodeId>{
        let iter = if let Some(ref mut iter) = self.iter{
            let next = iter.next();
            if let Some(next) = next{
                return Some(self.forest.arena.get(next).id());
            }else{
                if let Some(current) = self.current{
                    if current + 1 < self.forest.roots.len(){
                        self.current = Some(current + 1);
                        Some(self.forest.roots[current + 1].descendants(&self.forest.arena))
                    }else{
                        self.current = None;
                        None
                    }
                }else{
                    None
                }
            }
        }else{
            None
        };

        if let Some(mut iter) = iter{
            let next = iter.next().map(|id| self.forest.arena.get(id).id() );
            self.iter = Some(iter);
            next
        }else{
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>){
        (self.forest.arena.len(), Some(self.forest.arena.len()))
    }
}

impl<'a, T: 'a> ExactSizeIterator for ForestHierarchicalIdsIter<'a, T>{
    #[inline]
    fn len(&self) -> usize {
        self.forest.arena.len()
    }
}

pub struct ForestHierarchicalIter<'a, T: 'a>{
    forest: ReadGuardRef<'a, Forest<T>>,
    ordered_ids: &'a [OrderedId<idtree::NodeId>],
    next: usize,
}

impl<'a, T: 'a> Iterator for ForestHierarchicalIter<'a, T>{
    type Item = idtree::NodeRef<'a,T>;
    fn next(&mut self) -> Option<idtree::NodeRef<'a,T>>{
        if self.next == self.ordered_ids.len() {
            None
        }else{
            let next = unsafe{ *self.ordered_ids.get_unchecked(self.next) };
            let node = unsafe{ self.forest.fast_get_node(next.fast) };
            self.next += 1;
            let node = unsafe{ mem::transmute::<idtree::NodeRef<T>, idtree::NodeRef<T>>(node) };
            Some(node)
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>){
        (self.forest.arena.len(), Some(self.forest.arena.len()))
    }
}

impl<'a, T> IntoOrderedIterMut for WriteGuardRef<'a, Forest<T>>{
    type OrderedIterMut = ForestHierarchicalIterMut<'a,T>;
    fn into_ordered_iter_mut(self) -> Self::OrderedIterMut{
        self.ordered_ids();
        ForestHierarchicalIterMut{
            next: 0,
            forest: self,
        }
    }
}

pub struct ForestHierarchicalIterMut<'a, T: 'a>{
    forest: WriteGuardRef<'a, Forest<T>>,
    next: usize,
}

impl<'a, T: 'a> Iterator for ForestHierarchicalIterMut<'a, T>{
    type Item = idtree::NodeRefMut<'a,T>;
    fn next(&mut self) -> Option<idtree::NodeRefMut<'a,T>>{
        if self.next == self.forest.ordered_ids.get_mut().len() {
            None
        }else{
            let next = unsafe{ *self.forest.ordered_ids.get_mut().get_unchecked(self.next) };
            let node = unsafe{ self.forest.fast_get_node_mut(next.fast) };
            self.next += 1;
            let node = unsafe{ mem::transmute::<idtree::NodeRefMut<T>, idtree::NodeRefMut<T>>(node) };
            Some(node)
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>){
        (self.forest.arena.len(), Some(self.forest.arena.len()))
    }
}

impl<'a, T: 'a> ExactSizeIterator for ForestHierarchicalIterMut<'a, T>{
    #[inline]
    fn len(&self) -> usize {
        self.forest.arena.len()
    }
}

pub struct ForestHierarchicalIdedIterMut<'a, T: 'a>{
    forest: WriteGuardRef<'a, Forest<T>>,
    next: usize,
}

impl<'a, T: 'a> Iterator for ForestHierarchicalIdedIterMut<'a, T>{
    type Item = (usize, idtree::NodeRefMut<'a,T>);
    fn next(&mut self) -> Option<(usize, idtree::NodeRefMut<'a,T>)>{
        if self.next == self.forest.ordered_ids.get_mut().len() {
            None
        }else{
            let next = unsafe{ *self.forest.ordered_ids.get_mut().get_unchecked(self.next) };
            let node = unsafe{ self.forest.fast_get_node_mut(next.fast) };
            self.next += 1;
            let node = unsafe{ mem::transmute::<idtree::NodeRefMut<T>, idtree::NodeRefMut<T>>(node) };
            Some((next.guid, node))
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>){
        (self.forest.arena.len(), Some(self.forest.arena.len()))
    }
}

impl<'a, T: 'a> ExactSizeIterator for ForestHierarchicalIdedIterMut<'a, T>{
    #[inline]
    fn len(&self) -> usize {
        self.forest.arena.len()
    }
}

impl<'a, T> IntoOrderedIdedIterMut for WriteGuardRef<'a, Forest<T>>{
    type OrderedIdedIterMut = ForestHierarchicalIdedIterMut<'a, T>;
    fn into_ordered_ided_iter_mut(self) -> Self::OrderedIdedIterMut{
        self.ordered_ids();
        ForestHierarchicalIdedIterMut{
            forest: self,
            next: 0,
        }
    }
}