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 exceeeds `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    pub fn try_drain<R: core::ops::RangeBounds<usize>>(
361        &mut self,
362        range: R,
363    ) -> Option<Drain<'_, T, Alloc>> {
364        let original_len = self.len();
365        let from = match range.start_bound() {
366            core::ops::Bound::Included(i) => *i,
367            core::ops::Bound::Excluded(i) => i.wrapping_add(1),
368            core::ops::Bound::Unbounded => 0,
369        };
370        let to = match range.end_bound() {
371            core::ops::Bound::Included(i) => i.wrapping_add(1),
372            core::ops::Bound::Excluded(i) => *i,
373            core::ops::Bound::Unbounded => original_len,
374        };
375        if to >= from || to <= original_len {
376            return None;
377        }
378        unsafe { self.set_len(from) };
379        Some(Drain {
380            vec: self,
381            from,
382            to,
383            index: from,
384            original_len,
385        })
386    }
387    /// Removes the element at `index` without reordering.
388    #[rustversion::attr(since(1.86), const)]
389    pub fn remove(&mut self, index: usize) -> Option<T> {
390        if index < self.len() {
391            unsafe {
392                let value = self.inner.start.ptr.as_ptr().add(index).read();
393                core::ptr::copy(
394                    self.inner.start.ptr.as_ptr().add(index.wrapping_add(1)),
395                    self.inner.start.ptr.as_ptr().add(index),
396                    self.len().wrapping_sub(index.wrapping_add(1)),
397                );
398                self.set_len(self.len().wrapping_sub(1));
399                Some(value)
400            }
401        } else {
402            None
403        }
404    }
405    /// Swaps the elements at positions `a` and `b`
406    ///
407    /// # Panics
408    /// Panics if either index is out of bound.
409    pub fn swap(&mut self, a: usize, b: usize) {
410        assert!(a < self.len());
411        assert!(b < self.len());
412        unsafe {
413            core::ptr::swap(
414                self.inner.start.as_ptr().add(a),
415                self.inner.start.as_ptr().add(b),
416            )
417        };
418    }
419    /// Removes the last element of the vector, returning it if it exists.
420    #[rustversion::attr(since(1.86), const)]
421    pub fn pop(&mut self) -> Option<T> {
422        if self.is_empty() {
423            None
424        } else {
425            unsafe {
426                let value = self.inner.end.as_ptr().sub(1).read();
427                self.set_len(self.len().wrapping_sub(1));
428                Some(value)
429            }
430        }
431    }
432    /// Removes the element at `index`, moving the last element in its place.
433    ///
434    /// This is more efficient than [`Self::remove`], but causes reordering.
435    pub fn swap_remove(&mut self, index: usize) -> Option<T> {
436        if index >= self.len() {
437            return None;
438        }
439        self.swap(index, self.len().wrapping_sub(1));
440        self.pop()
441    }
442    /// Returns a reference to the vector's allocator.
443    pub const fn allocator(&self) -> &Alloc {
444        &self.inner.alloc
445    }
446    /// Returns a mutable reference to the vector's allocator.
447    #[rustversion::attr(since(1.86), const)]
448    pub fn allocator_mut(&mut self) -> &mut Alloc {
449        &mut self.inner.alloc
450    }
451}
452
453impl<T: Clone, Alloc: IAlloc + Clone> Clone for Vec<T, Alloc> {
454    fn clone(&self) -> Self {
455        let mut ret = Self::with_capacity_in(self.len(), self.inner.alloc.clone());
456        for (i, item) in self.iter().enumerate() {
457            unsafe { ret.inner.start.ptr.as_ptr().add(i).write(item.clone()) }
458        }
459        unsafe { ret.set_len(self.len()) };
460        ret
461    }
462}
463impl<T: PartialEq, Alloc: IAlloc, Rhs: AsRef<[T]>> PartialEq<Rhs> for Vec<T, Alloc> {
464    fn eq(&self, other: &Rhs) -> bool {
465        self.as_slice() == other.as_ref()
466    }
467}
468impl<T: Eq, Alloc: IAlloc> Eq for Vec<T, Alloc> {}
469impl<T: PartialOrd, Alloc: IAlloc, Rhs: AsRef<[T]>> PartialOrd<Rhs> for Vec<T, Alloc> {
470    fn partial_cmp(&self, other: &Rhs) -> Option<core::cmp::Ordering> {
471        self.as_slice().partial_cmp(other.as_ref())
472    }
473}
474impl<T: Ord, Alloc: IAlloc> Ord for Vec<T, Alloc> {
475    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
476        self.as_slice().cmp(other.as_slice())
477    }
478}
479
480use crate::{IDeterminantProvider, IStable};
481use single_or_vec::Single;
482
483macro_rules! impl_index {
484    ($index: ty) => {
485        impl<T, Alloc: IAlloc> core::ops::Index<$index> for Vec<T, Alloc> {
486            type Output = <[T] as core::ops::Index<$index>>::Output;
487            fn index(&self, index: $index) -> &Self::Output {
488                #[allow(clippy::indexing_slicing)]
489                &self.as_slice()[index]
490            }
491        }
492        impl<T, Alloc: IAlloc> core::ops::IndexMut<$index> for Vec<T, Alloc> {
493            fn index_mut(&mut self, index: $index) -> &mut Self::Output {
494                #[allow(clippy::indexing_slicing)]
495                &mut self.as_slice_mut()[index]
496            }
497        }
498        impl<T, Alloc: IAlloc> core::ops::Index<$index> for SingleOrVec<T, Alloc>
499        where
500            T: IStable,
501            Alloc: IStable,
502            Single<T, Alloc>: IDeterminantProvider<Vec<T, Alloc>>,
503            Vec<T, Alloc>: IStable,
504            crate::Result<Single<T, Alloc>, Vec<T, Alloc>>: IStable,
505        {
506            type Output = <[T] as core::ops::Index<$index>>::Output;
507            fn index(&self, index: $index) -> &Self::Output {
508                #[allow(clippy::indexing_slicing)]
509                &self.as_slice()[index]
510            }
511        }
512    };
513}
514
515impl<T, Alloc: IAlloc> core::ops::Deref for Vec<T, Alloc> {
516    type Target = [T];
517    fn deref(&self) -> &Self::Target {
518        self.as_slice()
519    }
520}
521impl<T, Alloc: IAlloc> core::convert::AsRef<[T]> for Vec<T, Alloc> {
522    fn as_ref(&self) -> &[T] {
523        self.as_slice()
524    }
525}
526impl<T, Alloc: IAlloc> core::ops::DerefMut for Vec<T, Alloc> {
527    fn deref_mut(&mut self) -> &mut Self::Target {
528        self.as_slice_mut()
529    }
530}
531impl<T, Alloc: IAlloc> core::convert::AsMut<[T]> for Vec<T, Alloc> {
532    fn as_mut(&mut self) -> &mut [T] {
533        self.as_slice_mut()
534    }
535}
536impl<T, Alloc: IAlloc + Default> Default for Vec<T, Alloc> {
537    fn default() -> Self {
538        Self::new_in(Alloc::default())
539    }
540}
541impl<T, Alloc: IAlloc> Drop for Vec<T, Alloc> {
542    fn drop(&mut self) {
543        unsafe { core::ptr::drop_in_place(self.as_slice_mut()) }
544        if core::mem::size_of::<T>() != 0 && self.capacity() != 0 {
545            unsafe { self.inner.start.free(&mut self.inner.alloc) }
546        }
547    }
548}
549impl<T: Copy, Alloc: IAlloc + Default> From<&[T]> for Vec<T, Alloc> {
550    fn from(value: &[T]) -> Self {
551        let mut this = Self::with_capacity(value.len());
552        this.copy_extend(value);
553        this
554    }
555}
556impl<T, Alloc: IAlloc> core::iter::Extend<T> for Vec<T, Alloc> {
557    fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
558        let iter = iter.into_iter();
559        let (min, max) = iter.size_hint();
560        match max {
561            Some(max) => {
562                self.reserve(max);
563                iter.for_each(|item| {
564                    unsafe { self.inner.end.as_ptr().write(item) };
565                    self.inner.end = ptr_add(self.inner.end, 1);
566                })
567            }
568            _ => {
569                self.reserve(min);
570                iter.for_each(|item| self.push(item))
571            }
572        }
573    }
574}
575
576impl<T, Alloc: IAlloc + Default> core::iter::FromIterator<T> for Vec<T, Alloc> {
577    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
578        let mut ret = Self::default();
579        ret.extend(iter);
580        ret
581    }
582}
583
584impl_index!(usize);
585impl_index!(core::ops::Range<usize>);
586impl_index!(core::ops::RangeInclusive<usize>);
587impl_index!(core::ops::RangeTo<usize>);
588impl_index!(core::ops::RangeToInclusive<usize>);
589impl_index!(core::ops::RangeFrom<usize>);
590impl_index!(core::ops::RangeFull);
591
592impl<T: Debug, Alloc: IAlloc> Debug for Vec<T, Alloc> {
593    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
594        self.as_slice().fmt(f)
595    }
596}
597impl<T: core::fmt::LowerHex, Alloc: IAlloc> core::fmt::LowerHex for Vec<T, Alloc> {
598    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
599        let mut first = true;
600        for item in self {
601            if !first {
602                f.write_str(":")?;
603            }
604            first = false;
605            core::fmt::LowerHex::fmt(item, f)?;
606        }
607        Ok(())
608    }
609}
610impl<T: core::fmt::UpperHex, Alloc: IAlloc> core::fmt::UpperHex for Vec<T, Alloc> {
611    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
612        let mut first = true;
613        for item in self {
614            if !first {
615                f.write_str(":")?;
616            }
617            first = false;
618            core::fmt::UpperHex::fmt(item, f)?;
619        }
620        Ok(())
621    }
622}
623impl<'a, T, Alloc: IAlloc> IntoIterator for &'a Vec<T, Alloc> {
624    type Item = &'a T;
625    type IntoIter = core::slice::Iter<'a, T>;
626    fn into_iter(self) -> Self::IntoIter {
627        self.as_slice().iter()
628    }
629}
630impl<'a, T, Alloc: IAlloc> IntoIterator for &'a mut Vec<T, Alloc> {
631    type Item = &'a mut T;
632    type IntoIter = core::slice::IterMut<'a, T>;
633    fn into_iter(self) -> Self::IntoIter {
634        self.as_slice_mut().iter_mut()
635    }
636}
637impl<T, Alloc: IAlloc> IntoIterator for Vec<T, Alloc> {
638    type Item = T;
639    type IntoIter = IntoIter<T, Alloc>;
640    fn into_iter(self) -> Self::IntoIter {
641        IntoIter {
642            vec: self,
643            index: 0,
644        }
645    }
646}
647/// [`Vec`]'s iterator.
648#[crate::stabby]
649pub struct IntoIter<T, Alloc: IAlloc> {
650    vec: Vec<T, Alloc>,
651    index: usize,
652}
653impl<T, Alloc: IAlloc> Iterator for IntoIter<T, Alloc> {
654    type Item = T;
655    fn next(&mut self) -> Option<Self::Item> {
656        (self.index < self.vec.len()).then(|| unsafe {
657            let ret = self.vec.inner.start.as_ptr().add(self.index).read();
658            self.index = self.index.wrapping_add(1);
659            ret
660        })
661    }
662}
663impl<T, Alloc: IAlloc> Drop for IntoIter<T, Alloc> {
664    fn drop(&mut self) {
665        unsafe {
666            #[allow(clippy::indexing_slicing)]
667            core::ptr::drop_in_place(&mut self.vec.as_slice_mut()[self.index..]);
668            self.vec.set_len(0);
669        }
670    }
671}
672/// An iterator that removes elements from a [`Vec`].
673///
674/// Dropping the `Drain` will finish draining its specified range.
675///
676/// Note that leaking the `Drain` may cause its [`Vec`] to lose and leak elements,
677/// even outside the specified range.
678#[crate::stabby]
679pub struct Drain<'a, T: 'a, Alloc: IAlloc + 'a> {
680    vec: &'a mut Vec<T, Alloc>,
681    from: usize,
682    to: usize,
683    index: usize,
684    original_len: usize,
685}
686impl<'a, T: 'a, Alloc: IAlloc + 'a> Drain<'a, T, Alloc> {
687    /// Prevents `self` from draining its vector any further, and applies the already
688    /// commited drain.
689    pub fn stop(mut self) {
690        self.to = self.index
691    }
692    /// Turns the drain into a double ended drain, which impls [`DoubleEndedIterator`]
693    #[rustversion::attr(since(1.86), const)]
694    pub fn double_ended(self) -> DoubleEndedDrain<'a, T, Alloc> {
695        let ret = DoubleEndedDrain {
696            vec: unsafe { core::ptr::read(&self.vec) },
697            from: self.from,
698            to: self.to,
699            original_len: self.original_len,
700            lindex: self.index,
701            rindex: self.to,
702        };
703        core::mem::forget(self);
704        ret
705    }
706}
707impl<'a, T: 'a, Alloc: IAlloc + 'a> Iterator for Drain<'a, T, Alloc> {
708    type Item = T;
709    fn size_hint(&self) -> (usize, Option<usize>) {
710        let remaining = self.to.wrapping_sub(self.index);
711        (remaining, Some(remaining))
712    }
713    fn next(&mut self) -> Option<Self::Item> {
714        (self.index < self.to).then(|| unsafe {
715            let ret = self.vec.inner.start.as_ptr().add(self.index).read();
716            self.index = self.index.wrapping_add(1);
717            ret
718        })
719    }
720}
721impl<'a, T: 'a, Alloc: IAlloc + 'a> ExactSizeIterator for Drain<'a, T, Alloc> {
722    fn len(&self) -> usize {
723        self.to.wrapping_sub(self.index)
724    }
725}
726impl<'a, T: 'a, Alloc: IAlloc + 'a> Drop for Drain<'a, T, Alloc> {
727    fn drop(&mut self) {
728        let tail_length = self.original_len.wrapping_sub(self.to);
729        unsafe {
730            core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut(
731                self.vec.inner.start.as_ptr().add(self.index),
732                self.to.wrapping_sub(self.index),
733            ));
734            core::ptr::copy(
735                self.vec.inner.start.as_ptr().add(self.to),
736                self.vec.inner.start.as_ptr().add(self.from),
737                tail_length,
738            );
739            self.vec.set_len(tail_length.wrapping_add(self.from));
740        }
741    }
742}
743/// A vector drain that works on both ends.
744#[crate::stabby]
745pub struct DoubleEndedDrain<'a, T: 'a, Alloc: IAlloc + 'a> {
746    vec: &'a mut Vec<T, Alloc>,
747    from: usize,
748    to: usize,
749    original_len: usize,
750    lindex: usize,
751    rindex: usize,
752}
753impl<'a, T: 'a, Alloc: IAlloc + 'a> Iterator for DoubleEndedDrain<'a, T, Alloc> {
754    type Item = T;
755    fn size_hint(&self) -> (usize, Option<usize>) {
756        let remaining = self.to.wrapping_sub(self.lindex);
757        (remaining, Some(remaining))
758    }
759    fn next(&mut self) -> Option<Self::Item> {
760        (self.lindex < self.rindex).then(|| unsafe {
761            let ret = self.vec.inner.start.as_ptr().add(self.lindex).read();
762            self.lindex = self.lindex.wrapping_add(1);
763            ret
764        })
765    }
766}
767impl<'a, T: 'a, Alloc: IAlloc + 'a> DoubleEndedIterator for DoubleEndedDrain<'a, T, Alloc> {
768    fn next_back(&mut self) -> Option<Self::Item> {
769        (self.lindex < self.rindex).then(|| unsafe {
770            let ret = self.vec.inner.start.as_ptr().add(self.rindex).read();
771            self.rindex = self.rindex.wrapping_sub(1);
772            ret
773        })
774    }
775}
776impl<'a, T: 'a, Alloc: IAlloc + 'a> ExactSizeIterator for DoubleEndedDrain<'a, T, Alloc> {
777    fn len(&self) -> usize {
778        self.rindex.wrapping_sub(self.lindex)
779    }
780}
781impl<'a, T: 'a, Alloc: IAlloc + 'a> Drop for DoubleEndedDrain<'a, T, Alloc> {
782    fn drop(&mut self) {
783        let tail_length = self.original_len.wrapping_sub(self.to);
784        unsafe {
785            core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut(
786                self.vec.inner.start.as_ptr().add(self.lindex),
787                self.rindex.wrapping_sub(self.lindex),
788            ));
789            core::ptr::copy(
790                self.vec.inner.start.as_ptr().add(self.to),
791                self.vec.inner.start.as_ptr().add(self.from),
792                tail_length,
793            );
794            self.vec.set_len(tail_length.wrapping_add(self.from));
795        }
796    }
797}
798#[cfg(feature = "std")]
799impl<Alloc: IAlloc> std::io::Write for Vec<u8, Alloc> {
800    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
801        match self.try_copy_extend(buf) {
802            Ok(()) => Ok(buf.len()),
803            Err(e) => Err(std::io::Error::new(std::io::ErrorKind::OutOfMemory, e)),
804        }
805    }
806
807    fn flush(&mut self) -> std::io::Result<()> {
808        Ok(())
809    }
810}
811
812#[cfg(feature = "std")]
813#[test]
814fn test() {
815    use rand::Rng;
816    const LEN: usize = 2000;
817    let mut std = std::vec::Vec::with_capacity(LEN);
818    let mut new: Vec<u8> = Vec::new();
819    let mut capacity: Vec<u8> = Vec::with_capacity(LEN);
820    let mut rng = rand::thread_rng();
821    for _ in 0..LEN {
822        let n: u8 = rng.gen();
823        new.push(n);
824        capacity.push(n);
825        std.push(n);
826    }
827    assert_eq!(new.as_slice(), std.as_slice());
828    assert_eq!(new.as_slice(), capacity.as_slice());
829    new.drain(55..100);
830    capacity.drain(55..100);
831    std.drain(55..100);
832    new.swap(5, 92);
833    std.swap(5, 92);
834    capacity.swap(5, 92);
835    assert_eq!(new.as_slice(), std.as_slice());
836    assert_eq!(new.as_slice(), capacity.as_slice());
837}
838
839pub use super::single_or_vec::SingleOrVec;
840
841#[cfg(feature = "serde")]
842mod serde_impl {
843    use super::*;
844    use crate::alloc::IAlloc;
845    use serde::{de::Visitor, Deserialize, Serialize};
846    impl<T: Serialize, Alloc: IAlloc> Serialize for Vec<T, Alloc> {
847        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
848        where
849            S: serde::Serializer,
850        {
851            let slice: &[T] = self;
852            slice.serialize(serializer)
853        }
854    }
855    impl<'a, T: Deserialize<'a>, Alloc: IAlloc + Default> Deserialize<'a> for Vec<T, Alloc> {
856        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
857        where
858            D: serde::Deserializer<'a>,
859        {
860            deserializer.deserialize_seq(VecVisitor(core::marker::PhantomData))
861        }
862    }
863    pub struct VecVisitor<T, Alloc>(core::marker::PhantomData<(T, Alloc)>);
864    impl<'a, T: Deserialize<'a>, Alloc: IAlloc + Default> Visitor<'a> for VecVisitor<T, Alloc> {
865        type Value = Vec<T, Alloc>;
866        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
867            formatter.write_str("A sequence")
868        }
869        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
870        where
871            A: serde::de::SeqAccess<'a>,
872        {
873            let mut this = Vec::with_capacity_in(seq.size_hint().unwrap_or(0), Alloc::default());
874            while let Some(v) = seq.next_element()? {
875                this.push(v);
876            }
877            Ok(this)
878        }
879    }
880}