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
use std::{
    borrow::Borrow,
    cmp::Ordering,
    fmt,
    hash::{Hash, Hasher},
    iter::{Skip, Take},
    ops::{Bound, Deref, RangeBounds},
    ptr,
};

macro_rules! cowslice {
    ($($item:expr),* $(,)?) => {
        $crate::cowslice::CowSlice::from([$($item),*])
    };
    ($item:expr; $len:expr) => {{
        let len = $len;
        let mut cs = $crate::cowslice::CowSlice::with_capacity(len);
        cs.extend(std::iter::repeat($item).take(len));
        cs
    }}
}

pub(crate) use cowslice;
use ecow::EcoVec;

pub struct CowSlice<T> {
    data: EcoVec<T>,
    start: usize,
    end: usize,
}

impl<T> CowSlice<T> {
    pub fn new() -> Self {
        Self::default()
    }
    pub fn truncate(&mut self, len: usize) {
        self.end = (self.start + len).min(self.end);
    }
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            data: EcoVec::with_capacity(capacity),
            start: 0,
            end: 0,
        }
    }
    pub fn as_slice(&self) -> &[T] {
        &self.data[self.start..self.end]
    }
    #[inline]
    pub fn is_unique(&mut self) -> bool {
        self.data.is_unique()
    }
    pub fn is_copy_of(&self, other: &Self) -> bool {
        ptr::eq(self.data.as_ptr(), other.data.as_ptr())
            && self.start == other.start
            && self.end == other.end
    }
}

impl<T: Clone> CowSlice<T> {
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        if !self.data.is_unique() {
            let mut new_data = EcoVec::with_capacity(self.len());
            new_data.extend_from_slice(&*self);
            self.data = new_data;
            self.start = 0;
            self.end = self.data.len();
        }
        &mut self.data.make_mut()[self.start..self.end]
    }
    pub fn extend_from_slice(&mut self, other: &[T]) {
        self.modify(|vec| vec.extend_from_slice(other))
    }
    pub fn try_extend<E>(&mut self, iter: impl IntoIterator<Item = Result<T, E>>) -> Result<(), E> {
        self.modify(|vec| {
            for item in iter {
                vec.push(item?);
            }
            Ok(())
        })
    }
    #[track_caller]
    pub fn slice<R>(&self, range: R) -> Self
    where
        R: RangeBounds<usize>,
    {
        let start = match range.start_bound() {
            Bound::Included(&start) => self.start + start,
            Bound::Excluded(&start) => self.start + start + 1,
            Bound::Unbounded => self.start,
        };
        let end = match range.end_bound() {
            Bound::Included(&end) => self.start + end + 1,
            Bound::Excluded(&end) => self.start + end,
            Bound::Unbounded => self.end,
        };
        assert!(start <= end);
        assert!(end <= self.end);
        Self {
            data: self.data.clone(),
            start,
            end,
        }
    }
    pub fn into_slices(
        self,
        size: usize,
    ) -> impl ExactSizeIterator<Item = Self> + DoubleEndedIterator {
        assert!(self.len() % size == 0);
        (0..self.len() / size).map(move |i| {
            let start = self.start + (i * size);
            Self {
                data: self.data.clone(),
                start,
                end: start + size,
            }
        })
    }
    pub fn modify<F, R>(&mut self, f: F) -> R
    where
        F: FnOnce(&mut EcoVec<T>) -> R,
    {
        if self.data.is_unique() && self.start == 0 && self.end == self.data.len() {
            let res = f(&mut self.data);
            self.end = self.data.len();
            res
        } else {
            let mut vec = EcoVec::from(&**self);
            let res = f(&mut vec);
            *self = vec.into();
            res
        }
    }
    /// Ensure that the capacity is at least `min`
    pub fn reserve_min(&mut self, min: usize) {
        if self.data.capacity() < min {
            self.modify(|vec| vec.reserve(vec.capacity().max(min) - vec.len()))
        }
    }
    pub fn split_off(&mut self, at: usize) -> Self {
        assert!(at <= self.len());
        let mut other = Self::with_capacity(self.len() - at);
        other.extend_from_slice(&self[at..]);
        self.truncate(at);
        other
    }
}

#[test]
fn cow_slice_modify() {
    let mut slice = CowSlice::from([1, 2, 3]);
    slice.modify(|vec| vec.push(4));
    assert_eq!(slice, [1, 2, 3, 4]);

    let mut sub = slice.slice(1..=2);
    sub.modify(|vec| vec.push(5));
    assert_eq!(slice, [1, 2, 3, 4]);
    assert_eq!(sub, [2, 3, 5]);
}

