lb_rs/model/text/
buffer.rs

1use super::offset_types::{DocByteOffset, DocCharOffset, RangeExt, RelCharOffset};
2use super::operation_types::{InverseOperation, Operation, Replace};
3use super::unicode_segs::UnicodeSegs;
4use super::{diff, unicode_segs};
5use std::ops::Index;
6use std::time::{Duration, Instant};
7use unicode_segmentation::UnicodeSegmentation;
8
9/// Long-lived state of the editor's text buffer. Factored into sub-structs for borrow-checking.
10/// # Operation algebra
11/// Operations are created based on a version of the buffer. This version is called the operation's base and is
12/// identified with a sequence number. When the base of an operation is equal to the buffer's current sequence number,
13/// the operation can be applied and increments the buffer's sequence number.
14///
15/// When multiple operations are created based on the same version of the buffer, such as when a user types a few
16/// keystrokes in one frame or issues a command like indenting multiple list items, the operations all have the same
17/// base. Once the first operation is applied and the buffer's sequence number is incremented, the base of the
18/// remaining operations must be incremented by using the first operation to transform them before they can be applied.
19/// This corresponds to the reality that the buffer state has changed since the operation was created and the operation
20/// must be re-interpreted. For example, if text is typed at the beginning then end of a buffer in one frame, the
21/// position of the text typed at the end of the buffer is greater when it is applied than it was when it was typed.
22///
23/// External changes are merged into the buffer by creating a set of operations that would transform the buffer from
24/// the last external state to the current state. These operations, based on the version of the buffer at the last
25/// successful save or load, must be transformed by all operations that have been applied since (this means we must
26/// preserve the undo history for at least that long; if this presents performance issues, we can always save). Each
27/// operation that is transforming the new operations will match the base of the new operations at the time of
28/// transformation. Finally, the operations will need to transform each other just like any other set of operations
29/// made in a single frame/made based on the same version of the buffer.
30///
31/// # Undo (work in progress)
32/// Undo should revert local changes only, leaving external changes in-tact, so that when all local changes are undone,
33/// the buffer is in a state reflecting external changes only. This is complicated by the fact that external changes
34/// may have been based on local changes that were synced to another client. To undo an operation that had an external
35/// change based on it, we have to interpret the external change in the absence of local changes that were present when
36/// it was created. This is the opposite of interpreting the external change in the presence of local changes that were
37/// not present when it was created i.e. the normal flow of merging external changes. Here, we are removing a local
38/// operation from the middle of the chain of operations that led to the current state of the buffer.
39///
40/// To do this, we perform the dance of transforming operations in reverse, taking a chain of operations each based on
41/// the prior and transforming them into a set of operations based on the same base as the operation to be undone. Then
42/// we remove the operation to be undone and apply the remaining operations with the forward transformation flow.
43///
44/// Operations are not invertible i.e. you cannot construct an inverse operation that will perfectly cancel out the
45/// effect of another operation regardless of the time of interpretation. For example, with a text replacement, you can
46/// construct an inverse text replacement that replaces the new range with the original text, but when operations are
47/// undone from the middle of the chain, it may affect the original text. The operation will be re-interpreted based on
48/// a new state of the buffer at its time of application. The replaced text has no fixed value by design.
49///
50/// However, it is possible to undo the specific application of an operation in the context of the state of the buffer
51/// when it was applied. We store information necessary to undo applied operations alongside the operations themselves
52/// i.e. the text replaced in the application. When the operation is transformed for any reason, this undo information
53/// is invalidated.
54#[derive(Default)]
55pub struct Buffer {
56    /// Current contents of the buffer (what should be displayed in the editor). Todo: hide behind a read-only accessor
57    pub current: Snapshot,
58
59    /// Snapshot of the buffer at the earliest undoable state. Operations are compacted into this as they overflow the
60    /// undo limit.
61    base: Snapshot,
62
63    /// Operations received by the buffer. Used for undo/redo and for merging external changes.
64    ops: Ops,
65
66    /// State for tracking out-of-editor changes
67    external: External,
68}
69
70#[derive(Debug, Default)]
71pub struct Snapshot {
72    pub text: String,
73    pub segs: UnicodeSegs,
74    pub selection: (DocCharOffset, DocCharOffset),
75    pub seq: usize,
76}
77
78impl Snapshot {
79    fn apply_select(&mut self, range: (DocCharOffset, DocCharOffset)) -> Response {
80        self.selection = range;
81        Response { text_updated: false }
82    }
83
84    fn apply_replace(&mut self, replace: &Replace) -> Response {
85        let Replace { range, text } = replace;
86        let byte_range = self.segs.range_to_byte(*range);
87
88        self.text
89            .replace_range(byte_range.start().0..byte_range.end().0, text);
90        self.segs = unicode_segs::calc(&self.text);
91        adjust_subsequent_range(
92            *range,
93            text.graphemes(true).count().into(),
94            false,
95            &mut self.selection,
96        );
97
98        Response { text_updated: true }
99    }
100
101    fn invert(&self, op: &Operation) -> InverseOperation {
102        let mut inverse = InverseOperation { replace: None, select: self.selection };
103        if let Operation::Replace(replace) = op {
104            inverse.replace = Some(self.invert_replace(replace));
105        }
106        inverse
107    }
108
109    fn invert_replace(&self, replace: &Replace) -> Replace {
110        let Replace { range, text } = replace;
111        let byte_range = self.segs.range_to_byte(*range);
112        let replaced_text = self[byte_range].into();
113        let replacement_range = (range.start(), range.start() + text.graphemes(true).count());
114        Replace { range: replacement_range, text: replaced_text }
115    }
116}
117
118#[derive(Default)]
119struct Ops {
120    /// Operations that have been received by the buffer
121    all: Vec<Operation>,
122    meta: Vec<OpMeta>,
123
124    /// Sequence number of the first unapplied operation. Operations starting with this one are queued for processing.
125    processed_seq: usize,
126
127    /// Operations that have been applied to the buffer and already transformed, in order of application. Each of these
128    /// operations is based on the previous operation in this list, with the first based on the history base. Derived
129    /// from other data and invalidated by some undo/redo flows.
130    transformed: Vec<Operation>,
131
132    /// Operations representing the inverse of the operations in `transformed_ops`, in order of application. Useful for
133    /// undoing operations. The data model differs because an operation that replaces text containing the cursor needs
134    /// two operations to revert the text and cursor. Derived from other data and invalidated by some undo/redo flows.
135    transformed_inverted: Vec<InverseOperation>,
136}
137
138impl Ops {
139    fn len(&self) -> usize {
140        self.all.len()
141    }
142
143    fn is_undo_checkpoint(&self, idx: usize) -> bool {
144        // start and end of undo history are checkpoints
145        if idx == 0 {
146            return true;
147        }
148        if idx == self.len() {
149            return true;
150        }
151
152        // events separated by enough time are checkpoints
153        let meta = &self.meta[idx];
154        let prev_meta = &self.meta[idx - 1];
155        if meta.timestamp - prev_meta.timestamp > Duration::from_millis(500) {
156            return true;
157        }
158
159        // immediately after a standalone selection is a checkpoint
160        let mut prev_op_standalone = meta.base != prev_meta.base;
161        if idx > 1 {
162            let prev_prev_meta = &self.meta[idx - 2];
163            prev_op_standalone &= prev_meta.base != prev_prev_meta.base;
164        }
165        let prev_op_selection = matches!(&self.all[idx - 1], Operation::Select(..));
166        if prev_op_standalone && prev_op_selection {
167            return true;
168        }
169
170        false
171    }
172}
173
174#[derive(Default)]
175struct External {
176    /// Text last loaded into the editor. Used as a reference point for merging out-of-editor changes with in-editor
177    /// changes, similar to a base in a 3-way merge. May be a state that never appears in the buffer's history.
178    text: String,
179
180    /// Index of the last external operation referenced when merging changes. May be ahead of current.seq if there has
181    /// not been a call to `update()` (updates current.seq) since the last call to `reload()` (assigns new greatest seq
182    /// to `external_seq`).
183    seq: usize,
184}
185
186#[derive(Default)]
187pub struct Response {
188    text_updated: bool,
189}
190
191impl std::ops::BitOrAssign for Response {
192    fn bitor_assign(&mut self, other: Response) {
193        self.text_updated |= other.text_updated;
194    }
195}
196
197impl From<Response> for bool {
198    fn from(value: Response) -> Self {
199        value.text_updated
200    }
201}
202
203/// Additional metadata tracked alongside operations internally.
204#[derive(Clone, Debug)]
205struct OpMeta {
206    /// At what time was this operation applied? Affects undo units.
207    pub timestamp: Instant,
208
209    /// What version of the buffer was the modifier looking at when they made this operation? Used for operational
210    /// transformation, both when applying multiple operations in one frame and when merging out-of-editor changes.
211    /// The magic happens here.
212    pub base: usize,
213}
214
215impl Buffer {
216    /// Push a series of operations onto the buffer's input queue; operations will be undone/redone atomically. Useful
217    /// for batches of internal operations produced from a single input event e.g. multi-line list identation.
218    pub fn queue(&mut self, mut ops: Vec<Operation>) {
219        let timestamp = Instant::now();
220        let base = self.current.seq;
221
222        // combine adjacent replacements
223        let mut combined_ops = Vec::new();
224        ops.sort_by_key(|op| match op {
225            Operation::Select(range) | Operation::Replace(Replace { range, .. }) => range.start(),
226        });
227        for op in ops.into_iter() {
228            match &op {
229                Operation::Replace(Replace { range: op_range, text: op_text }) => {
230                    if let Some(Operation::Replace(Replace {
231                        range: last_op_range,
232                        text: last_op_text,
233                    })) = combined_ops.last_mut()
234                    {
235                        if last_op_range.end() == op_range.start() {
236                            last_op_range.1 = op_range.1;
237                            last_op_text.push_str(op_text);
238                        } else {
239                            combined_ops.push(op);
240                        }
241                    } else {
242                        combined_ops.push(op);
243                    }
244                }
245                Operation::Select(_) => combined_ops.push(op),
246            }
247        }
248
249        self.ops
250            .meta
251            .extend(combined_ops.iter().map(|_| OpMeta { timestamp, base }));
252        self.ops.all.extend(combined_ops);
253    }
254
255    /// Loads a new string into the buffer, merging out-of-editor changes made since last load with in-editor changes
256    /// made since last load. The buffer's undo history is preserved; undo'ing will revert in-editor changes only.
257    /// Exercising undo's may put the buffer in never-before-seen states and exercising all undo's will revert the
258    /// buffer to the most recently loaded state (undo limit permitting).
259    /// Note: undo behavior described here is aspirational and not yet implemented.
260    pub fn reload(&mut self, text: String) {
261        let timestamp = Instant::now();
262        let base = self.external.seq;
263        let ops = diff(&self.external.text, &text);
264
265        self.ops
266            .meta
267            .extend(ops.iter().map(|_| OpMeta { timestamp, base }));
268        self.ops.all.extend(ops.into_iter().map(Operation::Replace));
269
270        self.external.text = text;
271        self.external.seq = self.base.seq + self.ops.all.len();
272    }
273
274    /// Indicates to the buffer the changes that have been saved outside the editor. This will serve as the new base
275    /// for merging external changes. The sequence number should be taken from `current.seq` of the buffer when the
276    /// buffer's contents are read for saving.
277    pub fn saved(&mut self, external_seq: usize, external_text: String) {
278        self.external.text = external_text;
279        self.external.seq = external_seq;
280    }
281
282    pub fn merge(mut self, external_text_a: String, external_text_b: String) -> String {
283        let ops_a = diff(&self.external.text, &external_text_a);
284        let ops_b = diff(&self.external.text, &external_text_b);
285
286        let timestamp = Instant::now();
287        let base = self.external.seq;
288        self.ops
289            .meta
290            .extend(ops_a.iter().map(|_| OpMeta { timestamp, base }));
291        self.ops
292            .meta
293            .extend(ops_b.iter().map(|_| OpMeta { timestamp, base }));
294
295        self.ops
296            .all
297            .extend(ops_a.into_iter().map(Operation::Replace));
298        self.ops
299            .all
300            .extend(ops_b.into_iter().map(Operation::Replace));
301
302        self.update();
303        self.current.text
304    }
305
306    /// Applies all operations in the buffer's input queue
307    pub fn update(&mut self) -> Response {
308        // clear redo stack
309        //             v base        v current    v processed
310        // ops before: |<- applied ->|<- undone ->|<- queued ->|
311        // ops after:  |<- applied ->|<- queued ->|
312        let queue_len = self.base.seq + self.ops.len() - self.ops.processed_seq;
313        if queue_len > 0 {
314            let drain_range = self.current.seq..self.ops.processed_seq;
315            self.ops.all.drain(drain_range.clone());
316            self.ops.meta.drain(drain_range.clone());
317            self.ops.transformed.drain(drain_range.clone());
318            self.ops.transformed_inverted.drain(drain_range.clone());
319            self.ops.processed_seq = self.current.seq;
320        } else {
321            return Response::default();
322        }
323
324        // transform & apply
325        let mut result = Response::default();
326        for idx in self.current_idx()..self.current_idx() + queue_len {
327            let mut op = self.ops.all[idx].clone();
328            let meta = &self.ops.meta[idx];
329            self.transform(&mut op, meta);
330            self.ops.transformed_inverted.push(self.current.invert(&op));
331            self.ops.transformed.push(op.clone());
332            self.ops.processed_seq += 1;
333
334            result |= self.redo();
335        }
336
337        result
338    }
339
340    fn transform(&self, op: &mut Operation, meta: &OpMeta) {
341        let base_idx = meta.base - self.base.seq;
342        for transforming_idx in base_idx..self.ops.processed_seq {
343            let preceding_op = &self.ops.transformed[transforming_idx];
344            if let Operation::Replace(Replace {
345                range: preceding_replaced_range,
346                text: preceding_replacement_text,
347            }) = preceding_op
348            {
349                if let Operation::Replace(Replace { range: transformed_range, text }) = op {
350                    if preceding_replaced_range.intersects(transformed_range, true)
351                        && !(preceding_replaced_range.is_empty() && transformed_range.is_empty())
352                    {
353                        // concurrent replacements to intersecting ranges choose the first/local edit as the winner
354                        // this doesn't create self-conflicts during merge because merge combines adjacent replacements
355                        // this doesn't create self-conflicts for same-frame editor changes because our final condition
356                        // is that we don't simultaneously insert text for both operations, which creates un-ideal
357                        // behavior (see test buffer_merge_insert)
358                        *text = "".into();
359                        transformed_range.1 = transformed_range.0;
360                    }
361                }
362
363                match op {
364                    Operation::Replace(Replace { range: transformed_range, .. })
365                    | Operation::Select(transformed_range) => {
366                        adjust_subsequent_range(
367                            *preceding_replaced_range,
368                            preceding_replacement_text.graphemes(true).count().into(),
369                            true,
370                            transformed_range,
371                        );
372                    }
373                }
374            }
375        }
376    }
377
378    pub fn can_redo(&self) -> bool {
379        self.current.seq < self.ops.processed_seq
380    }
381
382    pub fn can_undo(&self) -> bool {
383        self.current.seq > self.base.seq
384    }
385
386    pub fn redo(&mut self) -> Response {
387        let mut response = Response::default();
388        while self.can_redo() {
389            let op = &self.ops.transformed[self.current_idx()];
390
391            self.current.seq += 1;
392
393            response |= match op {
394                Operation::Replace(replace) => self.current.apply_replace(replace),
395                Operation::Select(range) => self.current.apply_select(*range),
396            };
397
398            if self.ops.is_undo_checkpoint(self.current_idx()) {
399                break;
400            }
401        }
402        response
403    }
404
405    pub fn undo(&mut self) -> Response {
406        let mut response = Response::default();
407        while self.can_undo() {
408            self.current.seq -= 1;
409            let op = &self.ops.transformed_inverted[self.current_idx()];
410
411            if let Some(replace) = &op.replace {
412                response |= self.current.apply_replace(replace);
413            }
414            response |= self.current.apply_select(op.select);
415
416            if self.ops.is_undo_checkpoint(self.current_idx()) {
417                break;
418            }
419        }
420        response
421    }
422
423    fn current_idx(&self) -> usize {
424        self.current.seq - self.base.seq
425    }
426
427    /// Reports whether the buffer's current text is empty.
428    pub fn is_empty(&self) -> bool {
429        self.current.text.is_empty()
430    }
431
432    pub fn selection_text(&self) -> String {
433        self[self.current.selection].to_string()
434    }
435}
436
437impl From<&str> for Buffer {
438    fn from(value: &str) -> Self {
439        let mut result = Self::default();
440        result.current.text = value.to_string();
441        result.current.segs = unicode_segs::calc(value);
442        result.external.text = value.to_string();
443        result
444    }
445}
446
447/// Adjust a range based on a text replacement. Positions before the replacement generally are not adjusted,
448/// positions after the replacement generally are, and positions within the replacement are adjusted to the end of
449/// the replacement if `prefer_advance` is true or are adjusted to the start of the replacement otherwise.
450pub fn adjust_subsequent_range(
451    replaced_range: (DocCharOffset, DocCharOffset), replacement_len: RelCharOffset,
452    prefer_advance: bool, range: &mut (DocCharOffset, DocCharOffset),
453) {
454    for position in [&mut range.0, &mut range.1] {
455        adjust_subsequent_position(replaced_range, replacement_len, prefer_advance, position);
456    }
457}
458
459/// Adjust a position based on a text replacement. Positions before the replacement generally are not adjusted,
460/// positions after the replacement generally are, and positions within the replacement are adjusted to the end of
461/// the replacement if `prefer_advance` is true or are adjusted to the start of the replacement otherwise.
462fn adjust_subsequent_position(
463    replaced_range: (DocCharOffset, DocCharOffset), replacement_len: RelCharOffset,
464    prefer_advance: bool, position: &mut DocCharOffset,
465) {
466    let replaced_len = replaced_range.len();
467    let replacement_start = replaced_range.start();
468    let replacement_end = replacement_start + replacement_len;
469
470    enum Mode {
471        Insert,
472        Replace,
473    }
474    let mode = if replaced_range.is_empty() { Mode::Insert } else { Mode::Replace };
475
476    let sorted_bounds = {
477        let mut bounds = vec![replaced_range.start(), replaced_range.end(), *position];
478        bounds.sort();
479        bounds
480    };
481    let bind = |start: &DocCharOffset, end: &DocCharOffset, pos: &DocCharOffset| {
482        start == &replaced_range.start() && end == &replaced_range.end() && pos == &*position
483    };
484
485    *position = match (mode, &sorted_bounds[..]) {
486        // case 1: position at point of text insertion
487        //                       text before replacement: * *
488        //                        range of replaced text:  |
489        //          range of subsequent cursor selection:  |
490        //                        text after replacement: * X *
491        // advance:
492        // adjusted range of subsequent cursor selection:    |
493        // don't advance:
494        // adjusted range of subsequent cursor selection:  |
495        (Mode::Insert, [start, end, pos]) if bind(start, end, pos) && end == pos => {
496            if prefer_advance {
497                replacement_end
498            } else {
499                replacement_start
500            }
501        }
502
503        // case 2: position at start of text replacement
504        //                       text before replacement: * * * *
505        //                        range of replaced text:  |<->|
506        //          range of subsequent cursor selection:  |
507        //                        text after replacement: * X *
508        // adjusted range of subsequent cursor selection:  |
509        (Mode::Replace, [start, pos, end]) if bind(start, end, pos) && start == pos => {
510            if prefer_advance {
511                replacement_end
512            } else {
513                replacement_start
514            }
515        }
516
517        // case 3: position at end of text replacement
518        //                       text before replacement: * * * *
519        //                        range of replaced text:  |<->|
520        //          range of subsequent cursor selection:      |
521        //                        text after replacement: * X *
522        // adjusted range of subsequent cursor selection:    |
523        (Mode::Replace, [start, end, pos]) if bind(start, end, pos) && end == pos => {
524            if prefer_advance {
525                replacement_end
526            } else {
527                replacement_start
528            }
529        }
530
531        // case 4: position before point/start of text insertion/replacement
532        //                       text before replacement: * * * * *
533        //       (possibly empty) range of replaced text:    |<->|
534        //          range of subsequent cursor selection:  |
535        //                        text after replacement: * * X *
536        // adjusted range of subsequent cursor selection:  |
537        (_, [pos, start, end]) if bind(start, end, pos) => *position,
538
539        // case 5: position within text replacement
540        //                       text before replacement: * * * *
541        //                        range of replaced text:  |<->|
542        //          range of subsequent cursor selection:    |
543        //                        text after replacement: * X *
544        // advance:
545        // adjusted range of subsequent cursor selection:    |
546        // don't advance:
547        // adjusted range of subsequent cursor selection:  |
548        (Mode::Replace, [start, pos, end]) if bind(start, end, pos) => {
549            if prefer_advance {
550                replacement_end
551            } else {
552                replacement_start
553            }
554        }
555
556        // case 6: position after point/end of text insertion/replacement
557        //                       text before replacement: * * * * *
558        //       (possibly empty) range of replaced text:  |<->|
559        //          range of subsequent cursor selection:        |
560        //                        text after replacement: * X * *
561        // adjusted range of subsequent cursor selection:      |
562        (_, [start, end, pos]) if bind(start, end, pos) => {
563            *position + replacement_len - replaced_len
564        }
565        _ => unreachable!(),
566    }
567}
568
569impl Index<(DocByteOffset, DocByteOffset)> for Snapshot {
570    type Output = str;
571
572    fn index(&self, index: (DocByteOffset, DocByteOffset)) -> &Self::Output {
573        &self.text[index.start().0..index.end().0]
574    }
575}
576
577impl Index<(DocCharOffset, DocCharOffset)> for Snapshot {
578    type Output = str;
579
580    fn index(&self, index: (DocCharOffset, DocCharOffset)) -> &Self::Output {
581        let index = self.segs.range_to_byte(index);
582        &self.text[index.start().0..index.end().0]
583    }
584}
585
586impl Index<(DocByteOffset, DocByteOffset)> for Buffer {
587    type Output = str;
588
589    fn index(&self, index: (DocByteOffset, DocByteOffset)) -> &Self::Output {
590        &self.current[index]
591    }
592}
593
594impl Index<(DocCharOffset, DocCharOffset)> for Buffer {
595    type Output = str;
596
597    fn index(&self, index: (DocCharOffset, DocCharOffset)) -> &Self::Output {
598        &self.current[index]
599    }
600}
601
602#[cfg(test)]
603mod test {
604    use super::Buffer;
605
606    #[test]
607    fn buffer_merge_nonintersecting_replace() {
608        let base_content = "base content base";
609        let local_content = "local content base";
610        let remote_content = "base content remote";
611
612        assert_eq!(
613            Buffer::from(base_content).merge(local_content.into(), remote_content.into()),
614            "local content remote"
615        );
616        assert_eq!(
617            Buffer::from(base_content).merge(remote_content.into(), local_content.into()),
618            "local content remote"
619        );
620    }
621
622    #[test]
623    fn buffer_merge_prefix_replace() {
624        let base_content = "base content";
625        let local_content = "local content";
626        let remote_content = "remote content";
627
628        assert_eq!(
629            Buffer::from(base_content).merge(local_content.into(), remote_content.into()),
630            "local content"
631        );
632    }
633
634    #[test]
635    fn buffer_merge_infix_replace() {
636        let base_content = "con base tent";
637        let local_content = "con local tent";
638        let remote_content = "con remote tent";
639
640        assert_eq!(
641            Buffer::from(base_content).merge(local_content.into(), remote_content.into()),
642            "con local tent"
643        );
644        assert_eq!(
645            Buffer::from(base_content).merge(remote_content.into(), local_content.into()),
646            "con remote tent"
647        );
648    }
649
650    #[test]
651    fn buffer_merge_postfix_replace() {
652        let base_content = "content base";
653        let local_content = "content local";
654        let remote_content = "content remote";
655
656        assert_eq!(
657            Buffer::from(base_content).merge(local_content.into(), remote_content.into()),
658            "content local"
659        );
660        assert_eq!(
661            Buffer::from(base_content).merge(remote_content.into(), local_content.into()),
662            "content remote"
663        );
664    }
665
666    #[test]
667    fn buffer_merge_insert() {
668        let base_content = "content";
669        let local_content = "content local";
670        let remote_content = "content remote";
671
672        assert_eq!(
673            Buffer::from(base_content).merge(local_content.into(), remote_content.into()),
674            "content local remote"
675        );
676        assert_eq!(
677            Buffer::from(base_content).merge(remote_content.into(), local_content.into()),
678            "content remote local"
679        );
680    }
681
682    #[test]
683    // this test case documents behavior moreso than asserting target state
684    fn buffer_merge_insert_replace() {
685        let base_content = "content";
686        let local_content = "content local";
687        let remote_content = "remote";
688
689        assert_eq!(
690            Buffer::from(base_content).merge(local_content.into(), remote_content.into()),
691            "content local"
692        );
693        assert_eq!(
694            Buffer::from(base_content).merge(remote_content.into(), local_content.into()),
695            "remote"
696        );
697    }
698
699    #[test]
700    // this test case used to crash `merge`
701    fn buffer_merge_crash() {
702        let base_content = "con tent";
703        let local_content = "cont tent locallocal";
704        let remote_content = "cont remote tent";
705
706        let _ = Buffer::from(base_content).merge(local_content.into(), remote_content.into());
707        let _ = Buffer::from(base_content).merge(remote_content.into(), local_content.into());
708    }
709}