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
//! A concurrent, incremental linked list implementation
use crate::{
    fields::{
        depth::Incremental, Collection, Intent, Load, LocalField, SparseField, Store, Strategy,
        Value,
    },
    index::{FieldWriter, Transaction},
    object::{self, serializer::SizedPointer, ObjectError},
};
use scc::{
    ebr::{Arc as SCCArc, AtomicArc, Barrier, Ptr, Tag},
    LinkedList as SCCLinkedList,
};
use std::{
    ops::Deref,
    sync::{atomic::Ordering, Arc},
};

#[derive(Default)]
pub struct Node<T: 'static>(AtomicArc<Node<T>>, T);
impl<T: 'static> SCCLinkedList for Node<T> {
    fn link_ref(&self) -> &AtomicArc<Node<T>> {
        &self.0
    }
}

#[allow(unused)]
impl<T: 'static> Node<T> {
    fn set_next(&self, next: SCCArc<Node<T>>, barrier: &Barrier) {
        let _ = self.push_back(next, false, Ordering::Release, barrier);
    }

    fn insert(&self, value: impl Into<T>) {
        let barrier = Barrier::new();
        self.set_next(SCCArc::new(Node(AtomicArc::null(), value.into())), &barrier);
    }

    pub fn is_last(&self) -> bool {
        self.0.is_null(Ordering::Acquire)
    }

    fn next(&self) -> Option<SCCArc<Node<T>>> {
        let barrier = Barrier::new();
        self.0.load(Ordering::Acquire, &barrier).get_arc()
    }
}

#[derive(Default)]
struct NodeIter<T: 'static> {
    first: bool,
    current: Option<SCCArc<Node<Arc<T>>>>,
}

impl<T: 'static> Iterator for NodeIter<T> {
    type Item = Arc<T>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.first {
            self.first = false;
            return self.current.as_ref().map(|n| n.1.clone());
        }

        let next = self.current.as_ref().and_then(|n| n.next());
        match next {
            Some(ref node) => {
                self.current = next.clone();
                Some(node.1.clone())
            }
            None => None,
        }
    }
}

impl<T: 'static> Deref for Node<Arc<T>> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.1.deref()
    }
}

struct LinkedListInner<T: 'static> {
    last: AtomicArc<Node<Arc<T>>>,
    commit_start: AtomicArc<Node<Arc<T>>>,
    previous_commit_last: AtomicArc<Node<Arc<T>>>,
    first: AtomicArc<Node<Arc<T>>>,
}

impl<T: 'static> Default for LinkedListInner<T> {
    fn default() -> Self {
        Self {
            last: AtomicArc::null(),
            commit_start: AtomicArc::null(),
            previous_commit_last: AtomicArc::null(),
            first: AtomicArc::null(),
        }
    }
}

/// Append-only linked list that only commits incremental changes
#[derive(Clone)]
pub struct LinkedList<T: 'static> {
    inner: SCCArc<LinkedListInner<T>>,
}

impl<T: 'static> Default for LinkedList<T> {
    fn default() -> Self {
        Self {
            inner: SCCArc::new(LinkedListInner::default()),
        }
    }
}