impl<T> Default for CowSlice<T> {
    fn default() -> Self {
        Self {
            data: EcoVec::new(),
            start: 0,
            end: 0,
        }
    }
}

impl<T: Clone> Clone for CowSlice<T> {
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            start: self.start,
            end: self.end,
        }
    }
}

impl<T> Deref for CowSlice<T> {
    type Target = [T];
    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

#[test]
fn cow_slice_deref_mut() {
    let mut slice = CowSlice::from([1, 2, 3, 4]);
    slice.as_mut_slice()[1] = 7;
    assert_eq!(slice, [1, 7, 3, 4]);

    let mut sub = slice.slice(1..=2);
    sub.as_mut_slice()[1] = 5;
    assert_eq!(slice, [1, 7, 3, 4]);
    assert_eq!(sub, [7, 5]);
}

impl<T: Clone> From<CowSlice<T>> for Vec<T> {
    fn from(mut slice: CowSlice<T>) -> Self {
        if slice.data.is_unique() && slice.start == 0 && slice.end == slice.data.len() {
            slice.data.into_iter().collect()
        } else {
            slice.to_vec()
        }
    }
}

impl<T: Clone> From<EcoVec<T>> for CowSlice<T> {
    fn from(data: EcoVec<T>) -> Self {
        Self {
            start: 0,
            end: data.len(),
            data,
        }
    }
}

impl<'a, T: Clone> From<&'a [T]> for CowSlice<T> {
    fn from(slice: &'a [T]) -> Self {
        Self {
            start: 0,
            end: slice.len(),
            data: slice.into(),
        }
    }
}

impl<T: Clone, const N: usize> From<[T; N]> for CowSlice<T> {
    fn from(array: [T; N]) -> Self {
        Self {
            start: 0,
            end: N,
            data: array.into(),
        }
    }
}

impl<T: fmt::Debug> fmt::Debug for CowSlice<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        (**self).fmt(f)
    }
}

impl<T> Borrow<[T]> for CowSlice<T> {
    fn borrow(&self) -> &[T] {
        self
    }
}

impl<T> AsRef<[T]> for CowSlice<T> {
    fn as_ref(&self) -> &[T] {
        self
    }
}

impl<T: PartialEq> PartialEq for CowSlice<T> {
    fn eq(&self, other: &Self) -> bool {
        **self == **other
    }
}

impl<T: Eq> Eq for CowSlice<T> {}

impl<T: PartialOrd> PartialOrd for CowSlice<T> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        (**self).partial_cmp(&**other)
    }
}

impl<T: Ord> Ord for CowSlice<T> {
    fn cmp(&self, other: &Self) -> Ordering {
        (**self).cmp(&**other)
    }
}

impl<T: PartialEq> PartialEq<[T]> for CowSlice<T> {
    fn eq(&self, other: &[T]) -> bool {
        **self == *other
    }
}

impl<T: PartialEq> PartialEq<Vec<T>> for CowSlice<T> {
    fn eq(&self, other: &Vec<T>) -> bool {
        **self == *other
    }
}

impl<T: PartialEq, const N: usize> PartialEq<[T; N]> for CowSlice<T> {
    fn eq(&self, other: &[T; N]) -> bool {
        **self == *other
    }
}

impl<T: Hash> Hash for CowSlice<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        (**self).hash(state)
    }
}

impl<T: Clone> IntoIterator for CowSlice<T> {
    type Item = T;
    type IntoIter = Take<Skip<<EcoVec<T> as IntoIterator>::IntoIter>>;
    fn into_iter(self) -> Self::IntoIter {
        self.data
            .into_iter()
            .skip(self.start)
            .take(self.end - self.start)
    }
}

impl<'a, T> IntoIterator for &'a CowSlice<T> {
    type Item = &'a T;
    type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, T: Clone> IntoIterator for &'a mut CowSlice<T> {
    type Item = &'a mut T;
    type IntoIter = <&'a mut [T] as IntoIterator>::IntoIter;
    fn into_iter(self) -> Self::IntoIter {
        self.as_mut_slice().iter_mut()
    }
}

impl<T: Clone> FromIterator<T> for CowSlice<T> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let mut data = EcoVec::new();
        data.extend(iter);
        data.into()
    }
}

impl<T: Clone> Extend<T> for CowSlice<T> {
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        self.modify(|vec| vec.extend(iter))
    }
}