turbocow 0.3.0-beta.2

Compact, clone-on-write vectors, strings, maps and sets with inline + referenced storage — a superset of ecow.
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
use alloc::vec::Vec;
use core::borrow::Borrow;
use core::cmp::Ordering;
use core::hash::{Hash, Hasher};
use core::ops::Deref;
use core::ptr;

use super::types::EcoVec;
use crate::allocator::{AllocatorProvider, Global};

// ── Access ──────────────────────────────────────────────────────────────

impl<T, A> Deref for EcoVec<T, A>
where
    A: AllocatorProvider,
{
    type Target = [T];

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

impl<T, A> Borrow<[T]> for EcoVec<T, A>
where
    A: AllocatorProvider,
{
    #[inline]
    fn borrow(&self) -> &[T] {
        self.as_slice()
    }
}

impl<T, A> AsRef<[T]> for EcoVec<T, A>
where
    A: AllocatorProvider,
{
    #[inline]
    fn as_ref(&self) -> &[T] {
        self.as_slice()
    }
}

// ── Comparison ──────────────────────────────────────────────────────────

impl<T, A> Hash for EcoVec<T, A>
where
    T: Hash,
    A: AllocatorProvider,
{
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_slice().hash(state);
    }
}

impl<T, A> Eq for EcoVec<T, A>
where
    T: Eq,
    A: AllocatorProvider,
{
}

impl<T, A> PartialEq for EcoVec<T, A>
where
    T: PartialEq,
    A: AllocatorProvider,
{
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        // Fast-path: two clones sharing the same backing allocation are
        // trivially equal (same data pointer and same length).
        (self.ptr == other.ptr && self.len == other.len)
            || self.as_slice() == other.as_slice()
    }
}

impl<T, A> PartialEq<[T]> for EcoVec<T, A>
where
    T: PartialEq,
    A: AllocatorProvider,
{
    #[inline]
    fn eq(&self, other: &[T]) -> bool {
        self.as_slice() == other
    }
}

impl<T, A> PartialEq<&[T]> for EcoVec<T, A>
where
    T: PartialEq,
    A: AllocatorProvider,
{
    #[inline]
    fn eq(&self, other: &&[T]) -> bool {
        self.as_slice() == *other
    }
}

impl<T, A, const N: usize> PartialEq<[T; N]> for EcoVec<T, A>
where
    T: PartialEq,
    A: AllocatorProvider,
{
    #[inline]
    fn eq(&self, other: &[T; N]) -> bool {
        self.as_slice() == other
    }
}

impl<T, A, const N: usize> PartialEq<&[T; N]> for EcoVec<T, A>
where
    T: PartialEq,
    A: AllocatorProvider,
{
    #[inline]
    fn eq(&self, other: &&[T; N]) -> bool {
        self.as_slice() == *other
    }
}

impl<T, A> PartialEq<EcoVec<T, A>> for [T]
where
    T: PartialEq,
    A: AllocatorProvider,
{
    #[inline]
    fn eq(&self, other: &EcoVec<T, A>) -> bool {
        self == other.as_slice()
    }
}

impl<T, A, const N: usize> PartialEq<EcoVec<T, A>> for [T; N]
where
    T: PartialEq,
    A: AllocatorProvider,
{
    #[inline]
    fn eq(&self, other: &EcoVec<T, A>) -> bool {
        self == other.as_slice()
    }
}

impl<T, A> PartialEq<Vec<T>> for EcoVec<T, A>
where
    T: PartialEq,
    A: AllocatorProvider,
{
    #[inline]
    fn eq(&self, other: &Vec<T>) -> bool {
        self.as_slice() == other.as_slice()
    }
}

impl<T, A> PartialEq<EcoVec<T, A>> for Vec<T>
where
    T: PartialEq,
    A: AllocatorProvider,
{
    #[inline]
    fn eq(&self, other: &EcoVec<T, A>) -> bool {
        self.as_slice() == other.as_slice()
    }
}

impl<T, A> Ord for EcoVec<T, A>
where
    T: Ord,
    A: AllocatorProvider,
{
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        self.as_slice().cmp(other.as_slice())
    }
}

impl<T, A> PartialOrd for EcoVec<T, A>
where
    T: PartialOrd,
    A: AllocatorProvider,
{
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.as_slice().partial_cmp(other.as_slice())
    }
}

// ── Construction ────────────────────────────────────────────────────────

impl<T> Default for EcoVec<T, Global> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<T> From<&[T]> for EcoVec<T, Global>
where
    T: Clone,
{
    fn from(slice: &[T]) -> Self {
        let mut vec = Self::with_capacity(slice.len());
        vec.extend_from_slice(slice);
        vec
    }
}

impl<T, const N: usize> From<[T; N]> for EcoVec<T, Global>
where
    T: Clone,
{
    fn from(array: [T; N]) -> Self {
        let mut vec = Self::with_capacity(N);
        unsafe {
            // Safety: Array's IntoIter implements `TrustedLen`.
            vec.extend_from_trusted(array);
        }
        vec
    }
}

impl<T> From<Vec<T>> for EcoVec<T, Global>
where
    T: Clone,
{
    /// Allocates a new EcoVec, and moves other's items into it.
    fn from(mut other: Vec<T>) -> Self {
        let len = other.len();
        let mut vec = Self::with_capacity(len);
        unsafe {
            // Disables dropping of individual `Vec` items that will be moved
            // into the `EcoVec`.
            //
            // Safety: 0 is less than or equal to capacity.
            other.set_len(0);

            // Safety:
            // - The source vector is valid for `len` reads.
            // - The destination is valid for `len` writes due to the
            //   `Self::with_capacity(len)` call.
            // - The source and destination are non-overlapping because we just
            //   allocated the destination.
            core::ptr::copy_nonoverlapping(other.as_ptr(), vec.data_mut(), len);

            // Sets the correct length, and thereby also enables dropping of the
            // individual items that have been moved into the `EcoVec`.
            // There is no possibility of double dropping because we've already
            // set the length of the original `Vec` to 0 before copying.
            vec.len = len;
        }
        vec
    }
}