impl<T: 'static> LinkedList<T> {
    /// Add a new item to the list
    ///
    /// # Examples
    ///
    /// ```
    /// use infinitree::fields::LinkedList;
    ///
    /// let list = LinkedList::default();
    /// list.push(123456);
    ///
    /// assert_eq!(list.last(), Some(123456.into()))
    ///
    /// ```
    pub fn push(&self, value: impl Into<Arc<T>>) {
        let node = SCCArc::new(Node(AtomicArc::default(), value.into()));
        let barrier = Barrier::new();

        let _ = self
            .inner
            .commit_start
            .compare_exchange(
                Ptr::null(),
                (Some(node.clone()), Tag::None),
                Ordering::SeqCst,
                Ordering::Relaxed,
                &barrier,
            )
            .and_then(|_| {
                self.inner.first.compare_exchange(
                    Ptr::null(),
                    (Some(node.clone()), Tag::None),
                    Ordering::SeqCst,
                    Ordering::Relaxed,
                    &barrier,
                )
            });

        let barrier = Barrier::new();
        let ptr = self.inner.last.load(Ordering::Acquire, &barrier);
        self.inner
            .last
            .swap((Some(node.clone()), Tag::None), Ordering::Release);

        if let Some(ptr) = ptr.as_ref() {
            ptr.set_next(node, &barrier);
        }
    }

    /// Gets the first item of the current commit
    ///
    /// # Examples
    ///
    /// ```
    /// use infinitree::fields::LinkedList;
    ///
    /// let list = LinkedList::default();
    ///
    /// list.push(123456);
    /// assert_eq!(list.first_in_commit(), Some(123456.into()));

    ///
    /// list.push(111111);
    /// assert_eq!(list.first_in_commit(), Some(123456.into()));
    ///
    /// list.commit();
    /// assert_eq!(list.first_in_commit(), None);
    ///
    /// list.push(654321);
    /// assert_eq!(list.first_in_commit(), Some(654321.into()));
    ///
    /// ```
    pub fn first_in_commit(&self) -> Option<Arc<T>> {
        let barrier = Barrier::new();
        self.inner
            .commit_start
            .load(Ordering::Acquire, &barrier)
            .as_ref()
            .map(|node| node.1.clone())
    }

    /// Gets the first item of the linked list
    ///
    /// # Examples
    ///
    /// ```
    /// use infinitree::fields::LinkedList;
    ///
    /// let list = LinkedList::default();
    /// list.push(123456);
    ///
    /// assert_eq!(list.first(), Some(123456.into()));
    ///
    /// list.push(111111);
    ///
    /// assert_eq!(list.first(), Some(123456.into()));
    /// ```
    pub fn first(&self) -> Option<Arc<T>> {
        let barrier = Barrier::new();
        self.inner
            .first
            .load(Ordering::Acquire, &barrier)
            .as_ref()
            .map(|node| node.1.clone())
    }

    /// Gets the last item of the linked list
    ///
    /// # Examples
    ///
    /// ```
    /// use infinitree::fields::LinkedList;
    ///
    /// let list = LinkedList::default();
    ///
    /// list.push(123456);
    /// assert_eq!(list.last(), Some(123456.into()));
    ///
    /// list.push(111111);
    /// assert_eq!(list.last(), Some(111111.into()));
    /// ```
    pub fn last(&self) -> Option<Arc<T>> {
        let barrier = Barrier::new();
        self.inner
            .last
            .load(Ordering::Acquire, &barrier)
            .as_ref()
            .map(|node| node.1.clone())
    }

    /// Move the commit pointer to the last item in the list
    ///
    /// # Examples
    ///
    /// ```
    /// use infinitree::fields::LinkedList;
    ///
    /// let list = LinkedList::default();
    ///
    /// list.push(123456);
    /// assert_eq!(list.first_in_commit(), Some(123456.into()));
    ///
    /// list.push(111111);
    /// assert_eq!(list.first_in_commit(), Some(123456.into()));
    ///
    /// list.commit();
    /// assert_eq!(list.first_in_commit(), None);
    ///
    /// list.push(654321);
    /// assert_eq!(list.first_in_commit(), Some(654321.into()));
    /// ```
    pub fn commit(&self) {
        let barrier = Barrier::new();
        let last = self.inner.last.load(Ordering::SeqCst, &barrier).get_arc();
        self.inner
            .commit_start
            .swap((None, Tag::None), Ordering::SeqCst);
        self.inner
            .previous_commit_last
            .swap((last, Tag::None), Ordering::SeqCst);
    }

    /// Move the commit pointer to the last item in the list
    ///
    /// # Examples
    ///
    /// ```
    /// use infinitree::fields::LinkedList;
    ///
    /// let list = LinkedList::default();
    ///
    /// list.push(123456);
    /// list.push(111111);
    /// list.commit();
    /// list.push(654321);
    /// assert_eq!(list.first_in_commit(), Some(654321.into()));
    /// assert_eq!(list.last(), Some(654321.into()));
    /// assert_eq!(list.first(), Some(123456.into()));
    ///
    /// list.clear();
    /// assert_eq!(list.first_in_commit(), None);
    /// assert_eq!(list.first(),None);
    /// assert_eq!(list.last(), None);
    /// ```
    pub fn clear(&self) {
        self.inner.first.swap((None, Tag::None), Ordering::SeqCst);
        self.inner
            .commit_start
            .swap((None, Tag::None), Ordering::SeqCst);
        self.inner
            .previous_commit_last
            .swap((None, Tag::None), Ordering::SeqCst);
        self.inner.last.swap((None, Tag::None), Ordering::SeqCst);
    }

    /// Move the commit pointer to the last item in the list
    ///
    /// # Examples
    ///
    /// ```
    /// use infinitree::fields::LinkedList;
    ///
    /// let list = LinkedList::default();
    ///
    /// list.push(123456);
    /// list.push(111111);
    /// list.commit();
    /// list.push(654321);
    /// assert_eq!(list.first_in_commit(), Some(654321.into()));
    /// assert_eq!(list.last(), Some(654321.into()));
    /// assert_eq!(list.first(), Some(123456.into()));
    ///
    /// list.rollback();
    /// assert_eq!(list.first_in_commit(), None);
    /// assert_eq!(list.first(), Some(123456.into()));
    /// assert_eq!(list.last(), Some(111111.into()));
    /// ```
    pub fn rollback(&self) {
        let barrier = Barrier::new();
        let last = self
            .inner
            .previous_commit_last
            .load(Ordering::SeqCst, &barrier)
            .get_arc();
        self.inner.last.swap((last, Tag::None), Ordering::SeqCst);
        self.inner
            .commit_start
            .swap((None, Tag::None), Ordering::SeqCst);
    }

    pub fn iter(&self) -> impl Iterator<Item = Arc<T>> {
        let barrier = Barrier::new();
        NodeIter {
            first: true,
            current: self.inner.first.load(Ordering::Acquire, &barrier).get_arc(),
        }
    }
}

