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
use std::ops::{Bound, RangeBounds};
use std::fmt;

use crate::{Author, Change, Chronofold, LogIndex, Op, Timestamp};

/// An editing session tied to one author.
///
/// `Session` provides a lot of functions you might know from `Vec` or
/// `VecDeque`. Under the hood, `Session` will append changes to the
/// chronofolds log.
///
/// Note that `Session` has a mutable (exclusive) borrow of a chronofold. So
/// Rust's ownership rules enforce that there is always just one `Session` per
/// chronofold.
#[derive(Debug)]
pub struct Session<'a, A: Author, T> {
    chronofold: &'a mut Chronofold<A, T>,
    author: A,
    first_index: LogIndex,
}

impl<'a, A: Author, T: fmt::Debug> Session<'a, A, T> {
    /// Creates an editing session for a single author.
    pub fn new(author: A, chronofold: &'a mut Chronofold<A, T>) -> Self {
        let first_index = chronofold.next_log_index();
        Self {
            chronofold,
            author,
            first_index,
        }
    }

    /// Clears the chronofold, removing all elements.
    pub fn clear(&mut self) {
        let indices = self
            .chronofold
            .iter()
            .map(|(_, idx)| idx)
            .collect::<Vec<_>>();
        for idx in indices {
            self.remove(idx);
        }
    }

    /// Appends an element to the back of the chronofold and returns the new
    /// element's log index.
    pub fn push_back(&mut self, value: T) -> LogIndex {
        if let Some((_, last_index)) = self.chronofold.iter().last() {
            self.insert_after(Some(last_index), value)
        } else {
            self.insert_after(None, value)
        }
    }

    /// Prepends an element to the chronofold and returns the new element's log
    /// index.
    pub fn push_front(&mut self, value: T) -> LogIndex {
        self.insert_after(None, value)
    }

    /// Inserts an element after the element with log index `index` and returns
    /// the new element's log index.
    ///
    /// If `index == None`, the element will be inserted at the beginning.
    pub fn insert_after(&mut self, index: Option<LogIndex>, value: T) -> LogIndex {
        self.apply_change(index, Change::Insert(value))
    }

    /// Removes the element with log index `index` from the chronofold.
    ///
    /// Note that this just marks the element as deleted, not actually modify
    /// the log apart from appending a `Change::Delete`.
    pub fn remove(&mut self, index: LogIndex) {
        self.apply_change(Some(index), Change::Delete);
    }

    /// Extends the chronofold with the contents of `iter`, returns the log
    /// index of the last inserted element, if any.
    pub fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) -> Option<LogIndex> {
        let oob = LogIndex(self.chronofold.log.len());
        self.splice(oob..oob, iter)
    }

    /// Replaces the specified range in the chronofold with the given
    /// `replace_with` iterator and returns the log index of the last inserted
    /// element, if any.
    pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Option<LogIndex>
    where
        I: IntoIterator<Item = T>,
        R: RangeBounds<LogIndex>,
    {
        let mut last_idx = match range.start_bound() {
            Bound::Unbounded => None,
            Bound::Included(idx) => self.chronofold.index_before(*idx),
            Bound::Excluded(idx) => Some(*idx),
        };
        let to_remove: Vec<LogIndex> = self
            .chronofold
            .iter_range(range)
            .map(|(_, idx)| idx)
            .collect();
        for idx in to_remove.into_iter() {
            self.remove(idx);
        }
        for v in replace_with.into_iter() {
            last_idx = Some(self.insert_after(last_idx, v));
        }
        last_idx
    }

    fn apply_change(&mut self, reference: Option<LogIndex>, change: Change<T>) -> LogIndex {
        self.chronofold
            .apply_change(self.next_timestamp(), reference, change)
            .expect("application of own change should never fail")
    }

    fn next_timestamp(&self) -> Timestamp<A> {
        let next_index = LogIndex(self.chronofold.log.len());
        Timestamp(next_index, self.author)
    }
}

impl<'a, A: Author, T: Clone> Session<'a, A, T> {
    /// Returns an iterator over ops in log order, that where created in this
    /// session.
    pub fn iter_ops(&'a self) -> impl Iterator<Item = Op<A, T>> + 'a {
        self.chronofold
            .iter_ops(self.first_index..)
            .filter(move |op| op.id.1 == self.author)
    }
}

impl<A: Author, T> AsRef<Chronofold<A, T>> for Session<'_, A, T> {
    fn as_ref(&self) -> &Chronofold<A, T> {
        self.chronofold
    }
}

impl<A: Author, T> AsMut<Chronofold<A, T>> for Session<'_, A, T> {
    fn as_mut(&mut self) -> &mut Chronofold<A, T> {
        self.chronofold
    }
}