automerge 0.9.0

A JSON-like data structure (a CRDT) that can be modified concurrently by different users, and merged again automatically
Documentation
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
use std::borrow::Cow;

// Test that looking up by index works across diferent ways of calculating
// the index
//
// Places in the codebase where we use indexes for manipulating text:
//
// # Reading values
//
// - ReadDoc::length and ReadDoc::length_at
// - ReadDoc::marks and ReadDoc::marks_at (via the Mark::start and Mark::end)
//   fields
// - ReadDoc::get_cursor
// - ReadDoc::get and ReadDoc::get_at
// - ReadDoc::get_all and ReadDoc::get_all_at
//
// # Writing values
//
// - Transactable::put
// - Transactable::insert
// - Transactable::delete
// - Transactable::splice_text
// - Transactable::mark
// - Transactable::unmark
// - Transactable::split_block
//
// # Patches
//
// - PatchAction::PutSeq
// - PatchAction::Insert
// - PatchAction::SpliceText
// - PatchAction::Conflict
// - PatchAction::DeleteSeq
// - PatchAction::Mark
//
// The task here is to ensure that all these methods work correctly when
// different ways of calculating the index are used. There are four different
// ways of calculating indexes in a text object:
//
// - The unicode code point index within a stream of characters
// - The UTF-8 code unit offset, i.e. the byte offset into a UTF-8 encoding of
//   the text
// - The UTF-16 code unit offset
// - The grapheme cluster index
use automerge::{
    marks::{ExpandMark, Mark},
    transaction::Transactable,
    AutoCommit, ObjId, ObjType, ReadDoc, ScalarValue, Value, ROOT,
};

#[derive(Debug, PartialEq, Clone, Copy)]
enum Encoding {
    UnicodeCodePoint,
    Utf8CodeUnit,
    Utf16CodeUnit,
    GraphemeCluster,
}

impl From<Encoding> for automerge::TextEncoding {
    fn from(value: Encoding) -> Self {
        match value {
            Encoding::UnicodeCodePoint => automerge::TextEncoding::UnicodeCodePoint,
            Encoding::Utf8CodeUnit => automerge::TextEncoding::Utf8CodeUnit,
            Encoding::Utf16CodeUnit => automerge::TextEncoding::Utf16CodeUnit,
            Encoding::GraphemeCluster => automerge::TextEncoding::GraphemeCluster,
        }
    }
}

impl std::fmt::Display for Encoding {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::UnicodeCodePoint => write!(f, "UnicodeCodePoint"),
            Self::Utf8CodeUnit => write!(f, "Utf8CodeUnit"),
            Self::Utf16CodeUnit => write!(f, "Utf16CodeUnit"),
            Self::GraphemeCluster => write!(f, "GraphemeCluster"),
        }
    }
}

enum Expected<T> {
    Always(T),
    ByEncoding {
        code_point: T,
        utf8: T,
        utf16: T,
        grapheme: T,
    },
}

impl<T: PartialEq + std::fmt::Debug> Expected<T> {
    fn assert(&self, actual: &T, encoding: Encoding) {
        match self {
            Self::Always(t) => assert_eq!(actual, t, "failed for {}", encoding),
            Self::ByEncoding {
                code_point,
                utf8,
                utf16,
                grapheme,
            } => match encoding {
                Encoding::UnicodeCodePoint => {
                    assert_eq!(actual, code_point, "failed for {}", encoding)
                }
                Encoding::Utf8CodeUnit => assert_eq!(actual, utf8, "failed for {}", encoding),
                Encoding::Utf16CodeUnit => assert_eq!(actual, utf16, "failed for {}", encoding),
                Encoding::GraphemeCluster => {
                    assert_eq!(actual, grapheme, "failed for {}", encoding)
                }
            },
        }
    }
}

struct Scenario<F, T> {
    text: &'static str,
    action: F,
    expected: Expected<T>,
}

