any-rope 1.1.1

A fast and robust arbitrary rope for Rust. Based on Ropey.
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
use std::borrow::Borrow;
use std::fmt::{Debug, Display};
use std::ops::Deref;

use crate::max_children;
use crate::rope::Measurable;

use self::inner::LeafSmallVec;

use super::max_len;

/// A custom small string.  The unsafe guts of this are in [`LeafSmallVec`]
/// further down in this file.
#[derive(Clone, Default)]
#[repr(C)]
pub(crate) struct LeafSlice<M>(inner::LeafSmallVec<M>)
where
    M: Measurable,
    [(); max_len::<M>()]: Sized;

impl<M> LeafSlice<M>
where
    M: Measurable,
    [(); max_len::<M>()]: Sized,
    [(); max_children::<M>()]: Sized,
{
    /// Creates a new [`Leaf`] from a slice.
    pub fn from_slice(value: &[M]) -> Self {
        Self(LeafSmallVec::from_slice(value))
    }

    pub fn insert_slice(&mut self, index: usize, slice: &[M]) {
        self.0.insert_slice(index, slice);
    }

    /// Inserts a [`&[M]`][Measurable] at `index` and splits the resulting
    /// string in half, returning the right half.
    pub fn insert_slice_split(&mut self, split_index: usize, slice: &[M]) -> Self {
        let tot_len = self.len() + slice.len();
        let mid_index = tot_len / 2;

        self.0.insert_slice(split_index, slice);
        let right = LeafSlice::from_slice(&self[mid_index..]);
        self.truncate(mid_index);

        self.0.inline_if_possible();
        right
    }

    /// Appends a [`&[M]`][Measurable] to end the of the [`LeafSlice`].
    pub fn push_slice(&mut self, slice: &[M]) {
        let len = self.len();
        self.0.insert_slice(len, slice);
    }

    /// Appends a [`&[M]`][Measurable] and splits the resulting string in half,
    /// returning the right half.
    ///
    /// Only splits on code point boundaries and will never split CRLF pairs,
    /// so if the whole string is a single code point or CRLF pair, the split
    /// will fail and the returned string will be empty.
    pub fn push_slice_split(&mut self, slice: &[M]) -> Self {
        let len = self.len();
        self.insert_slice_split(len, slice)
    }

    /// Drops the text after `index`.
    pub fn truncate(&mut self, index: usize) {
        self.0.truncate(index);
        self.0.inline_if_possible();
    }

    /// Drops the text before `index`, shifting the
    /// rest of the text to fill in the space.
    pub fn truncate_front(&mut self, index: usize) {
        self.0.remove_range(0, index);
        self.0.inline_if_possible();
    }

    /// Removes the text in the index interval `[start_index, end_index)`.
    pub fn remove_range(&mut self, start_index: usize, end_index: usize) {
        self.0.remove_range(start_index, end_index);
        self.0.inline_if_possible();
    }

    /// Splits the [`LeafSlice`] at `index`.
    ///
    /// The left part remains in the original, and the right part is
    /// returned in a new [`LeafSlice`].
    pub fn split_off(&mut self, index: usize) -> Self {
        let other = LeafSlice(self.0.split_off(index));
        self.0.inline_if_possible();
        other
    }

    pub fn zero_width_end(&self) -> bool {
        self.0
            .as_slice()
            .last()
            .map(|measurable| measurable.width() == 0)
            .unwrap_or(false)
    }
}

impl<M> std::cmp::PartialEq for LeafSlice<M>
where
    M: Measurable + PartialEq,
    [(); max_len::<M>()]: Sized,
{
    fn eq(&self, other: &Self) -> bool {
        let (s1, s2): (&[M], &[M]) = (self, other);
        s1 == s2
    }
}

impl<'a, M> PartialEq<LeafSlice<M>> for &'a [M]
where
    M: Measurable + PartialEq,
    [(); max_len::<M>()]: Sized,
{
    fn eq(&self, other: &LeafSlice<M>) -> bool {
        *self == (other as &[M])
    }
}

