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
use std::collections::{BTreeMap, HashMap};
use std::fmt::Debug;
use std::marker::PhantomData;
use std::ops::Bound::{Excluded, Unbounded};

use serde::de::Visitor;
use serde::ser::SerializeSeq;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::data_structures::ZenoIndex;
use crate::{StateMachine, Transition};

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub enum ListPosition {
    Beginning,
    End,
    AbsolutePosition(ZenoIndex),
    Before(Uuid, ZenoIndex),
    After(Uuid, ZenoIndex),
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(bound = "")]
pub enum ListOperation<T: StateMachine + PartialEq> {
    // TODO: implement this new operation
    Insert(ListPosition, Uuid, T),
    // TODO: delete the following operations
    //Insert(ZenoIndex, Uuid, T),
    //Append(Uuid, T),
    //Prepend(Uuid, T),
    Delete(Uuid),
    Move(Uuid, ZenoIndex),
    Apply(Uuid, <T as StateMachine>::Transition),
}

impl<T: StateMachine + PartialEq> Transition for ListOperation<T> {}

/// Represents a view of an entry in a list during iteration. Each
/// item contains a borrow of its `value`; its `location` as a [ZenoIndex],
/// and a unique identifier which is opaque but must be passed for
/// [List::delete] and [List::move_item] calls.
pub struct ListItem<'a, T: StateMachine + PartialEq> {
    pub value: &'a T,
    pub location: ZenoIndex,
    pub id: Uuid,
}

/// Represents a list of items, similar to a `Vec`, but designed to be robust
/// to concurrent modifications from multiple users.
#[derive(Clone, PartialEq, Debug)]
pub struct List<T: StateMachine + PartialEq> {
    items: BTreeMap<ZenoIndex, Uuid>,
    items_inv: BTreeMap<Uuid, ZenoIndex>,
    pool: HashMap<Uuid, T>,
}

impl<T: StateMachine + PartialEq> Serialize for List<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut seq = serializer.serialize_seq(Some(self.items.len()))?;
        for i in self.items.iter().map(|(zi, id)| (zi, id, &self.pool[id])) {
            seq.serialize_element(&i)?;
        }
        seq.end()
    }
}

impl<'de, T: StateMachine + PartialEq> Deserialize<'de> for List<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct ListVisitor<T>(PhantomData<T>);
        impl<'de, T: StateMachine + PartialEq> Visitor<'de> for ListVisitor<T> {
            type Value = List<T>;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a sequence of tuples")
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
            where
                A: serde::de::SeqAccess<'de>,
            {
                let mut list = List::new();

                while let Some((zi, id, v)) = seq.next_element::<(ZenoIndex, Uuid, T)>()? {
                    list.items.insert(zi.clone(), id);
                    list.items_inv.insert(id, zi);
                    list.pool.insert(id, v);
                }
                Ok(list)
            }
        }

        deserializer.deserialize_seq(ListVisitor(PhantomData))
    }
}

impl<T: StateMachine + PartialEq> Default for List<T> {
    fn default() -> Self {
        List {
            items: Default::default(),
            items_inv: Default::default(),
            pool: Default::default(),
        }
    }
}

impl<T: StateMachine + PartialEq> StateMachine for List<T> {
    type Transition = ListOperation<T>;

    fn apply(&mut self, transition_event: Self::Transition) {
        match transition_event {
            ListOperation::Insert(location, id, value) => self.do_insert(location, id, value),
            ListOperation::Delete(id) => self.do_delete(id),
            ListOperation::Move(id, location) => self.do_move(id, location),
            ListOperation::Apply(id, transition) => {
                if let Some(v) = self.pool.get_mut(&id) {
                    v.apply(transition)
                } else {
                    // TODO: resolve conflict.
                }
            }
        }
    }
}

pub type OperationWithId<T> = (Uuid, ListOperation<T>);

impl<T: StateMachine + PartialEq> List<T> {
    pub fn new() -> List<T> {
        Self::default()
    }

