Skip to main content

stabby_abi/alloc/
vec.rs

1//
2// Copyright (c) 2023 ZettaScale Technology
3//
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License 2.0 which is available at
6// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
7// which is available at https://www.apache.org/licenses/LICENSE-2.0.
8//
9// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
10//
11// Contributors:
12//   Pierre Avital, <pierre.avital@me.com>
13//
14
15use crate::num::NonMaxUsize;
16
17use super::{single_or_vec, AllocPtr, AllocSlice, AllocationError, IAlloc};
18use core::fmt::Debug;
19use core::ptr::NonNull;
20
21mod seal {
22    use super::*;
23    #[crate::stabby]
24    pub struct VecInner<T, Alloc: IAlloc> {
25        pub(crate) start: AllocPtr<T, Alloc>,
26        pub(crate) end: NonNull<T>,
27        pub(crate) capacity: NonNull<T>,
28        pub(crate) alloc: Alloc,
29    }
30    // SAFETY: This is analogous to a BoxedSlice.
31    unsafe impl<T: Send, Alloc: IAlloc + Send> Send for VecInner<T, Alloc> where
32        crate::alloc::boxed::BoxedSlice<T, Alloc>: Send
33    {
34    }
35    // SAFETY: This is analogous to a BoxedSlice.
36    unsafe impl<T: Sync, Alloc: IAlloc + Sync> Sync for VecInner<T, Alloc> where
37        crate::alloc::boxed::BoxedSlice<T, Alloc>: Sync
38    {
39    }
40}
41pub(crate) use seal::*;
42
43/// A growable vector of elements.
44#[crate::stabby]
45pub struct Vec<T, Alloc: IAlloc = super::DefaultAllocator> {
46    pub(crate) inner: VecInner<T, Alloc>,
47}
48
49pub(crate) const fn ptr_diff<T>(lhs: NonNull<T>, rhs: NonNull<T>) -> usize {
50    let diff = if core::mem::size_of::<T>() == 0 {
51        unsafe { lhs.as_ptr().cast::<u8>().offset_from(rhs.as_ptr().cast()) }
52    } else {
53        unsafe { lhs.as_ptr().offset_from(rhs.as_ptr()) }
54    };
55    debug_assert!(diff >= 0);
56    diff as usize
57}
58pub(crate) const fn ptr_add<T>(lhs: NonNull<T>, rhs: usize) -> NonNull<T> {
59    if core::mem::size_of::<T>() == 0 {
60        unsafe { NonNull::new_unchecked(lhs.as_ptr().cast::<u8>().add(rhs)).cast() }
61    } else {
62        unsafe { NonNull::new_unchecked(lhs.as_ptr().add(rhs)) }
63    }
64}
65
66#[cfg(not(stabby_default_alloc = "disabled"))]
67impl<T> Vec<T> {
68    /// Constructs a new vector with the default allocator. This doesn't actually allocate.
69    pub const fn new() -> Self {
70        Self::new_in(super::DefaultAllocator::new())
71    }
72}
73impl<T, Alloc: IAlloc> Vec<T, Alloc> {
74    /// Constructs a new vector in `alloc`. This doesn't actually allocate.
75    pub const fn new_in(alloc: Alloc) -> Self {
76        let start = AllocPtr::dangling();
77        Self {
78            inner: VecInner {
79                start,
80                end: start.ptr,
81                capacity: if Self::zst_mode() {
82                    unsafe { core::mem::transmute::<usize, NonNull<T>>(usize::MAX) }
83                } else {
84                    start.ptr
85                },
86                alloc,
87            },
88        }
89    }
90    /// Constructs a new vector in `alloc`, allocating sufficient space for `capacity` elements.
91    ///
92    /// # Panics
93    /// If the allocator failed to provide a large enough allocation.
94    pub fn with_capacity_in(capacity: usize, alloc: Alloc) -> Self {
95        let mut this = Self::new_in(alloc);
96        this.reserve(capacity);
97        this
98    }
99    /// Constructs a new vector, allocating sufficient space for `capacity` elements.
100    ///
101    /// # Panics
102    /// If the allocator failed to provide a large enough allocation.
103    pub fn with_capacity(capacity: usize) -> Self
104    where
105        Alloc: Default,
106    {
107        Self::with_capacity_in(capacity, Alloc::default())
108    }
109    /// Constructs a new vector in `alloc`, allocating sufficient space for `capacity` elements.
110    /// # Errors
111    /// Returns an [`AllocationError`] if the allocator couldn't provide a sufficient allocation.
112    pub fn try_with_capacity_in(capacity: usize, alloc: Alloc) -> Result<Self, Alloc> {
113        let mut this = Self::new_in(alloc);
114        match this.try_reserve(capacity) {
115            Ok(_) => Ok(this),
116            Err(_) => Err(this.into_raw_components().2),
117        }
118    }
119    /// Constructs a new vector, allocating sufficient space for `capacity` elements.
120    /// # Errors
121    /// Returns an [`AllocationError`] if the allocator couldn't provide a sufficient allocation.
122    pub fn try_with_capacity(capacity: usize) -> Result<Self, Alloc>
123    where
124        Alloc: Default,
125    {
126        Self::try_with_capacity_in(capacity, Alloc::default())
127    }
128    #[inline(always)]
129    const fn zst_mode() -> bool {
130        core::mem::size_of::<T>() == 0
131    }
132    /// Returns the number of elements in the vector.
133    pub const fn len(&self) -> usize {
134        ptr_diff(self.inner.end, self.inner.start.ptr)
135    }
136    /// Returns `true` if the vector is empty.
137    pub const fn is_empty(&self) -> bool {
138        self.len() == 0
139    }
140    /// Sets the length of the vector, not calling any destructors.
141    /// # Safety
142    /// This can lead to uninitialized memory being interpreted as an initialized value of `T`.
143    #[rustversion::attr(since(1.86), const)]
144    pub unsafe fn set_len(&mut self, len: usize) {
145        self.inner.end = ptr_add(self.inner.start.ptr, len);
146    }
147    /// Adds `value` at the end of `self`.
148    /// # Panics
149    /// This function panics if the vector tried to grow due to
150    /// being full, and the allocator failed to provide a new allocation.
151    pub fn push(&mut self, value: T) {
152        if self.inner.end == self.inner.capacity {
153            self.grow();
154        }
155        unsafe { self.inner.end.as_ptr().write(value) }
156        self.inner.end = ptr_add(self.inner.end, 1)
157    }
158    /// Adds `value` at the end of `self`.
159    ///
160    /// # Errors
161    /// This function gives back the `value` if the vector tried to grow due to
162    /// being full, and the allocator failed to provide a new allocation.
163    ///
164    /// `self` is still valid should that happen.
165    pub fn try_push(&mut self, value: T) -> Result<(), T> {
166        if self.inner.end == self.inner.capacity && self.try_grow().is_err() {
167            return Err(value);
168        }
169        unsafe { self.inner.end.as_ptr().write(value) }
170        self.inner.end = ptr_add(self.inner.end, 1);
171        Ok(())
172    }
173    /// The total capacity of the vector.
174    pub const fn capacity(&self) -> usize {
175        ptr_diff(self.inner.capacity, self.inner.start.ptr)
176    }
177    /// The remaining number of elements that can be pushed before reallocating.
178    pub const fn remaining_capacity(&self) -> usize {
179        ptr_diff(self.inner.capacity, self.inner.end)
180    }
181    const FIRST_CAPACITY: usize = match 1024 / core::mem::size_of::<T>() {
182        0 => 1,
183        v @ 1..=8 => v,
184        _ => 8,
185    };
186    fn grow(&mut self) {
187        self.try_grow().unwrap();
188    }
189    fn try_grow(&mut self) -> Result<NonMaxUsize, AllocationError> {
190        if self.capacity() == 0 {
191            let first_capacity = Self::FIRST_CAPACITY;
192            self.try_reserve(first_capacity)
193        } else {
194            self.try_reserve((self.capacity() >> 1).max(1))
195        }
196    }
197    /// Ensures that `additional` more elements can be pushed on `self` without reallocating.
198    ///
199    /// This may reallocate once to provide this guarantee.
200    ///
201    /// # Panics
202    /// This function panics if the allocator failed to provide an appropriate allocation.
203    pub fn reserve(&mut self, additional: usize) {
204        self.try_reserve(additional).unwrap();
205    }
206    /// Ensures that `additional` more elements can be pushed on `self` without reallocating.
207    ///
208    /// This may reallocate once to provide this guarantee.
209    ///
210    /// # Errors
211    /// Returns Ok(new_capacity) if succesful (including if no reallocation was needed),
212    /// otherwise returns Err(AllocationError)
213    pub fn try_reserve(&mut self, additional: usize) -> Result<NonMaxUsize, AllocationError> {
214        if self.remaining_capacity() < additional {
215            let len = self.len();
216            let new_capacity = len.wrapping_add(additional);
217            let old_capacity = self.capacity();
218            let start = if old_capacity != 0 {
219                unsafe {
220                    self.inner
221                        .start
222                        .realloc(&mut self.inner.alloc, old_capacity, new_capacity)
223                }
224            } else {
225                AllocPtr::alloc_array(&mut self.inner.alloc, new_capacity)
226            };
227            let Some(start) = start else {
228                return Err(AllocationError());
229            };
230            let end = ptr_add(*start, len);
231            let capacity = ptr_add(*start, new_capacity);
232            self.inner.start = start;
233            self.inner.end = end;
234            self.inner.capacity = capacity;
235            Ok(unsafe { NonMaxUsize::new_unchecked(new_capacity) })
236        } else {
237            let mut capacity = self.capacity();
238            if capacity == usize::MAX {
239                capacity = capacity.wrapping_sub(1);
240            }
241            Ok(unsafe { NonMaxUsize::new_unchecked(capacity) })
242        }
243    }
244    /// Removes all elements from `self` from the `len`th onward.
245    ///
246    /// Does nothing if `self.len() <= len`
247    pub fn truncate(&mut self, len: usize) {
248        if let Some(to_drop) = self.get_mut(len..) {
249            // SAFETY: `to_drop` is initialized (as it is returned by `get_mut`), so dropping in place is safe provided it's never accessed again, which `set_len` guarantees.
250            unsafe {
251                core::ptr::drop_in_place(to_drop);
252                self.set_len(len);
253            }
254        }
255    }
256    /// Returns a slice of the vector's elements.
257    pub const fn as_slice(&self) -> &[T] {
258        let start = self.inner.start;
259        let end = self.inner.end;
260        unsafe { core::slice::from_raw_parts(start.ptr.as_ptr(), ptr_diff(end, start.ptr)) }
261    }
262    /// Returns a mutable slice of the vector's elements.
263    #[rustversion::attr(since(1.86), const)]
264    pub fn as_slice_mut(&mut self) -> &mut [T] {
265        let start = self.inner.start;
266        let end = self.inner.end;
267        unsafe { core::slice::from_raw_parts_mut(start.ptr.as_ptr(), ptr_diff(end, start.ptr)) }
268    }
269    pub(crate) fn into_raw_components(self) -> (AllocSlice<T, Alloc>, usize, Alloc) {
270        let VecInner {
271            start,
272            end,
273            capacity: _,
274            alloc,
275        } = unsafe { core::ptr::read(&self.inner) };
276        let capacity = if core::mem::size_of::<T>() == 0 {
277            0
278        } else {
279            self.capacity()
280        };
281        core::mem::forget(self);
282        (AllocSlice { start, end }, capacity, alloc)
283    }
284    /// Extends `self` using a `memcpy`.
285    /// This may be faster than extending through an iterator.
286    /// # Panics
287    /// If extending required an allocation that failed.
288    pub fn copy_extend(&mut self, slice: &[T])
289    where
290        T: Copy,
291    {
292        self.try_copy_extend(slice).unwrap();
293    }
294    /// Extends `self` using a `memcpy`.
295    /// This may be faster than extending through an iterator.
296    /// # Errors
297    /// If extending required an allocation that failed.
298    pub fn try_copy_extend(&mut self, slice: &[T]) -> Result<(), AllocationError>
299    where
300        T: Copy,
301    {
302        if slice.is_empty() {
303            return Ok(());
304        }
305        self.try_reserve(slice.len())?;
306        unsafe {
307            core::ptr::copy_nonoverlapping(slice.as_ptr(), self.inner.end.as_ptr(), slice.len());
308            self.set_len(self.len().wrapping_add(slice.len()));
309        }
310        Ok(())
311    }
312    /// Iterates immutably over the vector's elements.
313    pub fn iter(&self) -> core::slice::Iter<'_, T> {
314        self.into_iter()
315    }
316    /// Iterates mutably over the vector's elements.
317    pub fn iter_mut(&mut self) -> core::slice::IterMut<'_, T> {
318        self.into_iter()
319    }
320    /// Removes the specified range from the vector in bulk,
321    /// returning all removed elements as an iterator.
322    /// If the iterator is dropped before being fully consumed,
323    /// it drops the remaining removed elements.
324    ///
325    /// If the drain is leaked, then the vector may lose and leak elements,
326    /// even if they weren't in the specified `range`
327    ///
328    /// # Panics
329    /// This function immediately panics if the range has a negative size, or if the range exceeds `self.len()`
330    pub fn drain<R: core::ops::RangeBounds<usize>>(&mut self, range: R) -> Drain<'_, T, Alloc> {
331        let original_len = self.len();
332        let from = match range.start_bound() {
333            core::ops::Bound::Included(i) => *i,
334            core::ops::Bound::Excluded(i) => i.wrapping_add(1),
335            core::ops::Bound::Unbounded => 0,
336        };
337        let to = match range.end_bound() {
338            core::ops::Bound::Included(i) => i.wrapping_add(1),
339            core::ops::Bound::Excluded(i) => *i,
340            core::ops::Bound::Unbounded => original_len,
341        };
342        assert!(to >= from);
343        assert!(to <= original_len);
344        unsafe { self.set_len(from) };
345        Drain {
346            vec: self,
347            from,
348            to,
349            index: from,
350            original_len,
351        }
352    }
353    /// Removes the specified range from the vector in bulk,
354    /// returning all removed elements as an iterator.
355    /// If the iterator is dropped before being fully consumed,
356    /// it drops the remaining removed elements.
357    ///
358    /// If the drain is leaked, then the vector may lose and leak elements,
359    /// even if they weren't in the specified `range`
360    ///
361    /// # Errors
362    /// This function returns `None` if the range has negative size, or would exceed `self.len()`.
363    pub fn try_drain<R: core::ops::RangeBounds<usize>>(
364        &mut self,
365        range: R,
366    ) -> Option<Drain<'_, T, Alloc>> {
367        let original_len = self.len();
368        let from = match range.start_bound() {
369            core::ops::Bound::Included(i) => *i,
370            core::ops::Bound::Excluded(i) => i.wrapping_add(1),
371            core::ops::Bound::Unbounded => 0,
372        };
373        let to = match range.end_bound() {
374            core::ops::Bound::Included(i) => i.wrapping_add(1),
375            core::ops::Bound::Excluded(i) => *i,
376            core::ops::Bound::Unbounded => original_len,
377        };
378        if to <= from || to >= original_len {
379            return None;
380        }
381        unsafe { self.set_len(from) };
382        Some(Drain {
383            vec: self,
384            from,
385            to,
386            index: from,
387            original_len,
388        })
389    }
390    /// Removes the element at `index` without reordering.
391    #[rustversion::attr(since(1.86), const)]
392    pub fn remove(&mut self, index: usize) -> Option<T> {
393        if index < self.len() {
394            unsafe {
395                let value = self.inner.start.ptr.as_ptr().add(index).read();
396                core::ptr::copy(
397                    self.inner.start.ptr.as_ptr().add(index.wrapping_add(1)),
398                    self.inner.start.ptr.as_ptr().add(index),
399                    self.len().wrapping_sub(index.wrapping_add(1)),
400                );
401                self.set_len(self.len().wrapping_sub(1));
402                Some(value)
403            }
404        } else {
405            None
406        }
407    }
408    /// Swaps the elements at positions `a` and `b`
409    ///
410    /// # Panics
411    /// Panics if either index is out of bound.
412    pub fn swap(&mut self, a: usize, b: usize) {
413        assert!(a < self.len());
414        assert!(b < self.len());
415        unsafe {
416            core::ptr::swap(
417                self.inner.start.as_ptr().add(a),
418                self.inner.start.as_ptr().add(b),
419            )
420        };
421    }
422    /// Removes the last element of the vector, returning it if it exists.
423    #[rustversion::attr(since(1.86), const)]
424    pub fn pop(&mut self) -> Option<T> {
425        if self.is_empty() {
426            None
427        } else {
428            unsafe {
429                let value = self.inner.end.as_ptr().sub(1).read();
430                self.set_len(self.len().wrapping_sub(1));
431                Some(value)
432            }
433        }
434    }
435    /// Removes the element at `index`, moving the last element in its place.
436    ///
437    /// This is more efficient than [`Self::remove`], but causes reordering.
438    pub fn swap_remove(&mut self, index: usize) -> Option<T> {
439        if index >= self.len() {
440            return None;
441        }
442        self.swap(index, self.len().wrapping_sub(1));
443        self.pop()
444    }
445    /// Returns a reference to the vector's allocator.
446    pub const fn allocator(&self) -> &Alloc {
447        &self.inner.alloc
448    }
449    /// Returns a mutable reference to the vector's allocator.
450    #[rustversion::attr(since(1.86), const)]
451    pub fn allocator_mut(&mut self) -> &mut Alloc {
452        &mut self.inner.alloc
453    }
454}
455
456impl<T: Clone, Alloc: IAlloc + Clone> Clone for Vec<T, Alloc> {
457    fn clone(&self) -> Self {
458        let mut ret = Self::with_capacity_in(self.len(), self.inner.alloc.clone());
459        for (i, item) in self.iter().enumerate() {
460            unsafe { ret.inner.start.ptr.as_ptr().add(i).write(item.clone()) }
461        }
462        unsafe { ret.set_len(self.len()) };
463        ret
464    }
465}
466impl<T: PartialEq, Alloc: IAlloc, Rhs: AsRef<[T]>> PartialEq<Rhs> for Vec<T, Alloc> {
467    fn eq(&self, other: &Rhs) -> bool {
468        self.as_slice() == other.as_ref()
469    }
470}
471impl<T: Eq, Alloc: IAlloc> Eq for Vec<T, Alloc> {}
472impl<T: PartialOrd, Alloc: IAlloc, Rhs: AsRef<[T]>> PartialOrd<Rhs> for Vec<T, Alloc> {
473    fn partial_cmp(&self, other: &Rhs) -> Option<core::cmp::Ordering> {
474        self.as_slice().partial_cmp(other.as_ref())
475    }
476}
477impl<T: Ord, Alloc: IAlloc> Ord for Vec<T, Alloc> {
478    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
479        self.as_slice().cmp(other.as_slice())
480    }
481}
482
483use crate::{IDeterminantProvider, IStable};
484use single_or_vec::Single;
485
486macro_rules! impl_index {
487    ($index: ty) => {
488        impl<T, Alloc: IAlloc> core::ops::Index<$index> for Vec<T, Alloc> {
489            type Output = <[T] as core::ops::Index<$index>>::Output;
490            fn index(&self, index: $index) -> &Self::Output {
491                #[allow(clippy::indexing_slicing)]
492                &self.as_slice()[index]
493            }
494        }
495        impl<T, Alloc: IAlloc> core::ops::IndexMut<$index> for Vec<T, Alloc> {
496            fn index_mut(&mut self, index: $index) -> &mut Self::Output {
497                #[allow(clippy::indexing_slicing)]
498                &mut self.as_slice_mut()[index]
499            }
500        }
501        impl<T, Alloc: IAlloc> core::ops::Index<$index> for SingleOrVec<T, Alloc>
502        where
503            T: IStable,
504            Alloc: IStable,
505            Single<T, Alloc>: IDeterminantProvider<Vec<T, Alloc>>,
506            Vec<T, Alloc>: IStable,
507            crate::Result<Single<T, Alloc>, Vec<T, Alloc>>: IStable,
508        {
509            type Output = <[T] as core::ops::Index<$index>>::Output;
510            fn index(&self, index: $index) -> &Self::Output {
511                #[allow(clippy::indexing_slicing)]
512                &self.as_slice()[index]
513            }
514        }
515    };
516}
517
518impl<T, Alloc: IAlloc> core::ops::Deref for Vec<T, Alloc> {
519    type Target = [T];
520    fn deref(&self) -> &Self::Target {
521        self.as_slice()
522    }
523}
524impl<T, Alloc: IAlloc> core::convert::AsRef<[T]> for Vec<T, Alloc> {
525    fn as_ref(&self) -> &[T] {
526        self.as_slice()
527    }
528}
529impl<T, Alloc: IAlloc> core::ops::DerefMut for Vec<T, Alloc> {
530    fn deref_mut(&mut self) -> &mut Self::Target {
531        self.as_slice_mut()
532    }
533}
534impl<T, Alloc: IAlloc> core::convert::AsMut<[T]> for Vec<T, Alloc> {
535    fn as_mut(&mut self) -> &mut [T] {
536        self.as_slice_mut()
537    }
538}
539impl<T, Alloc: IAlloc + Default> Default for Vec<T, Alloc> {
540    fn default() -> Self {
541        Self::new_in(Alloc::default())
542    }
543}
544impl<T, Alloc: IAlloc> Drop for Vec<T, Alloc> {
545    fn drop(&mut self) {
546        unsafe { core::ptr::drop_in_place(self.as_slice_mut()) }
547        if core::mem::size_of::<T>() != 0 && self.capacity() != 0 {
548            unsafe { self.inner.start.free(&mut self.inner.alloc) }
549        }
550    }
551}
552impl<T: Copy, Alloc: IAlloc + Default> From<&[T]> for Vec<T, Alloc> {
553    fn from(value: &[T]) -> Self {
554        let mut this = Self::with_capacity(value.len());
555        this.copy_extend(value);
556        this
557    }
558}
559impl<T, Alloc: IAlloc> core::iter::Extend<T> for Vec<T, Alloc> {
560    fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
561        let iter = iter.into_iter();
562        let (min, max) = iter.size_hint();
563        match max {
564            Some(max) => {
565                self.reserve(max);
566                iter.for_each(|item| {
567                    unsafe { self.inner.end.as_ptr().write(item) };
568                    self.inner.end = ptr_add(self.inner.end, 1);
569                })
570            }
571            _ => {
572                self.reserve(min);
573                iter.for_each(|item| self.push(item))
574            }
575        }
576    }
577}
578
579impl<T, Alloc: IAlloc + Default> core::iter::FromIterator<T> for Vec<T, Alloc> {
580    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
581        let mut ret = Self::default();
582        ret.extend(iter);
583        ret
584    }
585}
586
587impl_index!(usize);
588impl_index!(core::ops::Range<usize>);
589impl_index!(core::ops::RangeInclusive<usize>);
590impl_index!(core::ops::RangeTo<usize>);
591impl_index!(core::ops::RangeToInclusive<usize>);
592impl_index!(core::ops::RangeFrom<usize>);
593impl_index!(core::ops::RangeFull);
594
595impl<T: Debug, Alloc: IAlloc> Debug for Vec<T, Alloc> {
596    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
597        self.as_slice().fmt(f)
598    }
599}
600impl<T: core::fmt::LowerHex, Alloc: IAlloc> core::fmt::LowerHex for Vec<T, Alloc> {
601    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
602        let mut first = true;
603        for item in self {
604            if !first {
605                f.write_str(":")?;
606            }
607            first = false;
608            core::fmt::LowerHex::fmt(item, f)?;
609        }
610        Ok(())
611    }
612}
613impl<T: core::fmt::UpperHex, Alloc: IAlloc> core::fmt::UpperHex for Vec<T, Alloc> {
614    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
615        let mut first = true;
616        for item in self {
617            if !first {
618                f.write_str(":")?;
619            }
620            first = false;
621            core::fmt::UpperHex::fmt(item, f)?;
622        }
623        Ok(())
624    }
625}
626impl<'a, T, Alloc: IAlloc> IntoIterator for &'a Vec<T, Alloc> {
627    type Item = &'a T;
628    type IntoIter = core::slice::Iter<'a, T>;
629    fn into_iter(self) -> Self::IntoIter {
630        self.as_slice().iter()
631    }
632}
633impl<'a, T, Alloc: IAlloc> IntoIterator for &'a mut Vec<T, Alloc> {
634    type Item = &'a mut T;
635    type IntoIter = core::slice::IterMut<'a, T>;
636    fn into_iter(self) -> Self::IntoIter {
637        self.as_slice_mut().iter_mut()
638    }
639}
640impl<T, Alloc: IAlloc> IntoIterator for Vec<T, Alloc> {
641    type Item = T;
642    type IntoIter = IntoIter<T, Alloc>;
643    fn into_iter(self) -> Self::IntoIter {
644        IntoIter {
645            vec: self,
646            index: 0,
647        }
648    }
649}
650/// [`Vec`]'s iterator.
651#[crate::stabby]
652pub struct IntoIter<T, Alloc: IAlloc> {
653    vec: Vec<T, Alloc>,
654    index: usize,
655}
656impl<T, Alloc: IAlloc> Iterator for IntoIter<T, Alloc> {
657    type Item = T;
658    fn next(&mut self) -> Option<Self::Item> {
659        (self.index < self.vec.len()).then(|| unsafe {
660            let ret = self.vec.inner.start.as_ptr().add(self.index).read();
661            self.index = self.index.wrapping_add(1);
662            ret
663        })
664    }
665}
666impl<T, Alloc: IAlloc> Drop for IntoIter<T, Alloc> {
667    fn drop(&mut self) {
668        unsafe {
669            #[allow(clippy::indexing_slicing)]
670            core::ptr::drop_in_place(&mut self.vec.as_slice_mut()[self.index..]);
671            self.vec.set_len(0);
672        }
673    }
674}
675/// An iterator that removes elements from a [`Vec`].
676///
677/// Dropping the `Drain` will finish draining its specified range.
678///
679/// Note that leaking the `Drain` may cause its [`Vec`] to lose and leak elements,
680/// even outside the specified range.
681#[crate::stabby]
682pub struct Drain<'a, T: 'a, Alloc: IAlloc + 'a> {
683    vec: &'a mut Vec<T, Alloc>,
684    from: usize,
685    to: usize,
686    index: usize,
687    original_len: usize,
688}
689impl<'a, T: 'a, Alloc: IAlloc + 'a> Drain<'a, T, Alloc> {
690    /// Prevents `self` from draining its vector any further, and applies the already
691    /// commited drain.
692    pub fn stop(mut self) {
693        self.to = self.index
694    }
695    /// Turns the drain into a double ended drain, which impls [`DoubleEndedIterator`]
696    #[rustversion::attr(since(1.86), const)]
697    pub fn double_ended(self) -> DoubleEndedDrain<'a, T, Alloc> {
698        let ret = DoubleEndedDrain {
699            vec: unsafe { core::ptr::read(&self.vec) },
700            from: self.from,
701            to: self.to,
702            original_len: self.original_len,
703            lindex: self.index,
704            rindex: self.to,
705        };
706        core::mem::forget(self);
707        ret
708    }
709}
710impl<'a, T: 'a, Alloc: IAlloc + 'a> Iterator for Drain<'a, T, Alloc> {
711    type Item = T;
712    fn size_hint(&self) -> (usize, Option<usize>) {
713        let remaining = self.to.wrapping_sub(self.index);
714        (remaining, Some(remaining))
715    }
716    fn next(&mut self) -> Option<Self::Item> {
717        (self.index < self.to).then(|| unsafe {
718            let ret = self.vec.inner.start.as_ptr().add(self.index).read();
719            self.index = self.index.wrapping_add(1);
720            ret
721        })
722    }
723}
724impl<'a, T: 'a, Alloc: IAlloc + 'a> ExactSizeIterator for Drain<'a, T, Alloc> {
725    fn len(&self) -> usize {
726        self.to.wrapping_sub(self.index)
727    }
728}
729impl<'a, T: 'a, Alloc: IAlloc + 'a> Drop for Drain<'a, T, Alloc> {
730    fn drop(&mut self) {
731        let tail_length = self.original_len.wrapping_sub(self.to);
732        unsafe {
733            core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut(
734                self.vec.inner.start.as_ptr().add(self.index),
735                self.to.wrapping_sub(self.index),
736            ));
737            core::ptr::copy(
738                self.vec.inner.start.as_ptr().add(self.to),
739                self.vec.inner.start.as_ptr().add(self.from),
740                tail_length,
741            );
742            self.vec.set_len(tail_length.wrapping_add(self.from));
743        }
744    }
745}
746/// A vector drain that works on both ends.
747#[crate::stabby]
748pub struct DoubleEndedDrain<'a, T: 'a, Alloc: IAlloc + 'a> {
749    vec: &'a mut Vec<T, Alloc>,
750    from: usize,
751    to: usize,
752    original_len: usize,
753    lindex: usize,
754    rindex: usize,
755}
756impl<'a, T: 'a, Alloc: IAlloc + 'a> Iterator for DoubleEndedDrain<'a, T, Alloc> {
757    type Item = T;
758    fn size_hint(&self) -> (usize, Option<usize>) {
759        let remaining = self.to.wrapping_sub(self.lindex);
760        (remaining, Some(remaining))
761    }
762    fn next(&mut self) -> Option<Self::Item> {
763        (self.lindex < self.rindex).then(|| unsafe {
764            let ret = self.vec.inner.start.as_ptr().add(self.lindex).read();
765            self.lindex = self.lindex.wrapping_add(1);
766            ret
767        })
768    }
769}
770impl<'a, T: 'a, Alloc: IAlloc + 'a> DoubleEndedIterator for DoubleEndedDrain<'a, T, Alloc> {
771    fn next_back(&mut self) -> Option<Self::Item> {
772        (self.lindex < self.rindex).then(|| unsafe {
773            let ret = self.vec.inner.start.as_ptr().add(self.rindex).read();
774            self.rindex = self.rindex.wrapping_sub(1);
775            ret
776        })
777    }
778}
779impl<'a, T: 'a, Alloc: IAlloc + 'a> ExactSizeIterator for DoubleEndedDrain<'a, T, Alloc> {
780    fn len(&self) -> usize {
781        self.rindex.wrapping_sub(self.lindex)
782    }
783}
784impl<'a, T: 'a, Alloc: IAlloc + 'a> Drop for DoubleEndedDrain<'a, T, Alloc> {
785    fn drop(&mut self) {
786        let tail_length = self.original_len.wrapping_sub(self.to);
787        unsafe {
788            core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut(
789                self.vec.inner.start.as_ptr().add(self.lindex),
790                self.rindex.wrapping_sub(self.lindex),
791            ));
792            core::ptr::copy(
793                self.vec.inner.start.as_ptr().add(self.to),
794                self.vec.inner.start.as_ptr().add(self.from),
795                tail_length,
796            );
797            self.vec.set_len(tail_length.wrapping_add(self.from));
798        }
799    }
800}
801#[cfg(feature = "std")]
802impl<Alloc: IAlloc> std::io::Write for Vec<u8, Alloc> {
803    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
804        match self.try_copy_extend(buf) {
805            Ok(()) => Ok(buf.len()),
806            Err(e) => Err(std::io::Error::new(std::io::ErrorKind::OutOfMemory, e)),
807        }
808    }
809
810    fn flush(&mut self) -> std::io::Result<()> {
811        Ok(())
812    }
813}
814
815#[cfg(feature = "std")]
816#[test]
817fn drain() {
818    use rand::Rng;
819    const LEN: usize = 2000;
820    let mut std = std::vec::Vec::with_capacity(LEN);
821    let mut new: Vec<u8> = Vec::new();
822    let mut capacity: Vec<u8> = Vec::with_capacity(LEN);
823    let mut rng = rand::thread_rng();
824    for _ in 0..LEN {
825        let n: u8 = rng.gen();
826        new.push(n);
827        capacity.push(n);
828        std.push(n);
829    }
830    assert_eq!(new.as_slice(), std.as_slice());
831    assert_eq!(new.as_slice(), capacity.as_slice());
832    new.drain(55..100);
833    capacity.drain(55..100);
834    std.drain(55..100);
835    new.swap(5, 92);
836    std.swap(5, 92);
837    capacity.swap(5, 92);
838    assert_eq!(new.as_slice(), std.as_slice());
839    assert_eq!(new.as_slice(), capacity.as_slice());
840}
841
842#[cfg(feature = "std")]
843#[test]
844fn try_drain() {
845    use rand::Rng;
846    const LEN: usize = 2000;
847    let mut std = std::vec::Vec::with_capacity(LEN);
848    let mut new: Vec<u8> = Vec::new();
849    let mut capacity: Vec<u8> = Vec::with_capacity(LEN);
850    let mut rng = rand::thread_rng();
851    for _ in 0..LEN {
852        let n: u8 = rng.gen();
853        new.push(n);
854        capacity.push(n);
855        std.push(n);
856    }
857    assert_eq!(new.as_slice(), std.as_slice());
858    assert_eq!(new.as_slice(), capacity.as_slice());
859    new.try_drain(55..100).expect("Drain size is valid");
860    capacity.try_drain(55..100).expect("Drain size is valid");
861    std.drain(55..100);
862    new.swap(5, 92);
863    std.swap(5, 92);
864    capacity.swap(5, 92);
865    assert_eq!(new.as_slice(), std.as_slice());
866    assert_eq!(new.as_slice(), capacity.as_slice());
867
868    #[allow(clippy::reversed_empty_ranges)]
869    {
870        assert!(new.try_drain(8..5).is_none());
871    }
872    assert!(new.try_drain(LEN..LEN + 1).is_none());
873}
874
875pub use super::single_or_vec::SingleOrVec;
876
877#[cfg(feature = "serde")]
878mod serde_impl {
879    use super::*;
880    use crate::alloc::IAlloc;
881    use serde::{de::Visitor, Deserialize, Serialize};
882    impl<T: Serialize, Alloc: IAlloc> Serialize for Vec<T, Alloc> {
883        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
884        where
885            S: serde::Serializer,
886        {
887            let slice: &[T] = self;
888            slice.serialize(serializer)
889        }
890    }
891    impl<'a, T: Deserialize<'a>, Alloc: IAlloc + Default> Deserialize<'a> for Vec<T, Alloc> {
892        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
893        where
894            D: serde::Deserializer<'a>,
895        {
896            deserializer.deserialize_seq(VecVisitor(core::marker::PhantomData))
897        }
898    }
899    pub struct VecVisitor<T, Alloc>(core::marker::PhantomData<(T, Alloc)>);
900    impl<'a, T: Deserialize<'a>, Alloc: IAlloc + Default> Visitor<'a> for VecVisitor<T, Alloc> {
901        type Value = Vec<T, Alloc>;
902        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
903            formatter.write_str("A sequence")
904        }
905        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
906        where
907            A: serde::de::SeqAccess<'a>,
908        {
909            let mut this = Vec::with_capacity_in(seq.size_hint().unwrap_or(0), Alloc::default());
910            while let Some(v) = seq.next_element()? {
911                this.push(v);
912            }
913            Ok(this)
914        }
915    }
916}