impl<'a, M> PartialEq<&'a [M]> for LeafSlice<M>
where
    M: Measurable + PartialEq,
    [(); max_len::<M>()]: Sized,
{
    fn eq(&self, other: &&'a [M]) -> bool {
        (self as &[M]) == *other
    }
}

impl<M> std::fmt::Display for LeafSlice<M>
where
    M: Measurable + Display + Debug,
    [(); max_len::<M>()]: Sized,
{
    fn fmt(&self, fm: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        LeafSlice::deref(self).fmt(fm)
    }
}

impl<M> std::fmt::Debug for LeafSlice<M>
where
    M: Measurable + Debug,
    [(); max_len::<M>()]: Sized,
{
    fn fmt(&self, fm: &mut std::fmt::Formatter) -> std::fmt::Result {
        LeafSlice::deref(self).fmt(fm)
    }
}

impl<M> Deref for LeafSlice<M>
where
    M: Measurable,
    [(); max_len::<M>()]: Sized,
{
    type Target = [M];

    fn deref(&self) -> &[M] {
        self.0.as_slice()
    }
}

impl<M> AsRef<[M]> for LeafSlice<M>
where
    M: Measurable,
    [(); max_len::<M>()]: Sized,
{
    fn as_ref(&self) -> &[M] {
        self.0.as_slice()
    }
}

impl<M> Borrow<[M]> for LeafSlice<M>
where
    M: Measurable,
    [(); max_len::<M>()]: Sized,
{
    fn borrow(&self) -> &[M] {
        self.0.as_slice()
    }
}

//=======================================================================

/// The unsafe guts of NodeText, exposed through a safe API.
///
/// Try to keep this as small as possible, and implement functionality on
/// NodeText via the safe APIs whenever possible.
mod inner {
    use crate::tree::max_len;
    use smallvec::{Array, SmallVec};

    use super::Measurable;

    /// The backing internal buffer type for [`LeafSlice`][super::LeafSlice].
    #[derive(Copy, Clone)]
    struct BackingArray<M>([M; max_len::<M>()])
    where
        M: Measurable,
        [(); max_len::<M>()]: Sized;

    /// We need a very specific size of array, which is not necessarily
    /// supported directly by the impls in the smallvec crate.  We therefore
    /// have to implement this unsafe trait for our specific array size.
    /// TODO: once integer const generics land, and smallvec updates its APIs
    /// to use them, switch over and get rid of this unsafe impl.
    unsafe impl<M> Array for BackingArray<M>
    where
        M: Measurable,
        [(); max_len::<M>()]: Sized,
    {
        type Item = M;
        fn size() -> usize {
            max_len::<M>()
        }
    }

    /// Internal small string for [`LeafSlice`][super::LeafSlice].
    #[derive(Clone, Default)]
    #[repr(C)]
    pub struct LeafSmallVec<M>
    where
        M: Measurable,
        [(); max_len::<M>()]: Sized,
    {
        buffer: SmallVec<BackingArray<M>>,
    }

    impl<M> LeafSmallVec<M>
    where
        M: Measurable,
        [(); max_len::<M>()]: Sized,
    {
        #[inline(always)]
        pub fn with_capacity(capacity: usize) -> Self {
            LeafSmallVec {
                buffer: SmallVec::with_capacity(capacity),
            }
        }

        #[inline(always)]
        pub fn from_slice(slice: &[M]) -> Self {
            let mut leaf_small_vec = LeafSmallVec::with_capacity(slice.len());
            leaf_small_vec.insert_slice(0, slice);
            leaf_small_vec
        }

        #[inline(always)]
        pub fn len(&self) -> usize {
            self.buffer.len()
        }

        pub fn as_slice(&self) -> &[M] {
            &self.buffer
        }

        /// Inserts a [`&[M]`][Measurable] at `index`.
        #[inline(always)]
        pub fn insert_slice(&mut self, index: usize, slice: &[M]) {
            // Copy the `slice` into the appropriate space in the buffer.
            self.buffer.insert_from_slice(index, slice);
        }

        /// Removes text in range `[start_index, end_index)`
        #[inline(always)]
        pub fn remove_range(&mut self, start_index: usize, end_index: usize) {
            assert!(start_index <= end_index);
            // Already checked by copy_within/is_char_boundary.
            debug_assert!(end_index <= self.len());
            let len = self.len();
            let amt = end_index - start_index;

            self.buffer.copy_within(end_index..len, start_index);

            self.buffer.truncate(len - amt);
        }

        /// Removes text after `index`.
        #[inline(always)]
        pub fn truncate(&mut self, index: usize) {
            // Already checked by is_char_boundary.
            debug_assert!(index <= self.len());
            self.buffer.truncate(index);
        }

        /// Splits at `index`, returning the right part and leaving the
        /// left part in the original.
        #[inline(always)]
        pub fn split_off(&mut self, index: usize) -> Self {
            debug_assert!(index <= self.len());
            let len = self.len();
            let mut other = LeafSmallVec::with_capacity(len - index);
            other.buffer.extend_from_slice(&self.buffer[index..]);
            self.buffer.truncate(index);
            other
        }

        /// Re-inlines the data if it's been heap allocated but can fit inline.
        #[inline(always)]
        pub fn inline_if_possible(&mut self) {
            if self.buffer.spilled() && (self.buffer.len() <= self.buffer.inline_size()) {
                self.buffer.shrink_to_fit();
            }
        }
    }