impl<T, A, const N: usize> TryFrom<EcoVec<T, A>> for [T; N]
where
    T: Clone,
    A: AllocatorProvider,
{
    type Error = EcoVec<T, A>;

    fn try_from(mut vec: EcoVec<T, A>) -> Result<Self, Self::Error> {
        if vec.len() != N {
            return Err(vec);
        }

        Ok(if vec.is_unique() {
            // Set the length to zero to prevent double drop.
            vec.len = 0;

            // Safety: We have unique ownership and len == N.
            unsafe { ptr::read(vec.data() as *const [T; N]) }
        } else {
            // Safety: We know that the length is correct.
            unsafe { core::array::from_fn(|i| vec.get_unchecked(i).clone()) }
        })
    }
}

// ── Iteration ───────────────────────────────────────────────────────────

impl<T, A> Extend<T> for EcoVec<T, A>
where
    T: Clone,
    A: AllocatorProvider + Clone,
{
    fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = T>,
    {
        let iter = iter.into_iter();
        let hint = iter.size_hint().0;
        if hint > 0 {
            self.reserve(hint);
        }
        // After reserve, we're unique and may have spare capacity.
        // Use push_unchecked while capacity allows, then fall back to
        // push (which re-checks unique + grows) only when needed.
        for value in iter {
            if self.len < self.capacity() && self.is_unique() {
                unsafe { self.push_unchecked(value) };
            } else {
                self.push(value);
            }
        }
    }
}

impl<T> FromIterator<T> for EcoVec<T, Global>
where
    T: Clone,
{
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let iter = iter.into_iter();
        let hint = iter.size_hint().0;
        let mut vec = Self::with_capacity(hint);
        vec.extend(iter);
        vec
    }
}

impl<'a, T, A> IntoIterator for &'a EcoVec<T, A>
where
    A: AllocatorProvider,
{
    type IntoIter = core::slice::Iter<'a, T>;
    type Item = &'a T;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.as_slice().iter()
    }
}

impl<T, A> IntoIterator for EcoVec<T, A>
where
    T: Clone,
    A: AllocatorProvider,
{
    type IntoIter = IntoIter<T, A>;
    type Item = T;

    #[inline]
    fn into_iter(mut self) -> Self::IntoIter {
        IntoIter {
            unique: self.is_unique(),
            front: 0,
            back: self.len,
            vec: self,
        }
    }
}

/// An owned iterator over an [`EcoVec`].
///
/// If the vector had a reference count of 1, this moves out of the vector,
/// otherwise it lazily clones.
///
/// The second type parameter defaults to [`Global`] so that
/// `turbocow::vec::IntoIter<T>` resolves without an explicit allocator,
/// matching ecow's single-parameter `ecow::vec::IntoIter<T>`.
pub struct IntoIter<T, A = Global>
where
    A: AllocatorProvider,
{
    vec: EcoVec<T, A>,
    unique: bool,
    front: usize,
    back: usize,
}

impl<T, A> IntoIter<T, A>
where
    A: AllocatorProvider,
{
    /// Returns the remaining items of this iterator as a slice.
    #[inline]
    pub fn as_slice(&self) -> &[T] {
        unsafe {
            core::slice::from_raw_parts(
                self.vec.data().add(self.front),
                self.back - self.front,
            )
        }
    }
}

impl<T, A> Iterator for IntoIter<T, A>
where
    T: Clone,
    A: AllocatorProvider,
{
    type Item = T;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        (self.front < self.back).then(|| {
            let prev = self.front;
            self.front += 1;
            if self.unique {
                unsafe { ptr::read(self.vec.data().add(prev)) }
            } else {
                unsafe { self.vec.get_unchecked(prev).clone() }
            }
        })
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.back - self.front;
        (len, Some(len))
    }

    #[inline]
    fn count(self) -> usize {
        self.len()
    }
}

impl<T, A> DoubleEndedIterator for IntoIter<T, A>
where
    T: Clone,
    A: AllocatorProvider,
{
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        (self.back > self.front).then(|| {
            self.back -= 1;
            if self.unique {
                unsafe { ptr::read(self.vec.data().add(self.back)) }
            } else {
                unsafe { self.vec.get_unchecked(self.back).clone() }
            }
        })
    }
}

impl<T, A> ExactSizeIterator for IntoIter<T, A>
where
    T: Clone,
    A: AllocatorProvider,
{
}

impl<T, A> Drop for IntoIter<T, A>
where
    A: AllocatorProvider,
{
    fn drop(&mut self) {
        if !self.unique || !self.vec.is_allocated() {
            return;
        }

        unsafe {
            // Set len to zero before dropping to prevent double dropping in
            // EcoVec's drop impl in case of panic.
            self.vec.len = 0;

            // Drop only the remaining elements in the middle.
            ptr::drop_in_place(ptr::slice_from_raw_parts_mut(
                self.vec.data_mut().add(self.front),
                self.back - self.front,
            ));
        }
    }
}

impl<T, A> core::fmt::Debug for IntoIter<T, A>
where
    T: core::fmt::Debug,
    A: AllocatorProvider,
{
    #[inline]
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
    }
}