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
use crate::anchor::InnerAnchor as Anchor;
use crate::{LamportTs, Length, ReplicaId, RunTs, Text};
/// An insertion in CRDT coordinates.
///
/// This struct is created by the [`inserted`] method on the [`Replica`] owned
/// by the peer that performed the insertion, and can be integrated by another
/// [`Replica`] via the [`integrate_insertion`] method.
///
/// See the documentation of those methods for more information.
///
/// [`Replica`]: crate::Replica
/// [`inserted`]: crate::Replica::inserted
/// [`integrate_insertion`]: crate::Replica::integrate_insertion
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Insertion {
/// The anchor point of the insertion.
anchor: Anchor,
/// Contains the replica that made the insertion and the temporal range
/// of the text that was inserted.
text: Text,
/// The run timestamp of this insertion.
run_ts: RunTs,
/// The Lamport timestamp of this insertion.
lamport_ts: LamportTs,
}
impl Insertion {
#[inline(always)]
pub(crate) fn anchor(&self) -> Anchor {
self.anchor
}
#[inline(always)]
pub(crate) fn end(&self) -> Length {
self.text.range.end
}
/// Returns the [`ReplicaId`] of the [`Replica`](crate::Replica) that
/// performed the insertion.
///
/// # Examples
///
/// ```
/// # use cola::Replica;
/// let mut replica = Replica::new(1, 3);
/// let insertion = replica.inserted(3, 7);
/// assert_eq!(insertion.inserted_by(), replica.id());
/// ```
#[inline]
pub fn inserted_by(&self) -> ReplicaId {
self.text.inserted_by()
}
#[inline]
pub(crate) fn is_no_op(&self) -> bool {
self.len() == 0
}
#[inline(always)]
pub(crate) fn run_ts(&self) -> RunTs {
self.run_ts
}
#[inline(always)]
pub(crate) fn lamport_ts(&self) -> LamportTs {
self.lamport_ts
}
#[inline]
pub(crate) fn len(&self) -> Length {
self.text.len()
}
#[inline]
pub(crate) fn new(
anchor: Anchor,
text: Text,
lamport_ts: LamportTs,
run_ts: RunTs,
) -> Self {
Self { anchor, text, lamport_ts, run_ts }
}
#[inline]
pub(crate) fn no_op() -> Self {
Self::new(Anchor::zero(), Text::new(0, 0..0), 0, 0)
}
#[inline]
pub(crate) fn start(&self) -> Length {
self.text.range.start
}
/// The [`Text`] of this insertion.
#[inline]
pub fn text(&self) -> &Text {
&self.text
}
}
#[cfg(feature = "encode")]
mod encode {
use super::*;
use crate::encode::{BoolDecodeError, Decode, Encode, IntDecodeError};
impl Insertion {
#[inline]
fn encode_anchor(&self, run: InsertionRun, buf: &mut Vec<u8>) {
match run {
InsertionRun::BeginsNew => self.anchor.encode(buf),
InsertionRun::ContinuesExisting => {},
}
}
#[inline]
fn decode_anchor<'buf>(
run: InsertionRun,
text: &Text,
run_ts: RunTs,
buf: &'buf [u8],
) -> Result<(Anchor, &'buf [u8]), <Anchor as Decode>::Error> {
match run {
InsertionRun::BeginsNew => Anchor::decode(buf),
InsertionRun::ContinuesExisting => {
let anchor =
Anchor::new(text.inserted_by(), text.start(), run_ts);
Ok((anchor, buf))
},
}
}
}
impl Encode for Insertion {
#[inline]
fn encode(&self, buf: &mut Vec<u8>) {
self.text.encode(buf);
self.run_ts.encode(buf);
self.lamport_ts.encode(buf);
let run = InsertionRun::new(self);
run.encode(buf);
self.encode_anchor(run, buf);
}
}
pub(crate) enum InsertionDecodeError {
Int(IntDecodeError),
Run(BoolDecodeError),
}
impl From<IntDecodeError> for InsertionDecodeError {
#[inline]
fn from(err: IntDecodeError) -> Self {
Self::Int(err)
}
}
impl From<BoolDecodeError> for InsertionDecodeError {
#[inline]
fn from(err: BoolDecodeError) -> Self {
Self::Run(err)
}
}
impl core::fmt::Display for InsertionDecodeError {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let err: &dyn core::fmt::Display = match self {
Self::Int(err) => err,
Self::Run(err) => err,
};
write!(f, "InsertionRun couldn't be decoded: {err}")
}
}
impl Decode for Insertion {
type Value = Self;
type Error = InsertionDecodeError;
#[inline]
fn decode(buf: &[u8]) -> Result<(Self, &[u8]), Self::Error> {
let (text, buf) = Text::decode(buf)?;
let (run_ts, buf) = RunTs::decode(buf)?;
let (lamport_ts, buf) = LamportTs::decode(buf)?;
let (run, buf) = InsertionRun::decode(buf)?;
let (anchor, buf) = Self::decode_anchor(run, &text, run_ts, buf)?;
let insertion = Self::new(anchor, text, lamport_ts, run_ts);
Ok((insertion, buf))
}
}
/// Whether an [`Insertion`] begins a new run or continues an existing one.
///
/// This is used when encoding and decoding [`Insertion`]s to determine
/// whether their [`Anchor`] needs to be encoded.
///
/// Most of the time when people edit a document they insert a bunch of
/// characters in a single run before moving the cursor or deleting some
/// text, and we can use this pattern to save some bytes.
///
/// For example, if someone types "foo" sequentially in a blank document,
/// we'll create the following insertions (assuming a `ReplicaId` of 1 and
/// omitting fields that aren't relevant to this discussion):
///
/// ```text
/// f -> Insertion { anchor: zero, text: 1.0..1, .. },
/// o -> Insertion { anchor: 1.1, text: 1.1..2, .. },
/// o -> Insertion { anchor: 1.2, text: 1.2..3, .. },
/// ```
///
/// The first insertion begins a new run, but from then on every
/// Insertion's anchor is the same as the start of its text.
///
/// This means that we can save space when encoding by omitting the anchor
/// and adding a flag that indicates that it should be derived from the
/// text and the run timestamp.
///
/// This enum corresponds to that flag.
enum InsertionRun {
/// The [`Insertion`] begins a new run.
///
/// In this case we also encode the insertion's [`Anchor`].
BeginsNew,
/// The [`Insertion`] continues an existing run.
///
/// In this case we can avoid encoding the insertion's [`Anchor`]
/// because it can be fully decoded from the insertion's [`Text`] and
/// [`RunTs`].
ContinuesExisting,
}
impl InsertionRun {
#[inline]
fn new(insertion: &Insertion) -> Self {
// To determine whether this insertion is a continuation of an
// existing insertion run we simply check:
//
// 1: the `ReplicaId`s of the anchor and the text. Clearly they
// must match because you can't continue someone else's
// insertion;
//
// 2: the `RunTs` of the anchor and the insertion. Since that
// counter is only incremented when a new insertion run begins,
// we know that if they match then this insertion must continue
// an existing run.
let is_continuation = insertion.anchor.replica_id()
== insertion.text.inserted_by()
&& insertion.anchor.run_ts() == insertion.run_ts();
if is_continuation {
Self::ContinuesExisting
} else {
Self::BeginsNew
}
}
}
impl Encode for InsertionRun {
#[inline]
fn encode(&self, buf: &mut Vec<u8>) {
matches!(self, Self::ContinuesExisting).encode(buf);
}
}
impl Decode for InsertionRun {
type Value = Self;
type Error = BoolDecodeError;
#[inline]
fn decode(buf: &[u8]) -> Result<(Self, &[u8]), Self::Error> {
let (is_continuation, rest) = bool::decode(buf)?;
let this = if is_continuation {
Self::ContinuesExisting
} else {
Self::BeginsNew
};
Ok((this, rest))
}
}
}
#[cfg(feature = "serde")]
mod serde {
crate::encode::impl_deserialize!(super::Insertion);
crate::encode::impl_serialize!(super::Insertion);
}
#[cfg(all(test, feature = "encode"))]
mod encode_tests {
use super::*;
use crate::encode::{Decode, Encode};
impl core::fmt::Debug for encode::InsertionDecodeError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
core::fmt::Display::fmt(self, f)
}
}
#[test]
fn encode_insertion_round_trip_0() {
let anchor = Anchor::new(1, 1, 1);
let text = Text::new(2, 0..1);
let insertion = Insertion::new(anchor, text, 3, 0);
let mut buf = Vec::new();
insertion.encode(&mut buf);
let (decoded, rest) = Insertion::decode(&buf).unwrap();
assert_eq!(insertion, decoded);
assert!(rest.is_empty());
}
}