cev/
cev.rs

1#![allow(clippy::partialeq_ne_impl)]
2use crate::raw_cev::RawCev;
3use core::borrow::{Borrow, BorrowMut};
4use core::cmp::Ordering;
5use core::fmt;
6use core::mem::{self, ManuallyDrop, MaybeUninit};
7use core::ops::{self, Index, IndexMut};
8use core::ptr::{self, NonNull};
9use core::slice::{self, SliceIndex};
10
11/// An array of data allocated on the heap that grows from end to beginning.
12///
13/// # Examples
14///
15/// ```
16/// use cev::Cev;
17///
18/// let mut cev = Cev::new();
19/// cev.push('v');
20/// cev.push('e');
21/// cev.push('c');
22///
23/// assert_eq!(cev, ['c', 'e', 'v']);
24///
25/// ```
26pub struct Cev<T> {
27    buf: RawCev<T>,
28    len: usize,
29}
30
31impl<T> Cev<T> {
32    /// Adds elements to the beginning of the `Cev` array, moving them from another `Cev` array,
33    /// leaving the other empty to reuse the allocated memory.
34    ///
35    /// # Examples
36    ///
37    /// ```
38    /// use cev::Cev;
39    ///
40    /// let mut cev = Cev::from([4, 5, 6]);
41    /// let mut cev_other = Cev::from([1, 2, 3]);
42    /// cev.append(&mut cev_other);
43    /// assert_eq!(cev, [1, 2, 3, 4, 5, 6]);
44    /// assert_eq!(cev_other, []);
45    /// ```
46    #[inline]
47    pub fn append(&mut self, other: &mut Self) {
48        unsafe {
49            self.append_elements(other.as_slice() as _);
50            other.set_len_ptr(0);
51        }
52    }
53
54    /// Returns an unsafe mutable pointer.
55    /// If length is zero, then points to capacity minus 1 element of type `T`,
56    /// otherwise capacity minus length.
57    /// For unallocated array `Cev` and types of size zero, a `NonNull` dangling pointer is returned.
58    ///
59    /// # Examples
60    ///
61    /// ```
62    /// use::cev::Cev;
63    ///
64    /// let len = 5;
65    /// let mut cev = Cev::<u8>::with_capacity(len);
66    /// let mov_ptr = cev.as_mut_ptr();
67    ///
68    /// unsafe {
69    ///     for elem in 0..len {
70    ///         *mov_ptr.sub(elem) = elem as u8;
71    ///     }
72    ///     cev.set_len_ptr(len);
73    /// }
74    ///
75    /// // The `mov_ptr` pointer points to the element at index 4.
76    /// assert_eq!(unsafe { *mov_ptr }, 0);
77    /// assert_eq!(cev, [4, 3, 2, 1, 0]);
78    /// ```
79    #[inline]
80    pub fn as_mut_ptr(&mut self) -> *mut T {
81        self.buf.ptr()
82    }
83
84    /// A mutable slice from this `Cev` array.
85    #[inline]
86    pub fn as_mut_slice(&mut self) -> &mut [T] {
87        self
88    }
89
90    /// Returns an unsafe constant pointer.
91    /// If length is zero, then points to capacity minus 1 element of type `T`,
92    /// otherwise capacity minus length.
93    /// For unallocated array `Cev` and types of size zero, a `NonNull` dangling pointer is returned.
94    ///
95    /// # Examples
96    ///
97    /// ```
98    /// use::cev::Cev;
99    ///
100    /// let mut cev = Cev::<u8>::from_vec(vec![2, 4, 6, 8, 10]);
101    /// let len = cev.len();
102    /// let mov_ptr = cev.as_mut_ptr();
103    ///
104    /// unsafe {
105    ///     for index in 0..len {
106    ///         
107    ///         assert_eq!(unsafe { *mov_ptr.add(index) }, cev[index]);
108    ///     }
109    /// }
110    ///
111    /// ```
112    #[inline]
113    pub fn as_ptr(&self) -> *const T {
114        self.buf.ptr()
115    }
116
117    /// A constant slice from this `Cev` array.
118    #[inline]
119    pub fn as_slice(&self) -> &[T] {
120        self
121    }
122
123    /// Returns the capacity of this `Cev` array.
124    ///
125    /// # Examples
126    ///
127    /// ```
128    /// use cev::Cev;
129    ///
130    /// let cev = Cev::<String>::with_capacity(0);
131    /// assert_eq!(cev.capacity(), 0);
132    ///
133    /// let cev = Cev::<String>::with_capacity(1);
134    /// assert_eq!(cev.capacity(), 1);
135    ///
136    /// let cev = Cev::<()>::with_capacity(0);
137    /// assert_eq!(cev.capacity(), usize::MAX);
138    /// ```
139    #[inline]
140    pub fn capacity(&self) -> usize {
141        self.buf.capacity()
142    }
143
144    /// Clears the `Cev` array, removing all elements.
145    ///
146    /// # Examples
147    ///
148    /// ```
149    /// use cev::Cev;
150    ///
151    /// let mut cev: Cev<&str> = Cev::from(["c", "l", "e", "a", "r"]);
152    /// cev.clear();
153    /// assert!(cev.is_empty());
154    ///
155    /// cev.append(&mut Cev::from_vec(vec!["r", "e", "u", "s", "e"]));
156    /// assert_eq!(cev, Cev::from_vec(vec!["r", "e", "u", "s", "e"]));
157    /// ```
158    #[inline]
159    pub fn clear(&mut self) {
160        let elems: *mut [T] = self.as_mut_slice();
161
162        unsafe {
163            self.set_len_ptr(0);
164            ptr::drop_in_place(elems);
165        }
166    }
167
168    /// Creates a `Cev<T>` directly from a pointers, a capacity, and a length.
169    #[inline]
170    pub unsafe fn from_raw_parts(mov_ptr: *mut T, raw_ptr: *mut T, len: usize, cap: usize) -> Self {
171        unsafe {
172            Cev {
173                buf: RawCev::from_raw_parts_ptr(mov_ptr, raw_ptr, cap),
174                len,
175            }
176        }
177    }
178
179    /// Converting a std vector to a `Cev` array.
180    /// When length and capacity are equal, data copying is not required.
181    /// If the capacity is larger, the data is copied to the end of the array.
182    /// In both cases the same memory is reused.
183    ///
184    /// # Examples
185    ///
186    /// ```
187    /// use cev::Cev;
188    ///
189    /// let vec = vec!["std", "vector"];
190    /// let cev = Cev::from_vec(vec);
191    /// assert_eq!(cev, ["std", "vector"]);
192    /// ```
193    #[inline]
194    pub fn from_vec(mut vec: Vec<T>) -> Self {
195        let (raw_ptr, len, capacity) = (vec.as_mut_ptr(), vec.len(), vec.capacity());
196        unsafe {
197            vec.set_len(0);
198            mem::forget(vec);
199
200            Cev::from_raw_parts(
201                if capacity == len {
202                    raw_ptr
203                } else if len == 0 {
204                    raw_ptr.add(capacity - 1)
205                } else {
206                    let mov_ptr = raw_ptr.add(capacity - len);
207                    ptr::copy(raw_ptr, mov_ptr, len);
208                    mov_ptr
209                },
210                raw_ptr,
211                len,
212                capacity,
213            )
214        }
215    }
216
217    /// Inserts an element at position `index` within the `Cev` array, shifting all
218    /// elements before it to the left.
219    ///
220    /// # Panics
221    ///
222    /// Panics if `index > len`.
223    ///
224    /// # Examples
225    ///
226    /// ```
227    /// use cev::Cev;
228    ///
229    /// let mut cev = Cev::from([2, 2, 3]);
230    /// cev.insert(1, 0);
231    /// assert_eq!(cev, [2, 0, 2, 3]);
232    /// cev.insert(4, 8);
233    /// assert_eq!(cev, [2, 0, 2, 3, 8]);
234    /// ```
235    pub fn insert(&mut self, index: usize, element: T) {
236        #[cold]
237        #[inline(never)]
238        fn assert_failed(index: usize, len: usize) -> ! {
239            panic!("insertion index (is {index}) should be <= len (is {len})");
240        }
241
242        let len = self.len();
243
244        if len == self.buf.capacity() {
245            self.reserve(1);
246        }
247
248        unsafe {
249            if index == 0 {
250                if len != 0 {
251                    self.buf.mov_ptr_sub(1)
252                }
253            } else if index <= len {
254                let p = self.as_mut_ptr();
255                ptr::copy(p, p.sub(1), index);
256                self.buf.mov_ptr_sub(1)
257            } else {
258                assert_failed(index, len);
259            }
260
261            ptr::write(self.as_mut_ptr().add(index), element);
262            self.set_len(len + 1);
263        }
264    }
265
266    /// Converting a `Cev` array to a `std` vector.
267    /// When length and capacity are equal, data copying is not required.
268    /// If the capacity is larger, the data is copied to the begining of the array.
269    /// In both cases the same memory is reused.
270    ///
271    /// # Examples
272    ///
273    /// ```
274    /// use cev::Cev;
275    ///
276    /// let cev = Cev::from_vec(vec!["std", "vector"]);
277    /// let vec = cev.into_vec();
278    /// assert_eq!(vec, ["std", "vector"]);
279    /// ```
280    #[inline]
281    pub fn into_vec(self) -> Vec<T> {
282        let (ptr, len, capacity) = (self.buf.raw_ptr(), self.len(), self.capacity());
283        unsafe {
284            if capacity != len {
285                ptr::copy(self.as_ptr(), ptr, len);
286            }
287
288            mem::forget(self);
289            Vec::from_raw_parts(ptr, len, capacity)
290        }
291    }
292
293    /// Returns `true` if the `Cev` array contains no elements.
294    ///
295    /// # Examples
296    ///
297    /// ```
298    /// use cev::Cev;
299    ///
300    /// let mut cev = Cev::new();
301    /// assert!(cev.is_empty());
302    ///
303    /// cev.push("push one element");
304    /// assert!(!cev.is_empty());
305    /// ```
306    pub fn is_empty(&self) -> bool {
307        self.len() == 0
308    }
309
310    /// `Cev` array length, the number of elements in the array.
311    ///
312    /// # Examples
313    ///
314    /// ```
315    /// use cev::Cev;
316    ///
317    /// let cev = Cev::from([1, 2, 3]);
318    /// assert_eq!(cev.len(), 3);
319    /// ```
320    #[inline]
321    pub fn len(&self) -> usize {
322        self.len
323    }
324
325    /// Creates a new, empty `Cev<T>`.
326    ///
327    /// # Examples
328    ///
329    /// ```
330    /// use cev::Cev;
331    ///
332    /// let cev: Cev<i64> = Cev::new();
333    /// ```
334    #[inline]
335    pub const fn new() -> Self {
336        Cev {
337            buf: RawCev::NEW,
338            len: 0,
339        }
340    }
341
342    /// Removes the first element from a collection and returns it, or None if it is empty.
343    ///
344    /// # Examples
345    ///
346    /// ```
347    /// use cev::Cev;
348    ///
349    /// let mut cev = Cev::from([1, 9, 7, 5]);
350    /// assert_eq!(cev.pop(), Some(1));
351    /// assert_eq!(cev, [9, 7, 5]);
352    /// assert_eq!(cev.pop(), Some(9));
353    /// assert_eq!(cev.pop(), Some(7));
354    /// assert_eq!(cev.pop(), Some(5));
355    /// assert_eq!(cev.pop(), None);
356    /// ```
357    #[inline]
358    pub fn pop(&mut self) -> Option<T> {
359        if self.len == 0 {
360            None
361        } else {
362            unsafe {
363                self.len -= 1;
364                let ptr = self.as_ptr();
365                if self.len != 0 {
366                    self.buf.mov_ptr_add(1);
367                }
368                Some(ptr::read(ptr))
369            }
370        }
371    }
372
373    /// Appends an element to the beginning of a collection.
374    ///
375    /// # Panics
376    ///
377    /// Panics if the new capacity exceeds `isize::MAX` bytes.
378    ///
379    /// # Examples
380    ///
381    /// ```
382    /// use cev::Cev;
383    ///
384    /// let mut cev: Cev<i8> = Cev::new();
385    /// cev.push(1);
386    /// cev.push(2);
387    /// cev.push(3);
388    /// assert_eq!(cev, [3, 2, 1]);
389    /// ```
390    #[inline]
391    pub fn push(&mut self, value: T) {
392        if self.len == self.capacity() {
393            self.buf.reserve_for_push(self.len);
394        }
395        unsafe {
396            if self.len != 0 {
397                self.buf.mov_ptr_sub(1);
398            }
399            self.as_mut_ptr().write(value);
400            self.len += 1;
401        };
402    }
403
404    /// Returns a constant unsafe pointer.
405    /// Pointer for alloc and dealloc memory.
406    #[inline]
407    pub fn raw_ptr(&self) -> *const T {
408        self.buf.raw_ptr()
409    }
410
411    /// Reserves capacity for the elements in this collection.
412    /// It is possible that more space will be reserved than specified.
413    /// Does nothing if capacity is already sufficient.
414    ///
415    /// # Panics
416    ///
417    /// Panics if the new capacity exceeds `isize::MAX` bytes.
418    ///
419    /// # Examples
420    ///
421    /// ```
422    /// use cev::Cev;
423    ///
424    /// let mut cev = Cev::from(["one"]);
425    /// cev.reserve(5);
426    /// assert!(cev.capacity() >= 6);
427    /// ```
428    pub fn reserve(&mut self, additional: usize) {
429        self.buf.reserve(self.len, additional);
430    }
431
432    /// Changes the current length to `new_len`.
433    ///
434    /// # Safety
435    /// - Length of new_len must be initialized.
436    /// - The length must be equal to or less than the capacity.
437    /// - The `mov_ptr` **pointer must be set to the correct position**.
438    ///
439    /// # Exaples
440    ///
441    /// ```
442    /// use cev::Cev;
443    ///
444    /// let mut cev = Cev::<u8>::from([21, 32, 43]);
445    /// unsafe {
446    ///     cev.set_len(2);
447    ///     cev.as_mut_ptr().add(cev.capacity() - cev.len());
448    /// };
449    /// assert_eq!(cev, [21, 32]);
450    /// ```
451    #[inline]
452    pub unsafe fn set_len(&mut self, new_len: usize) {
453        debug_assert!(new_len <= self.capacity());
454
455        self.len = new_len;
456    }
457
458    /// Changes the current length to `new_len`,
459    /// also sets the `mov_ptr` pointer to the desired position.
460    ///
461    /// # Safety
462    /// - Length of new_len must be initialized.
463    /// - The length of `new_len` must not be greater than the capacity.
464    ///
465    /// # Examples
466    ///
467    /// ```
468    /// use cev::Cev;
469    ///
470    /// let mut cev = Cev::from([1, 2, 3, 4, 5]);
471    ///
472    /// unsafe { cev.set_len_ptr(2) };
473    /// assert_eq!(cev, [4, 5]);
474    /// ```
475    #[inline]
476    pub unsafe fn set_len_ptr(&mut self, new_len: usize) {
477        debug_assert!(new_len <= self.capacity());
478
479        self.buf.mov_ptr(self.mov_ptr(new_len));
480        self.len = new_len;
481    }
482
483    #[inline]
484    unsafe fn mov_ptr(&self, new_len: usize) -> *mut T {
485        if self.capacity() == new_len {
486            self.buf.raw_ptr()
487        } else if new_len == 0 {
488            self.buf.raw_ptr().add(self.capacity() - 1)
489        } else {
490            self.buf.raw_ptr().add(self.capacity() - new_len)
491        }
492    }
493
494    /// Returns the remaining spare capacity of the `Cev` array as a slice of
495    /// `MaybeUninit<T>`.
496    #[inline]
497    pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
498        unsafe {
499            slice::from_raw_parts_mut(
500                self.buf.raw_ptr() as *mut MaybeUninit<T>,
501                self.buf.capacity() - self.len,
502            )
503        }
504    }
505
506    /// Reduces the length of the `Cev` array to `len`,
507    /// by removing elements from the beginning of the array.
508    ///
509    /// # Examples
510    ///
511    /// ```
512    /// use cev::Cev;
513    ///
514    /// let mut cev = Cev::from(['T', 'r', 'u', 'n', 'c', 'a', 't', 'e']);
515    /// cev.truncate(4);
516    /// assert_eq!(cev, ['c', 'a', 't', 'e']);
517    /// ```
518    pub fn truncate(&mut self, len: usize) {
519        unsafe {
520            if len >= self.len {
521                return;
522            }
523
524            let remaining_len = self.len - len;
525            let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), remaining_len);
526            if len != 0 {
527                self.buf.mov_ptr_add(remaining_len);
528            } else {
529                self.buf.mov_ptr_add(remaining_len - 1);
530            }
531
532            self.len = len;
533            ptr::drop_in_place(s);
534        }
535    }
536
537    /// Creates a new `Cev` array and allocates memory for type `T` with the given capacity.
538    /// If `capacity` is null, no memory is allocated.
539    ///
540    /// # Panics
541    ///
542    /// Panics if the new capacity exceeds `isize::MAX` bytes.
543    ///
544    /// # Examples
545    ///
546    /// ```
547    /// use cev::Cev;
548    /// use std::ptr::NonNull;
549    ///
550    /// let mut cev = Cev::with_capacity(0);
551    /// assert_eq!(cev.as_ptr(), NonNull::<u32>::dangling().as_ptr());
552    ///
553    /// let capacity = 5;
554    /// let mut cev = Cev::with_capacity(capacity);
555    ///
556    /// assert!(cev.capacity() >= capacity);
557    ///
558    /// for val in 0..=capacity {
559    ///     cev.insert(0, val);
560    /// }
561    /// assert_eq!(cev, [5, 4, 3, 2, 1, 0]);
562    ///
563    /// ```
564    #[inline]
565    pub fn with_capacity(capacity: usize) -> Self {
566        Cev {
567            buf: RawCev::with_capacity(capacity),
568            len: 0,
569        }
570    }
571
572    /// Appends elements to `self` from other buffer.
573    #[inline]
574    unsafe fn append_elements(&mut self, other: *const [T]) {
575        let count = (*other).len();
576        self.reserve(count);
577        self.set_len_ptr(self.len() + count);
578        ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr(), count);
579    }
580}
581
582impl<T> AsRef<Cev<T>> for Cev<T> {
583    fn as_ref(&self) -> &Cev<T> {
584        self
585    }
586}
587
588impl<T> AsMut<Cev<T>> for Cev<T> {
589    fn as_mut(&mut self) -> &mut Cev<T> {
590        self
591    }
592}
593
594impl<T> Borrow<[T]> for Cev<T> {
595    fn borrow(&self) -> &[T] {
596        &self[..]
597    }
598}
599
600impl<T> BorrowMut<[T]> for Cev<T> {
601    fn borrow_mut(&mut self) -> &mut [T] {
602        &mut self[..]
603    }
604}
605
606impl<T> AsRef<[T]> for Cev<T> {
607    fn as_ref(&self) -> &[T] {
608        self
609    }
610}
611
612impl<T> AsMut<[T]> for Cev<T> {
613    fn as_mut(&mut self) -> &mut [T] {
614        self
615    }
616}
617
618impl<T> ops::Deref for Cev<T> {
619    type Target = [T];
620
621    #[inline]
622    fn deref(&self) -> &[T] {
623        unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
624    }
625}
626
627impl<T> ops::DerefMut for Cev<T> {
628    #[inline]
629    fn deref_mut(&mut self) -> &mut [T] {
630        unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
631    }
632}
633
634impl<T> Drop for Cev<T> {
635    fn drop(&mut self) {
636        unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)) }
637    }
638}
639
640impl<T: fmt::Debug> fmt::Debug for Cev<T> {
641    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
642        fmt::Debug::fmt(&**self, f)
643    }
644}
645
646macro_rules! impl_slice_eq {
647    ([$($vars:tt)*] $lhs:ty, $rhs:ty $(where $ty:ty: $bound:ident)?) => {
648        impl<T, U, $($vars)*> PartialEq<$rhs> for $lhs
649        where
650            T: PartialEq<U>,
651            $($ty: $bound)?
652        {
653            #[inline]
654            fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }
655            #[inline]
656            fn ne(&self, other: &$rhs) -> bool { self[..] != other[..] }
657        }
658    }
659}
660
661impl_slice_eq! { [] Cev<T>, &[U]}
662impl_slice_eq! { [const N: usize] Cev<T>, [U; N] }
663impl_slice_eq! { [const N: usize] Cev<T>, &[U; N] }
664impl_slice_eq! { [] Cev<T>, &mut [U] }
665impl_slice_eq! { [] Cev<T>, [U] }
666impl_slice_eq! { [] [T], Cev<U> }
667impl_slice_eq! { [] &[T], Cev<U> }
668impl_slice_eq! { [] &mut [T], Cev<U> }
669impl_slice_eq! { [] Cev<T>, Cev<U> }
670impl_slice_eq! { [] Cev<T>, Vec<U> }
671impl_slice_eq! { [] Vec<T>, Cev<U> }
672
673impl<T: PartialOrd> PartialOrd for Cev<T> {
674    #[inline]
675    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
676        PartialOrd::partial_cmp(&**self, &**other)
677    }
678}
679
680impl<T: Eq> Eq for Cev<T> {}
681
682impl<T: Ord> Ord for Cev<T> {
683    #[inline]
684    fn cmp(&self, other: &Self) -> Ordering {
685        Ord::cmp(&**self, &**other)
686    }
687}
688
689impl<T> Default for Cev<T> {
690    fn default() -> Cev<T> {
691        Cev::new()
692    }
693}
694
695impl<T> Clone for Cev<T>
696where
697    T: Clone,
698{
699    fn clone(&self) -> Self {
700        to_cev(self)
701    }
702}
703
704pub fn to_cev<T: ConvertCev>(s: &[T]) -> Cev<T> {
705    T::to_cev(s)
706}
707
708impl<T, I: SliceIndex<[T]>> Index<I> for Cev<T> {
709    type Output = I::Output;
710
711    #[inline]
712    fn index(&self, index: I) -> &Self::Output {
713        Index::index(&**self, index)
714    }
715}
716
717impl<T, I: SliceIndex<[T]>> IndexMut<I> for Cev<T> {
718    #[inline]
719    fn index_mut(&mut self, index: I) -> &mut Self::Output {
720        IndexMut::index_mut(&mut **self, index)
721    }
722}
723
724impl<T, const N: usize> TryFrom<Cev<T>> for [T; N] {
725    type Error = Cev<T>;
726
727    fn try_from(mut cev: Cev<T>) -> Result<[T; N], Cev<T>> {
728        if cev.len() != N {
729            return Err(cev);
730        }
731
732        unsafe { cev.set_len(0) };
733        let array = unsafe { ptr::read(cev.as_ptr() as *const [T; N]) };
734        Ok(array)
735    }
736}
737
738impl<T> From<Cev<T>> for Vec<T> {
739    fn from(cev: Cev<T>) -> Vec<T> {
740        cev.into_vec()
741    }
742}
743
744impl<T> From<Vec<T>> for Cev<T> {
745    fn from(vec: Vec<T>) -> Cev<T> {
746        Cev::from_vec(vec)
747    }
748}
749
750impl<T, const N: usize> From<[T; N]> for Cev<T> {
751    fn from(slice: [T; N]) -> Cev<T> {
752        Cev::from(Vec::from(slice))
753    }
754}
755
756impl<T> From<&[T]> for Cev<T>
757where
758    T: Clone,
759{
760    fn from(slice: &[T]) -> Cev<T> {
761        to_cev(slice)
762    }
763}
764
765impl<T> From<&mut [T]> for Cev<T>
766where
767    T: Clone,
768{
769    fn from(slice: &mut [T]) -> Cev<T> {
770        to_cev(slice)
771    }
772}
773
774pub trait ConvertCev {
775    fn to_cev(s: &[Self]) -> Cev<Self>
776    where
777        Self: Sized;
778}
779
780impl<T> FromIterator<T> for Cev<T> {
781    #[inline]
782    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Cev<T> {
783        Self::from_vec(iter.into_iter().collect::<Vec<_>>())
784    }
785}
786
787impl<T> IntoIterator for Cev<T> {
788    type Item = T;
789    type IntoIter = IntoIter<T>;
790
791    #[inline]
792    fn into_iter(self) -> Self::IntoIter {
793        let cev = ManuallyDrop::new(self);
794        let ptr = cev.as_ptr();
795        let len = cev.len();
796
797        IntoIter {
798            buf: unsafe { NonNull::new_unchecked(cev.buf.raw_ptr()) },
799            cap: cev.capacity(),
800            len,
801            ptr,
802            end: unsafe { ptr.add(len) },
803        }
804    }
805}
806
807impl<'a, T> IntoIterator for &'a Cev<T> {
808    type Item = &'a T;
809    type IntoIter = slice::Iter<'a, T>;
810
811    fn into_iter(self) -> Self::IntoIter {
812        self.iter()
813    }
814}
815
816impl<'a, T> IntoIterator for &'a mut Cev<T> {
817    type Item = &'a mut T;
818    type IntoIter = slice::IterMut<'a, T>;
819
820    fn into_iter(self) -> Self::IntoIter {
821        self.iter_mut()
822    }
823}
824
825impl<T: Clone> ConvertCev for T {
826    fn to_cev(s: &[Self]) -> Cev<Self> {
827        struct DropGuard<'a, T> {
828            cev: &'a mut Cev<T>,
829            num_init: usize,
830        }
831
832        impl<'a, T> Drop for DropGuard<'a, T> {
833            fn drop(&mut self) {
834                unsafe {
835                    self.cev.set_len(self.num_init);
836                }
837            }
838        }
839
840        let mut cev = Cev::with_capacity(s.len());
841        let mut guard = DropGuard {
842            cev: &mut cev,
843            num_init: 0,
844        };
845
846        let slots = guard.cev.spare_capacity_mut();
847        for (i, b) in s.iter().enumerate().take(slots.len()) {
848            guard.num_init = i;
849            slots[i].write(b.clone());
850        }
851
852        core::mem::forget(guard);
853        unsafe {
854            cev.set_len(s.len());
855            cev.buf.mov_ptr(cev.buf.raw_ptr());
856        }
857        cev
858    }
859}
860
861pub struct IntoIter<T> {
862    buf: NonNull<T>,
863    cap: usize,
864    len: usize,
865    ptr: *const T,
866    end: *const T,
867}
868
869impl<T> IntoIter<T> {
870    pub fn as_slice(&self) -> &[T] {
871        unsafe { slice::from_raw_parts(self.ptr, self.len()) }
872    }
873
874    pub fn as_mut_slice(&mut self) -> &mut [T] {
875        unsafe { &mut *self.as_raw_mut_slice() }
876    }
877
878    fn as_raw_mut_slice(&mut self) -> *mut [T] {
879        ptr::slice_from_raw_parts_mut(self.ptr as *mut T, self.len())
880    }
881}
882
883impl<T> AsRef<[T]> for IntoIter<T> {
884    fn as_ref(&self) -> &[T] {
885        self.as_slice()
886    }
887}
888
889impl<T> Default for IntoIter<T> {
890    fn default() -> Self {
891        Cev::new().into_iter()
892    }
893}
894
895impl<T> Iterator for IntoIter<T> {
896    type Item = T;
897
898    #[inline]
899    fn next(&mut self) -> Option<T> {
900        if self.len == 0 {
901            None
902        } else {
903            unsafe {
904                self.len -= 1;
905                let ptr = self.ptr;
906                self.ptr = self.ptr.add(1);
907                Some(ptr::read(ptr))
908            }
909        }
910    }
911
912    #[inline]
913    fn size_hint(&self) -> (usize, Option<usize>) {
914        (self.len, Some(self.len))
915    }
916}
917
918impl<T> Drop for IntoIter<T> {
919    fn drop(&mut self) {
920        if self.cap != 0 {
921            for _ in &mut *self {}
922            unsafe {
923                let _ = RawCev::from_raw_parts_ptr(self.buf.as_ptr(), self.buf.as_ptr(), self.cap);
924            }
925        }
926    }
927}
928
929impl<T> DoubleEndedIterator for IntoIter<T> {
930    #[inline]
931    fn next_back(&mut self) -> Option<T> {
932        if self.len == 0 {
933            None
934        } else {
935            unsafe {
936                self.len -= 1;
937                self.end = self.end.sub(1);
938                Some(ptr::read(self.end))
939            }
940        }
941    }
942}
943
944impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
945    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
946        f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
947    }
948}
949
950impl<T> ExactSizeIterator for IntoIter<T> {}