impl<F: Fn(&mut AutoCommit, &automerge::ObjId, Encoding) -> T, T: PartialEq + std::fmt::Debug>
    Scenario<F, T>
{
    fn run(&self) {
        for encoding in [
            Encoding::UnicodeCodePoint,
            Encoding::Utf8CodeUnit,
            Encoding::Utf16CodeUnit,
            Encoding::GraphemeCluster,
        ] {
            self.run_with_encoding(encoding);
        }
    }

    fn run_with_encoding(&self, encoding: Encoding) {
        let mut doc = AutoCommit::new_with_encoding(encoding.into());
        let text = doc.put_object(ROOT, "text", ObjType::Text).unwrap();
        doc.splice_text(&text, 0, 0, self.text).unwrap();
        let result = (self.action)(&mut doc, &text, encoding);
        self.expected.assert(&result, encoding);
    }
}

impl<
        F: Fn(&mut AutoCommit, &automerge::ObjId, Encoding) -> Result<T, String>,
        T: PartialEq + std::fmt::Debug,
    > Scenario<F, T>
{
    fn run_fallible(&self) {
        for encoding in [
            Encoding::UnicodeCodePoint,
            Encoding::Utf8CodeUnit,
            Encoding::Utf16CodeUnit,
            Encoding::GraphemeCluster,
        ] {
            self.run_fallible_with_encoding(encoding);
        }
    }

    fn run_fallible_with_encoding(&self, encoding: Encoding) {
        let mut doc = AutoCommit::new_with_encoding(encoding.into());
        let text = doc.put_object(ROOT, "text", ObjType::Text).unwrap();
        doc.splice_text(&text, 0, 0, self.text).unwrap();
        let result = (self.action)(&mut doc, &text, encoding);
        match result {
            Ok(result) => self.expected.assert(&result, encoding),
            Err(e) => panic!("failed for {}: {}", encoding, e),
        }
    }
}

// All of the following tests use the πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦ emoji which is the following sequence of code points:
//
// - U+1F469 WOM
// - U+200D ZWJ
// - U+1F467 GIRL
// - U+1f466 BOY
//
// This is a useful test case because it is:
//
// * A single grapheme cluster
// * 7 code points
// * 11 utf-16 code units
// * 25 utf-8 code units

#[test]
fn length() {
    Scenario {
        text: "helloπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦",
        action: |doc: &mut AutoCommit, text: &ObjId, _encoding: Encoding| doc.length(text),
        expected: Expected::ByEncoding {
            code_point: 12,
            utf8: 30,
            utf16: 16,
            grapheme: 6,
        },
    }
    .run();
}

#[test]
fn splice_text() {
    Scenario {
        text: "hello πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦ world",
        action: |doc: &mut AutoCommit, text: &ObjId, encoding: Encoding| {
            let insert_index = match encoding {
                Encoding::UnicodeCodePoint => 14,
                Encoding::Utf8CodeUnit => 32,
                Encoding::Utf16CodeUnit => 18,
                Encoding::GraphemeCluster => 8,
            };
            doc.splice_text(text, insert_index, 0, "beautiful ")
                .unwrap();
            doc.text(text).unwrap()
        },
        expected: Expected::Always("hello πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦ beautiful world".to_string()),
    }
    .run();
}

#[test]
fn mark() {
    Scenario {
        text: "heπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦llo",
        action: |doc: &mut AutoCommit, text: &ObjId, encoding: Encoding| {
            let end_index = match encoding {
                Encoding::UnicodeCodePoint => 11,
                Encoding::Utf8CodeUnit => 27,
                Encoding::Utf16CodeUnit => 13,
                Encoding::GraphemeCluster => 4,
            };
            let mark = Mark::new("bold".to_string(), true, 1, end_index);
            doc.mark(text, mark, ExpandMark::Both).unwrap();
            doc.marks(text)
                .unwrap()
                .into_iter()
                .map(|m| (m.start, m.end))
                .collect::<Vec<_>>()
        },
        expected: Expected::ByEncoding {
            code_point: vec![(1, 11)],
            utf8: vec![(1, 27)],
            utf16: vec![(1, 13)],
            grapheme: vec![(1, 4)],
        },
    }
    .run()
}