    //-----------------------------------------------------------------------

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

        #[test]
        fn vec_basics() {
            let vec = LeafSmallVec::from_slice(&[Width(1), Width(2), Width(3), Width(0), Width(0)]);
            assert_eq!(vec.as_slice(), &[
                Width(1),
                Width(2),
                Width(3),
                Width(0),
                Width(0)
            ]);
            assert_eq!(5, vec.len());
        }

        #[test]
        fn insert_slice_01() {
            let mut vec = LeafSmallVec::from_slice(&[Width(1), Width(2)]);
            vec.insert_slice(2, &[Width(5), Width(0), Width(0)]);
            assert_eq!(vec.as_slice(), &[
                Width(1),
                Width(2),
                Width(5),
                Width(0),
                Width(0)
            ]);
        }

        #[test]
        #[should_panic]
        fn insert_slice_02() {
            let mut vec = LeafSmallVec::from_slice(&[Width(2), Width(0)]);
            vec.insert_slice(3, &[Width(1)]);
        }

        #[test]
        fn remove_range_01() {
            let mut vec =
                LeafSmallVec::from_slice(&[Width(1), Width(2), Width(1), Width(0), Width(0)]);
            vec.remove_range(2, 3);
            assert_eq!(vec.as_slice(), &[Width(1), Width(2), Width(0), Width(0)]);
        }

        #[test]
        #[should_panic]
        fn remove_range_02() {
            let mut vec = LeafSmallVec::from_slice(&[Width(5), Width(0), Width(0), Width(2)]);
            vec.remove_range(4, 2);
        }

        #[test]
        #[should_panic]
        fn remove_range_03() {
            let mut vec = LeafSmallVec::from_slice(&[Width(5), Width(0), Width(0), Width(2)]);
            vec.remove_range(2, 7);
        }

        #[test]
        fn truncate_01() {
            let mut vec = LeafSmallVec::from_slice(&[Width(3), Width(0), Width(0), Width(4)]);
            vec.truncate(3);
            assert_eq!(vec.as_slice(), &[Width(3), Width(0), Width(0)]);
        }

        #[test]
        #[should_panic]
        fn truncate_02() {
            let mut vec = LeafSmallVec::from_slice(&[Width(6)]);
            vec.truncate(7);
        }

        #[test]
        fn split_off_01() {
            let mut vec_1 = LeafSmallVec::from_slice(&[Width(1), Width(3), Width(0), Width(0)]);
            let vec_2 = vec_1.split_off(2);
            assert_eq!(vec_1.as_slice(), &[Width(1), Width(3)]);
            assert_eq!(vec_2.as_slice(), &[Width(0), Width(0)]);
        }

        #[test]
        #[should_panic]
        fn split_off_02() {
            let mut s1 =
                LeafSmallVec::from_slice(&[Width(1), Width(2), Width(3), Width(0), Width(0)]);
            s1.split_off(7);
        }
    }
}