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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
//! A concurrent, incremental HashMap implementation
use super::{store, Action, RawAction};
use crate::{
    fields::{
        depth::Incremental, Collection, Intent, Key, Load, LocalField, SparseField, Store,
        Strategy, Value,
    },
    index::{writer, FieldWriter},
    object::{self, serializer::SizedPointer, ObjectError},
};
use scc::HashMap;
use std::{borrow::Borrow, cell::Cell, hash::Hash, sync::Arc};

/// HashMap that tracks incremental changes between commits
///
/// Calling [`clone()`](VersionedMap::clone) will create a reference to the
/// same instance, and can be easily shared between threads.
///
/// To write to disk the entire content of a hash map on every commit,
/// see [`Map`](crate::fields::Map)
pub struct VersionedMap<K, V>
where
    K: Key + 'static,
    V: Value + 'static,
{
    current: Arc<HashMap<K, Action<V>>>,
    base: Arc<HashMap<K, Action<V>>>,
}

impl<K, V> Clone for VersionedMap<K, V>
where
    K: Key + 'static,
    V: Value + 'static,
{
    fn clone(&self) -> Self {
        VersionedMap {
            base: self.base.clone(),
            current: self.current.clone(),
        }
    }
}

impl<K, V> Default for VersionedMap<K, V>
where
    K: Key + 'static,
    V: Value + 'static,
{
    fn default() -> Self {
        VersionedMap {
            base: Arc::default(),
            current: Arc::default(),
        }
    }
}