#[test]
fn unmark() {
    Scenario {
        text: "heπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦llo",
        action: |doc: &mut AutoCommit, text: &ObjId, encoding: Encoding| {
            let end_index = match encoding {
                Encoding::UnicodeCodePoint => 11,
                Encoding::Utf8CodeUnit => 27,
                Encoding::Utf16CodeUnit => 13,
                Encoding::GraphemeCluster => 4,
            };
            let mark = Mark::new("bold".to_string(), true, 1, end_index);
            doc.mark(text, mark, ExpandMark::Both).unwrap();
            doc.unmark(text, "bold", 1, end_index, ExpandMark::Both)
                .unwrap();
            doc.marks(text)
                .unwrap()
                .into_iter()
                .map(|m| (m.start, m.end))
                .collect::<Vec<_>>()
        },
        expected: Expected::Always(Vec::new()),
    }
    .run()
}

#[test]
fn cursors() {
    // Get a cursor for the first 'l' in 'heπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦llo', then insert a 'πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦' before
    // the 'l' and lookup the index of the cursor afterwards.
    Scenario {
        text: "heπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦llo",
        action: |doc: &mut AutoCommit, text: &ObjId, encoding: Encoding| {
            let cursor_index = match encoding {
                Encoding::UnicodeCodePoint => 9,
                Encoding::Utf8CodeUnit => 27,
                Encoding::Utf16CodeUnit => 13,
                Encoding::GraphemeCluster => 3,
            };
            let cursor = doc.get_cursor(text, cursor_index, None).unwrap();
            doc.splice_text(text, 2, 0, "πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦").unwrap();
            doc.get_cursor_position(text, &cursor, None).unwrap()
        },
        expected: Expected::ByEncoding {
            code_point: 16,
            utf8: 52,
            utf16: 24,
            grapheme: 4,
        },
    }
    .run()
}

#[test]
fn get() {
    Scenario {
        text: "heπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦lo",
        action: |doc: &mut AutoCommit, text: &ObjId, encoding: Encoding| {
            let index = match encoding {
                Encoding::UnicodeCodePoint => 9,
                Encoding::Utf8CodeUnit => 27,
                Encoding::Utf16CodeUnit => 13,
                Encoding::GraphemeCluster => 3,
            };
            match doc.get(text, index).unwrap() {
                Some((Value::Scalar(s), _)) => match s.as_ref() {
                    ScalarValue::Str(s) => Some(s.to_string()),
                    _ => None,
                },
                _ => None,
            }
        },
        expected: Expected::Always(Some("l".to_string())),
    }
    .run()
}

#[test]
fn put() {
    Scenario {
        text: "heπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦llo",
        action: |doc: &mut AutoCommit, text: &ObjId, encoding: Encoding| {
            let index = match encoding {
                Encoding::UnicodeCodePoint => 9,
                Encoding::Utf8CodeUnit => 27,
                Encoding::Utf16CodeUnit => 13,
                Encoding::GraphemeCluster => 3,
            };
            doc.put(text, index, "L").unwrap();
            doc.text(text).unwrap()
        },
        expected: Expected::Always("heπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦Llo".to_string()),
    }
    .run()
}

#[test]
fn insert() {
    Scenario {
        text: "heπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦llo",
        action: |doc: &mut AutoCommit, text: &ObjId, encoding: Encoding| {
            let index = match encoding {
                Encoding::UnicodeCodePoint => 9,
                Encoding::Utf8CodeUnit => 27,
                Encoding::Utf16CodeUnit => 13,
                Encoding::GraphemeCluster => 3,
            };
            doc.insert(text, index, "L").unwrap();
            doc.text(text).unwrap()
        },
        expected: Expected::Always("heπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦Lllo".to_string()),
    }
    .run()
}

#[test]
fn delete() {
    Scenario {
        text: "heπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦llo",
        action: |doc: &mut AutoCommit, text: &ObjId, encoding: Encoding| {
            let index = match encoding {
                Encoding::UnicodeCodePoint => 9,
                Encoding::Utf8CodeUnit => 27,
                Encoding::Utf16CodeUnit => 13,
                Encoding::GraphemeCluster => 3,
            };
            doc.delete(text, index).unwrap();
            doc.text(text).unwrap()
        },
        expected: Expected::Always("heπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦lo".to_string()),
    }
    .run()
}

