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