    pub fn get_location(&self, position: ListPosition) -> ZenoIndex {
        let location = match position {
            ListPosition::Beginning => {
                // return a zenoindex < the index of the first list element
                return if let Some((i, _)) = self.items.iter().next() {
                    ZenoIndex::new_before(i)
                } else {
                    ZenoIndex::default()
                };
            }
            ListPosition::End => {
                return if let Some((i, _)) = self.items.iter().next_back() {
                    ZenoIndex::new_after(i)
                } else {
                    ZenoIndex::default()
                }
            }
            ListPosition::AbsolutePosition(p) => p,
            ListPosition::Before(uuid, fallback_location) => {
                if let Some(location) = self.items_inv.get(&uuid) {
                    ZenoIndex::new_before(&location)
                } else {
                    ZenoIndex::new_before(&fallback_location)
                }
            }
            ListPosition::After(uuid, fallback_location) => {
                if let Some(location) = self.items_inv.get(&uuid) {
                    ZenoIndex::new_after(&location)
                } else {
                    ZenoIndex::new_after(&fallback_location)
                }
            }
        };

        if self.items.contains_key(&location) {
            if let Some((next_location, _)) =
                self.items.range((Excluded(&location), Unbounded)).next()
            {
                ZenoIndex::new_between(&location, next_location)
            } else {
                ZenoIndex::new_after(&location)
            }
        } else {
            location
        }
    }

    fn do_insert(&mut self, position: ListPosition, id: Uuid, value: T) {
        let location = self.get_location(position);
        self.items.insert(location.clone(), id);
        self.items_inv.insert(id, location);
        self.pool.insert(id, value);
    }

    fn do_move(&mut self, id: Uuid, location: ZenoIndex) {
        if let Some(old_location) = self.items_inv.remove(&id) {
            self.items.remove(&old_location);
            self.items.insert(location.clone(), id);
            self.items_inv.insert(id, location);
        } else {
            // TODO: if the item is not in the pool, we have a conflict.
            // For now, we ignore it.
        }
    }

    fn do_delete(&mut self, id: Uuid) {
        if let Some(location) = self.items_inv.remove(&id) {
            self.items.remove(&location);
        }
        self.pool.remove(&id);
    }

    pub fn insert_between(&self, id1: &Uuid, id2: &Uuid, value: T) -> OperationWithId<T> {
        let id = Uuid::new_v4();
        let loc1 = self.items_inv.get(id1).unwrap();
        let loc2 = self.items_inv.get(id2).unwrap();
        let new_loc = ZenoIndex::new_between(loc1, loc2);
        (
            id,
            ListOperation::Insert(ListPosition::AbsolutePosition(new_loc), id, value),
        )
    }

    /// Construct an [OperationWithId] representing appending the given object to this
    /// list.
    pub fn append(&self, value: T) -> OperationWithId<T> {
        let id = Uuid::new_v4();
        (id, ListOperation::Insert(ListPosition::End, id, value))
    }

    /// Construct a [OperationWithId] representing prepending the given object to this
    /// list.
    pub fn prepend(&self, value: T) -> OperationWithId<T> {
        let id = Uuid::new_v4();
        (
            id,
            ListOperation::Insert(ListPosition::Beginning, id, value),
        )
    }

    /// Construct a [OperationWithId] representing inserting the given object at the
    /// given location in this list.
    pub fn insert(&self, location: ZenoIndex, value: T) -> OperationWithId<T> {
        let id = Uuid::new_v4();
        (
            id,
            ListOperation::Insert(ListPosition::AbsolutePosition(location), id, value),
        )
    }

    /// Construct a [ListOperation] representing deleting the object given (by id)
    /// in this list.
    pub fn delete(&self, id: Uuid) -> ListOperation<T> {
        ListOperation::Delete(id)
    }

    /// Construct a [ListOperation] representing moving an object already in this
    /// list to the given location in the list.
    pub fn move_item(&self, id: Uuid, new_location: ZenoIndex) -> ListOperation<T> {
        ListOperation::Move(id, new_location)
    }

    pub fn map_item(
        &self,
        id: Uuid,
        fun: impl FnOnce(&T) -> <T as StateMachine>::Transition,
    ) -> <Self as StateMachine>::Transition {
        if let Some(it) = self.pool.get(&id) {
            ListOperation::Apply(id, fun(it))
        } else {
            // Handle conflict.
            panic!("Conflict should be better handled.")
        }
    }