#[test]
fn split_block() {
    Scenario {
        text: "heπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦llo",
        action: |doc: &mut AutoCommit, text: &ObjId, encoding: Encoding| {
            let index = match encoding {
                Encoding::UnicodeCodePoint => 9,
                Encoding::Utf8CodeUnit => 27,
                Encoding::Utf16CodeUnit => 13,
                Encoding::GraphemeCluster => 3,
            };
            doc.split_block(text, index).unwrap();
            doc.spans(text)
                .unwrap()
                .filter_map(|s| match s {
                    automerge::iter::Span::Text {
                        text: val,
                        marks: _,
                    } => Some(val),
                    automerge::iter::Span::Block(_) => None,
                })
                .collect::<Vec<_>>()
        },
        expected: Expected::Always(vec!["heπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦".to_string(), "llo".to_string()]),
    }
    .run()
}

#[test]
fn patch_put_seq() {
    Scenario {
        text: "heπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦llo",
        action: |doc: &mut AutoCommit, text: &ObjId, encoding: Encoding| {
            let index = match encoding {
                Encoding::UnicodeCodePoint => 9,
                Encoding::Utf8CodeUnit => 27,
                Encoding::Utf16CodeUnit => 13,
                Encoding::GraphemeCluster => 3,
            };
            doc.update_diff_cursor();
            println!(" ENCODING = {:?}", encoding);
            doc.put(text, index, "L").unwrap();
            let indexes = doc
                .diff_incremental()
                .into_iter()
                .map(|p| match p {
                    automerge::Patch {
                        action: automerge::PatchAction::PutSeq { index, value, .. },
                        ..
                    } => {
                        if value.0 == Value::Scalar(Cow::Owned(ScalarValue::Str("L".into()))) {
                            Ok(index)
                        } else {
                            Err(format!("unexpected value {}", value.0).to_string())
                        }
                    }
                    other => Err(format!("unexpected patch action {:?}", other).to_string()),
                })
                .collect::<Result<Vec<_>, _>>()?;
            if indexes.len() != 1 {
                return Err(format!("expected 1 patch, got {}", indexes.len()));
            }
            Ok(indexes[0])
        },
        expected: Expected::ByEncoding {
            code_point: 9,
            utf8: 27,
            utf16: 13,
            grapheme: 3,
        },
    }
    .run_fallible()
}

#[test]
fn patch_insert() {
    Scenario {
        text: "heπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦llo",
        action: |doc: &mut AutoCommit, text: &ObjId, encoding: Encoding| {
            let index = match encoding {
                Encoding::UnicodeCodePoint => 9,
                Encoding::Utf8CodeUnit => 27,
                Encoding::Utf16CodeUnit => 13,
                Encoding::GraphemeCluster => 3,
            };
            doc.update_diff_cursor();
            doc.insert(text, index, "L").unwrap();
            let indexes = doc
                .diff_incremental()
                .into_iter()
                .map(|p| match p {
                    automerge::Patch {
                        action: automerge::PatchAction::SpliceText { index, value, .. },
                        ..
                    } => {
                        if value.make_string() != "L" {
                            Err(format!("unexpected value {}", value.make_string()).to_string())
                        } else {
                            Ok(index)
                        }
                    }
                    other => Err(format!("unexpected patch action {:?}", other).to_string()),
                })
                .collect::<Result<Vec<_>, _>>()?;
            if indexes.len() != 1 {
                return Err(format!("expected 1 patch, got {}", indexes.len()));
            }
            Ok(indexes[0])
        },
        expected: Expected::ByEncoding {
            code_point: 9,
            utf8: 27,
            utf16: 13,
            grapheme: 3,
        },
    }
    .run_fallible()
}