impl<K, V> VersionedMap<K, V>
where
    K: Key + Clone,
    V: Value,
{
    /// Set `key` to `value`.
    ///
    /// `insert` never overwrites existing values.
    ///
    /// Returns either the existing value, or the newly inserted value.
    ///
    /// It is equivalent to calling `map.insert_with(key, move || value)`.
    ///
    /// # Examples
    ///
    /// ```
    /// use infinitree::fields::VersionedMap;
    ///
    /// let m = VersionedMap::<usize, String>::default();
    /// assert_eq!(m.insert(1, "first".to_owned()), "first".to_owned().into());
    /// assert_eq!(m.insert(1, "second".to_owned()), "first".to_owned().into());
    /// ```
    #[inline(always)]
    pub fn insert(&self, key: K, value: impl Into<Arc<V>>) -> Arc<V> {
        self.insert_with(key, move || value)
    }

    /// Set `key` to the value returned by `new`.
    ///
    /// `insert` never overwrites existing values.
    ///
    /// Returns either the existing value, or the newly inserted value.
    ///
    /// # Examples
    ///
    /// ```
    /// use infinitree::fields::VersionedMap;
    ///
    /// let m = VersionedMap::<usize, String>::default();
    /// assert_eq!(m.insert_with(1, || "first".to_owned()), "first".to_owned().into());
    /// assert_eq!(m.insert_with(1, || "second".to_owned()), "first".to_owned().into());
    /// ```
    #[inline(always)]
    pub fn insert_with<T: Into<Arc<V>>, F: FnOnce() -> T>(&self, key: K, new: F) -> Arc<V> {
        match self.get(&key) {
            Some(v) => v,
            None => {
                let new = Arc::new(Cell::new(Some(new)));
                let result = Cell::new(None);

                self.current.upsert(
                    key,
                    || {
                        let val = store(new.take().unwrap()());
                        result.set(val.clone());
                        val
                    },
                    |_, v| {
                        v.get_or_insert_with(|| new.take().unwrap()().into());
                        result.set(v.clone());
                    },
                );

                // this will never panic, because callbacks guarantee it ends up being Some()
                result.into_inner().unwrap()
            }
        }
    }

    /// Update the value in `key` to the one returned by the `update` closure.
    ///
    /// `update_with` will never insert a new value to the map.
    ///
    /// Returns the update value, or None if `key` does not exist in the map.
    ///
    /// # Examples
    ///
    /// ```
    /// use infinitree::fields::VersionedMap;
    ///
    /// let m = VersionedMap::<usize, String>::default();
    ///
    /// assert_eq!(m.update_with(1, |_| "first".to_owned()), None);
    ///
    /// m.insert(1, "first".to_owned());
    ///
    /// assert_eq!(m.update_with(1, |_| "second".to_owned()), Some("second".to_owned().into()));
    /// ```
    #[inline(always)]
    pub fn update_with(&self, key: K, update: impl FnOnce(Arc<V>) -> V) -> Action<V> {
        match self.get(&key) {
            Some(existing) => {
                let result = Cell::new(None);
                let update = Arc::new(Cell::new(Some(update)));

                self.current.upsert(
                    key,
                    || {
                        let val = store(update.take().unwrap()(existing.clone()));
                        result.set(val.clone());
                        val
                    },
                    |_, v| {
                        *v = store(update.take().unwrap()(v.as_ref().unwrap().clone()));
                        result.set(v.clone())
                    },
                );

                // this will never panic, because callbacks guarantee it ends up being Some()
                result.into_inner()
            }
            None => None,
        }
    }

    /// Returns the stored value for a key, or `None`
    ///
    /// # Examples
    ///
    /// ```
    /// use infinitree::fields::VersionedMap;
    ///
    /// let m = VersionedMap::<usize, String>::default();
    ///
    /// assert_eq!(m.get(&1), None);
    ///
    /// m.insert(1, "first".to_owned());
    /// assert_eq!(m.get(&1), Some("first".to_owned().into()));
    /// ```
    #[inline(always)]
    pub fn get<Q>(&self, key: &Q) -> Option<Arc<V>>
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized,
    {
        self.current
            .read(key, |_, v| v.clone())
            .or_else(|| self.base.read(key, |_, v| v.clone()))
            .flatten()
    }

    /// Sets the key as removed in the map
    ///
    /// # Examples
    ///
    /// ```
    /// use infinitree::fields::VersionedMap;
    ///
    /// let m = VersionedMap::<usize, String>::default();
    ///
    /// m.insert(1, "first".to_owned());
    /// assert_eq!(m.get(&1), Some("first".to_owned().into()));
    ///
    /// m.remove(1);
    /// assert_eq!(m.get(&1), None);
    /// ```
    #[inline(always)]
    pub fn remove(&self, key: K) {
        if self.contains(&key) {
            self.current
                .upsert(key, || Action::None, |_, v| *v = Action::None)
        }
    }

    /// Returns `true` if there's an addition for the specified key
    ///
    /// # Examples
    ///
    /// ```
    /// use infinitree::fields::VersionedMap;
    ///
    /// let m = VersionedMap::<usize, String>::default();
    ///
    /// assert_eq!(m.contains(&1), false);
    /// m.insert(1, "first".to_owned());
    ///
    /// assert_eq!(m.contains(&1), true);
    /// ```
    #[inline(always)]
    pub fn contains(&self, key: &K) -> bool {
        let contained = self
            .current
            .read(key, |_, v| v.is_some())
            .or_else(|| self.base.read(key, |_, v| v.is_some()));

        contained.unwrap_or(false)
    }

    /// Call the function for all additive keys
    ///
    /// # Examples
    ///
    /// ```
    /// use infinitree::fields::VersionedMap;
    ///
    /// let m = VersionedMap::<usize, String>::default();
    ///
    /// m.insert(1, "first".to_owned());
    ///
    /// m.for_each(|k, v| {
    ///     assert_eq!(v, &"first".to_owned());
    /// });
    /// ```
    #[inline(always)]
    pub fn for_each(&self, mut callback: impl FnMut(&K, &V)) {
        // note: this is copy-pasta, because the closures have
        // different lifetimes.
        //
        // if you have a good idea how to avoid
        // using a macro and just do this, please send a PR

        self.base.for_each(|k, v: &mut Action<V>| {
            if let Some(value) = v {
                (callback)(k, Arc::as_ref(value));
            }
        });
        self.current.for_each(|k, v: &mut Action<V>| {
            if let Some(value) = v {
                (callback)(k, Arc::as_ref(value));
            }
        });
    }

    /// Mark values as deleted where `callback` returns `false`
    ///
    /// # Examples
    ///
    /// ```
    /// use infinitree::fields::VersionedMap;
    ///
    /// let m = VersionedMap::<usize, String>::default();
    ///
    /// m.insert(1, "first".to_owned());
    ///
    /// m.retain(|k, v| false);
    /// assert_eq!(m.contains(&1), false);
    /// ```
    #[inline(always)]
    pub fn retain(&self, mut callback: impl FnMut(&K, &V) -> bool) {
        // note: this is copy-pasta, because the closures have
        // different lifetimes.
        //
        // if you have a good idea how to avoid
        // using a macro and just do this, please send a PR

        self.base.for_each(|k, v: &mut Action<V>| {
            if let Some(value) = v {
                if !(callback)(k, Arc::as_ref(value)) {
                    self.current
                        .upsert(k.clone(), || Action::None, |_, v| *v = Action::None)
                }
            }
        });
        self.current.for_each(|k, v: &mut Action<V>| {
            if let Some(value) = v {
                if !(callback)(k, Arc::as_ref(value)) {
                    *v = Action::None
                }
            }
        });
    }

    /// Clear out the current changeset, and commit all changes to history.
    ///
    /// This operation potentially helps free some memory, but more
    /// importantly any subsequent `Store` calls are going to be empty
    /// until further additions or removals.
    pub fn commit(&self) {
        self.current.retain(|k, v| {
            // if the base doesn't have the key, and we're not
            // removing it
            if self.base.remove_if(k, |_v_base| v.is_none()).is_none() {
                // then make sure we store the new value
                //
                // cloning the value is safe and cheap, because
                // it's always an Option<Arc<V>>
                self.base
                    .upsert(k.clone(), || v.clone(), |_, v| *v = v.clone());
            }

            false
        });
    }

    /// Returns the number of additive keys
    ///
    /// See [`VersionedMap::clear`] for example use.
    #[inline(always)]
    pub fn len(&self) -> usize {
        let mut stored = self.base.len();

        self.current.for_each(|_, v| {
            match v {
                Some(_) => stored += 1,

                // None implies it's Some() in `self.base` due to `remove()` semantics
                None => stored -= 1,
            }
        });

        stored
    }

    /// Returns the number of all keys, including deletions
    ///
    /// See [`VersionedMap::clear`] for example use.
    #[inline(always)]
    pub fn size(&self) -> usize {
        self.base.len() + self.current.len()
    }

    /// Return the size of all allocated items
    ///
    /// See [`VersionedMap::clear`] for example use.
    #[inline(always)]
    pub fn capacity(&self) -> usize {
        self.base.capacity() + self.current.capacity()
    }

    /// Free all items in the VersionedMap, _without_ tracking changes
    ///
    /// Returns the number of elements freed.
    ///
    /// # Examples
    ///
    /// ```
    /// use infinitree::fields::VersionedMap;
    ///
    /// let value = "first".to_owned();
    /// let m = VersionedMap::<usize, String>::default();
    ///
    /// assert_eq!(m.is_empty(), true);
    ///
    /// let _ = m.insert(1, value.clone());
    ///
    /// assert_eq!(m.len(), 1);
    /// assert_eq!(m.size(), 1);
    /// assert_eq!(m.is_empty(), false);
    ///
    /// m.commit();
    ///
    /// assert_eq!(m.contains(&1), true);
    ///
    /// assert_eq!(m.len(), 1);
    /// assert_eq!(m.size(), 1);
    /// assert_eq!(m.is_empty(), false);
    ///
    /// m.remove(1);
    ///
    /// assert_eq!(m.contains(&1), false);
    ///
    /// assert_eq!(m.len(), 0);
    /// assert_eq!(m.size(), 2);
    /// assert_eq!(m.is_empty(), true);
    ///
    /// // Call `clear()`
    /// assert_eq!(m.clear(), 2);
    ///
    /// assert_eq!(m.len(), 0);
    /// assert_eq!(m.size(), 0);
    /// assert_eq!(m.is_empty(), true);
    /// ```
    #[inline(always)]
    pub fn clear(&self) -> usize {
        self.base.clear() + self.current.clear()
    }

    /// Roll back all modification since the last commit
    ///
    /// Calling `rollback` also frees up memory dynamically.
    ///
    /// # Examples
    /// ```
    /// use infinitree::fields::VersionedMap;
    ///
    /// let value = "first".to_owned();
    /// let m = VersionedMap::<usize, String>::default();
    ///
    /// assert_eq!(m.is_empty(), true);
    ///
    /// let _ = m.insert(1, value.clone());
    ///
    /// assert_eq!(m.len(), 1);
    /// assert_eq!(m.size(), 1);
    /// assert_eq!(m.is_empty(), false);
    ///
    /// m.commit();
    ///
    /// assert_eq!(m.contains(&1), true);
    ///
    /// assert_eq!(m.len(), 1);
    /// assert_eq!(m.size(), 1);
    /// assert_eq!(m.is_empty(), false);
    ///
    /// m.remove(1);
    ///
    /// assert_eq!(m.contains(&1), false);
    ///
    /// assert_eq!(m.len(), 0);
    /// assert_eq!(m.size(), 2);
    /// assert_eq!(m.is_empty(), true);
    ///
    /// // Call `rollback()`
    /// assert_eq!(m.rollback(), 1);
    ///
    /// assert_eq!(m.len(), 1);
    /// assert_eq!(m.size(), 1);
    /// assert_eq!(m.is_empty(), false);
    #[inline(always)]
    pub fn rollback(&self) -> usize {
        self.current.clear()
    }

    /// True if the number of additions to the map is zero
    ///
    /// Since `VersionedMap` is tracking _changes_, `is_empty()` may
    /// return `true` even if a non-zero amount of memory is being
    /// used.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl<K, V> Collection for LocalField<VersionedMap<K, V>>
where
    K: Key,
    V: Value,
{
    type Depth = Incremental;
    type Key = K;
    type Serialized = (K, Action<V>);
    type Item = (K, Action<V>);

    #[inline(always)]
    fn key(from: &Self::Serialized) -> &Self::Key {
        &from.0
    }

    #[inline(always)]
    fn load(from: Self::Serialized, _object: &mut dyn crate::object::Reader) -> Self::Item {
        from
    }

    #[inline(always)]
    fn insert(&mut self, record: Self::Item) {
        assert!(self.field.base.insert(record.0, record.1).is_ok());
    }
}

impl<K, V> Store for LocalField<VersionedMap<K, V>>
where
    K: Key + Clone,
    V: Value,
{
    #[inline(always)]
    fn store(
        &mut self,
        transaction: &mut writer::Transaction<'_>,
        _object: &mut dyn object::Writer,
    ) {
        self.field.current.for_each(|k, v| {
            transaction.write_next((k, v));
        });

        self.field.commit();
    }
}

impl<K, V> Collection for SparseField<VersionedMap<K, V>>
where
    K: Key,
    V: Value,
{
    type Depth = Incremental;
    type Key = K;
    type Serialized = (K, RawAction<SizedPointer>);
    type Item = (K, Action<V>);

    #[inline(always)]
    fn key(from: &Self::Serialized) -> &Self::Key {
        &from.0
    }

    #[inline(always)]
    fn load(from: Self::Serialized, object: &mut dyn object::Reader) -> Self::Item {
        let value = match from.1 {
            Some(ptr) => {
                let value: V = object::serializer::read(
                    object,
                    |x| {
                        crate::deserialize_from_slice(x).map_err(|e| ObjectError::Deserialize {
                            source: Box::new(e),
                        })
                    },
                    ptr,
                )
                .unwrap();

                store(value)
            }
            None => None,
        };

        (from.0, value)
    }

    #[inline(always)]
    fn insert(&mut self, record: Self::Item) {
        // we're optimizing for the case where the versions are
        // restored from top to bottom, in reverse order.
        // therefore:
        // 1. do not insert a key if it already exists
        // 2. do not restore a removed key
        if let value @ Some(..) = record.1 {
            let _ = self.field.base.insert(record.0, value);
        }
    }
}

impl<K, V> Store for SparseField<VersionedMap<K, V>>
where
    K: Key + Clone,
    V: Value,
{
    #[inline(always)]
    fn store(
        &mut self,
        transaction: &mut writer::Transaction<'_>,
        writer: &mut dyn object::Writer,
    ) {
        self.field.current.for_each(|key, value| {
            let ptr = value.as_ref().map(|stored| {
                object::serializer::write(
                    writer,
                    |x| {
                        crate::serialize_to_vec(&x).map_err(|e| ObjectError::Serialize {
                            source: Box::new(e),
                        })
                    },
                    stored,
                )
                .unwrap()
            });
            transaction.write_next((key, ptr));
        });

        self.field.commit();
    }
}

impl<K, V> crate::Index for VersionedMap<K, V>
where
    K: Key + Clone,
    V: Value,
{
    fn store_all(&mut self) -> anyhow::Result<Vec<Intent<Box<dyn Store>>>> {
        Ok(vec![Intent::new(
            "root",
            Box::new(LocalField::for_field(self)),
        )])
    }

    fn load_all(&mut self) -> anyhow::Result<Vec<Intent<Box<dyn Load>>>> {
        Ok(vec![Intent::new(
            "root",
            Box::new(LocalField::for_field(self)),
        )])
    }
}

#[cfg(test)]
mod test {
    use super::VersionedMap;
    use crate::{
        fields::{LocalField, SparseField, Strategy},
        index::test::store_then_load,
        Infinitree, Key,
    };

    #[test]
    fn bare_index_can_be_restored() {
        let key = || Key::from_credentials("bare_index_map", "password").unwrap();
        let storage = crate::backends::test::InMemoryBackend::shared();

        {
            let mut tree = Infinitree::<VersionedMap<usize, usize>>::empty(storage.clone(), key());
            tree.index().insert(1000, 1000);
            tree.commit(None);
            tree.index().clear();

            for i in 0..100 {
                tree.index().insert(i, i + 1);
            }

            tree.commit(None);
        }

        let mut tree =
            Infinitree::<VersionedMap<usize, usize>>::open(storage.clone(), key()).unwrap();
        tree.load_all();

        for i in 0..100 {
            assert_eq!(i + 1, *tree.index().get(&i).unwrap());
        }

        assert_eq!(tree.index().len(), 101);
    }

    #[test]
    fn duplicate_insert_is_noop() {
        let m = VersionedMap::<usize, String>::default();
        assert_eq!(m.insert(1, "first".to_owned()), "first".to_owned().into());
        assert_eq!(m.insert(1, "second".to_owned()), "first".to_owned().into());
    }

    #[test]
    fn updating_empty_is_noop() {
        let m = VersionedMap::<usize, String>::default();
        assert_eq!(m.update_with(1, |_| "first".to_owned()), None);
    }

    #[test]
    fn store_then_confirm_then_remove() {
        let m = VersionedMap::<usize, String>::default();
        let first = "first".to_owned();
        let updated = "updated".to_owned();
        let second = "second".to_owned();

        // insert
        assert_eq!(m.insert_with(1, || first.clone()), first.clone().into());
        assert_eq!(m.insert_with(2, || second.clone()), second.clone().into());

        // get first
        assert_eq!(m.get(&1), Some(first.into()));

        // contains
        assert_eq!(m.contains(&1), true);
        assert_eq!(m.contains(&2), true);

        // update
        assert_eq!(
            m.update_with(1, |_| updated.clone()),
            Some(updated.clone().into())
        );
        assert_eq!(m.get(&1), Some(updated.into()));

        // removed
        m.remove(1);
        assert_eq!(m.get(&1), None);

        // second still fine
        assert_eq!(m.get(&2), Some(second.into()));
    }

    #[test]
    fn commit_then_confirm_then_lengths() {
        let value = "first".to_owned();
        let m = VersionedMap::<usize, String>::default();

        assert_eq!(m.is_empty(), true);

        let _ = m.insert(1, value.clone());

        assert_eq!(m.len(), 1);
        assert_eq!(m.size(), 1);
        assert_eq!(m.is_empty(), false);

        m.commit();

        assert_eq!(m.get(&1), Some(value.into()));
        assert_eq!(m.contains(&1), true);

        m.remove(1);

        assert_eq!(m.get(&1), None);
        assert_eq!(m.contains(&1), false);

        assert_eq!(m.len(), 0);
        assert_eq!(m.size(), 2);
        assert_eq!(m.is_empty(), true);

        m.clear();

        assert_eq!(m.len(), 0);
        assert_eq!(m.size(), 0);
        assert_eq!(m.is_empty(), true);
    }

    type TestMap = VersionedMap<usize, String>;
    fn init_map(store: &TestMap) {
        store.insert(1, "one".to_owned());
        store.insert(2, "two".to_owned());
    }
    crate::len_check_test!(TestMap, LocalField, init_map, |m: TestMap| m.len());
    crate::len_check_test!(TestMap, SparseField, init_map, |m: TestMap| m.len());
}