impl<T> Store for LocalField<LinkedList<T>>
where
    T: Value,
{
    fn store(&mut self, mut transaction: &mut dyn Transaction, _object: &mut dyn object::Writer) {
        for v in self.field.iter() {
            transaction.write_next(v);
        }

        self.field.commit();
    }
}

impl<T> Collection for LocalField<LinkedList<T>>
where
    T: Value + Clone,
{
    type Depth = Incremental;
    type Key = T;
    type Serialized = T;
    type Item = T;

    fn key(from: &Self::Serialized) -> &Self::Key {
        from
    }

    fn load(from: Self::Serialized, _object: &mut dyn object::Reader) -> Self::Item {
        from
    }

    fn insert(&mut self, record: Self::Item) {
        self.field.push(record);
    }
}

impl<T> Store for SparseField<LinkedList<T>>
where
    T: Value,
{
    fn store(&mut self, mut transaction: &mut dyn Transaction, writer: &mut dyn object::Writer) {
        for v in self.field.iter() {
            let ptr = object::serializer::write(
                writer,
                |x| {
                    crate::serialize_to_vec(&x).map_err(|e| ObjectError::Serialize {
                        source: Box::new(e),
                    })
                },
                v,
            )
            .unwrap();

            transaction.write_next(ptr);
        }

        self.field.commit();
    }
}

impl<T> Collection for SparseField<LinkedList<T>>
where
    T: Value + Clone,
{
    type Depth = Incremental;
    type Key = SizedPointer;
    type Serialized = SizedPointer;
    type Item = T;

    fn key(from: &Self::Serialized) -> &Self::Key {
        from
    }

    fn load(from: Self::Serialized, object: &mut dyn object::Reader) -> Self::Item {
        object::serializer::read(
            object,
            |x| {
                crate::deserialize_from_slice(x).map_err(|e| ObjectError::Deserialize {
                    source: Box::new(e),
                })
            },
            from,
        )
        .unwrap()
    }

    fn insert(&mut self, record: Self::Item) {
        self.field.push(record);
    }
}

impl<T> crate::Index for LinkedList<T>
where
    T: 'static + Value + Clone,
{
    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::LinkedList;
    use crate::{
        fields::{LocalField, SparseField, Strategy},
        index::test::store_then_load,
    };

    type TestList = LinkedList<usize>;
    fn init_list(store: &TestList) {
        store.push(123456790);
        store.push(987654321);
    }

    crate::len_check_test!(TestList, LocalField, init_list, |l: TestList| {
        let mut x = 0;
        for _ in l.iter() {
            x += 1;
        }
        x
    });
    crate::len_check_test!(TestList, SparseField, init_list, |l: TestList| {
        let mut x = 0;
        for _ in l.iter() {
            x += 1;
        }
        x
    });
}