#[test]
fn patch_splice_text() {
    Scenario {
        text: "heπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦llo",
        action: |doc: &mut AutoCommit, text: &ObjId, encoding: Encoding| {
            let index = match encoding {
                Encoding::UnicodeCodePoint => 9,
                Encoding::Utf8CodeUnit => 27,
                Encoding::Utf16CodeUnit => 13,
                Encoding::GraphemeCluster => 3,
            };
            doc.update_diff_cursor();
            doc.splice_text(text, index, 0, "L").unwrap();
            let indexes = doc
                .diff_incremental()
                .into_iter()
                .map(|p| match p {
                    automerge::Patch {
                        action: automerge::PatchAction::SpliceText { index, value, .. },
                        ..
                    } => {
                        if value.make_string() != "L" {
                            Err(format!("unexpected value {}", value.make_string()).to_string())
                        } else {
                            Ok(index)
                        }
                    }
                    other => Err(format!("unexpected patch action {:?}", other).to_string()),
                })
                .collect::<Result<Vec<_>, _>>()?;
            if indexes.len() != 1 {
                return Err(format!("expected 1 patch, got {}", indexes.len()));
            }
            Ok(indexes[0])
        },
        expected: Expected::ByEncoding {
            code_point: 9,
            utf8: 27,
            utf16: 13,
            grapheme: 3,
        },
    }
    .run_fallible()
}

#[test]
fn patch_delete() {
    Scenario {
        text: "heπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦llo",
        action: |doc: &mut AutoCommit, text: &ObjId, encoding: Encoding| {
            let index = match encoding {
                Encoding::UnicodeCodePoint => 9,
                Encoding::Utf8CodeUnit => 27,
                Encoding::Utf16CodeUnit => 13,
                Encoding::GraphemeCluster => 3,
            };
            doc.update_diff_cursor();
            doc.delete(text, index).unwrap();
            let indexes = doc
                .diff_incremental()
                .into_iter()
                .map(|p| match p {
                    automerge::Patch {
                        action: automerge::PatchAction::DeleteSeq { index, length, .. },
                        ..
                    } => {
                        if length != 1 {
                            Err(format!("unexpected length {}", length).to_string())
                        } else {
                            Ok(index)
                        }
                    }
                    other => Err(format!("unexpected patch action {:?}", other).to_string()),
                })
                .collect::<Result<Vec<_>, _>>()?;
            if indexes.len() != 1 {
                return Err(format!("expected 1 patch, got {}", indexes.len()));
            }
            Ok(indexes[0])
        },
        expected: Expected::ByEncoding {
            code_point: 9,
            utf8: 27,
            utf16: 13,
            grapheme: 3,
        },
    }
    .run_fallible()
}

#[test]
fn patch_mark() {
    Scenario {
        text: "heπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦llo",
        action: |doc: &mut AutoCommit, text: &ObjId, encoding: Encoding| {
            let end_index = match encoding {
                Encoding::UnicodeCodePoint => 9,
                Encoding::Utf8CodeUnit => 27,
                Encoding::Utf16CodeUnit => 13,
                Encoding::GraphemeCluster => 3,
            };
            let mark = Mark::new("bold".to_string(), true, 1, end_index);
            doc.diff_incremental();
            doc.mark(text, mark, ExpandMark::Both).unwrap();
            let indexes = doc
                .diff_incremental()
                .into_iter()
                .filter(|p| p.obj == *text)
                .map(|p| match p {
                    automerge::Patch {
                        action: automerge::PatchAction::Mark { mut marks },
                        ..
                    } => {
                        if marks.len() != 1 {
                            return Err(format!("expected 1 mark, got {}", marks.len()));
                        }
                        let mark = marks.pop().unwrap();
                        if mark.name() != "bold" {
                            return Err(format!("unexpected mark name {}", mark.name()));
                        }
                        Ok((mark.start, mark.end))
                    }
                    other => Err(format!("unexpected patch action {:?}", other).to_string()),
                })
                .collect::<Result<Vec<_>, _>>()?;
            if indexes.len() != 1 {
                return Err(format!("expected 1 patch, got {}", indexes.len()));
            }
            Ok(indexes[0])
        },
        expected: Expected::ByEncoding {
            code_point: (1, 9),
            utf8: (1, 27),
            utf16: (1, 13),
            grapheme: (1, 3),
        },
    }
    .run_fallible()
}