    /// Returns an iterator over [ListItem] views into this list.
    pub fn iter(&self) -> impl Iterator<Item = ListItem<T>> {
        self.items.iter().map(move |(location, id)| ListItem {
            location: location.clone(),
            id: *id,
            value: &self.pool[id],
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data_structures::Atom;

    #[test]
    fn test_get_location() {
        let mut my_list: List<Atom<u32>> = List::new();
        let mut ids: Vec<Uuid> = vec![];

        for i in 0..10 {
            let (id, transition) = my_list.append(Atom::new(i));
            ids.push(id);

            my_list.apply(transition);
        }

        // Beginning

        assert!(
            my_list.get_location(ListPosition::Beginning) < *my_list.items.keys().next().unwrap()
        );

        // Ending

        assert!(
            my_list.get_location(ListPosition::End) > *my_list.items.keys().next_back().unwrap()
        );

        // AbsolutePosition

        assert!(
            my_list.get_location(ListPosition::AbsolutePosition(
                my_list.items_inv[&ids[4]].clone()
            )) > my_list.items_inv[&ids[4]]
        );

        // Before

        assert!(
            my_list.get_location(ListPosition::Before(
                ids[7],
                my_list.items_inv[&ids[7]].clone()
            )) < my_list.items_inv[&ids[7]]
        );

        // After

        assert!(
            my_list.get_location(ListPosition::After(
                ids[7],
                my_list.items_inv[&ids[7]].clone()
            )) > my_list.items_inv[&ids[7]]
        );
    }

    #[test]
    fn test_insert_between_merge() {
        let mut my_list: List<Atom<u32>> = List::new();

        let (id1, transition1) = my_list.append(Atom::new(1));
        let (id2, transition2) = my_list.append(Atom::new(2));

        my_list.apply(transition2); // my_list = [2]
        my_list.apply(transition1); // my_list = [2, 1]

        let (_id3, transition3) = my_list.insert_between(&id2, &id1, Atom::new(3));

        let (_id4, transition4) = my_list.insert_between(&id2, &id1, Atom::new(4));

        my_list.apply(transition4);
        assert_eq!(
            vec![2, 4, 1],
            my_list
                .iter()
                .map(|d| *d.value.value())
                .collect::<Vec<u32>>()
        );
        my_list.apply(transition3);
        assert_eq!(
            vec![2, 4, 3, 1],
            my_list
                .iter()
                .map(|d| *d.value.value())
                .collect::<Vec<u32>>()
        );
    }

    #[test]
    fn test_list() {
        let mut list: List<Atom<i64>> = List::default();

        // Test Append.

        list.apply(list.append(Atom::new(5)).1);

        list.apply(list.append(Atom::new(3)).1);

        list.apply(list.append(Atom::new(143)).1);

        // Test Prepend.

        list.apply(list.prepend(Atom::new(99)).1);

        {
            let result: Vec<i64> = list.iter().map(|d| *d.value.value()).collect();
            assert_eq!(vec![99, 5, 3, 143], result);
        }

        // Test Insert.
        {
            let locations: Vec<ZenoIndex> = list.iter().map(|d| d.location).collect();

            list.apply(
                list.insert(
                    ZenoIndex::new_between(&locations[2], &locations[3]),
                    Atom::new(44),
                )
                .1,
            );

            list.apply(
                list.insert(
                    ZenoIndex::new_between(&locations[0], &locations[1]),
                    Atom::new(23),
                )
                .1,
            );

            list.apply(
                list.insert(
                    ZenoIndex::new_between(&locations[1], &locations[2]),
                    Atom::new(84),
                )
                .1,
            );

            {
                let result: Vec<i64> = list.iter().map(|d| *d.value.value()).collect();
                assert_eq!(vec![99, 23, 5, 84, 3, 44, 143], result);
            }
        }

        // Test Delete.
        {
            let uuids: Vec<Uuid> = list.iter().map(|d| d.id).collect();

            list.apply(list.delete(uuids[2]));

            list.apply(list.delete(uuids[3]));

            {
                let result: Vec<i64> = list.iter().map(|d| *d.value.value()).collect();
                assert_eq!(vec![99, 23, 3, 44, 143], result);
            }
        }

        // Test Move.
        {
            let uuids: Vec<Uuid> = list.iter().map(|d| d.id).collect();
            let locations: Vec<ZenoIndex> = list.iter().map(|d| d.location).collect();

            list.apply(list.move_item(
                uuids[0],
                ZenoIndex::new_between(&locations[2], &locations[3]),
            ));

            list.apply(list.move_item(uuids[4], ZenoIndex::new_before(&locations[0])));

            {
                let result: Vec<i64> = list.iter().map(|d| *d.value.value()).collect();
                assert_eq!(vec![143, 23, 3, 99, 44], result);
            }
        }
    }

    #[test]
    fn test_list_serialization() {
        // Serialization of nonempty List to JSON used to fail
        // because serde-json requires map keys to be strings.

        let mut list: List<Atom<i64>> = List::default();
        list.apply(list.append(Atom::new(5)).1);

        let result = serde_json::to_string(&list).unwrap();

        let parsed_list: List<Atom<i64>> = serde_json::from_str(&result).unwrap();

        assert_eq!(list.items, parsed_list.items);
        assert_eq!(list.items_inv, parsed_list.items_inv);
        assert_eq!(list.pool, parsed_list.pool);
    }
}