#![expect(
clippy::semicolon_if_nothing_returned,
clippy::needless_pass_by_ref_mut,
clippy::needless_for_each,
clippy::cloned_instead_of_copied,
clippy::checked_conversions,
clippy::legacy_numeric_constants,
clippy::cast_sign_loss,
clippy::cast_possible_wrap,
clippy::swap_ptr_to_ref,
clippy::ref_as_ptr,
clippy::ptr_as_ptr,
clippy::ptr_cast_constness,
unsafe_op_in_unsafe_fn,
clippy::undocumented_unsafe_blocks
)]
#![allow(rustdoc::broken_intra_doc_links)]
use std::{
borrow::{Borrow, BorrowMut},
cmp::Ordering,
fmt,
hash::{self, Hash},
hint::assert_unchecked,
iter::FusedIterator,
marker::PhantomData,
mem,
ops::{
self,
Bound::{Excluded, Included, Unbounded},
Index, IndexMut, RangeBounds,
},
ptr::{self, NonNull},
slice::{self, SliceIndex},
};
use oxc_data_structures::assert_unchecked;
use crate::alloc::Alloc;
mod raw_vec;
use raw_vec::{AllocError, RawVec};
unsafe fn arith_offset<T>(p: *const T, offset: isize) -> *const T {
p.offset(offset)
}
fn partition_dedup_by<T, F>(s: &mut [T], mut same_bucket: F) -> (&mut [T], &mut [T])
where
F: FnMut(&mut T, &mut T) -> bool,
{
let len = s.len();
if len <= 1 {
return (s, &mut []);
}
let ptr = s.as_mut_ptr();
let mut next_read: usize = 1;
let mut next_write: usize = 1;
unsafe {
while next_read < len {
let ptr_read = ptr.add(next_read);
let prev_ptr_write = ptr.add(next_write - 1);
if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
if next_read != next_write {
let ptr_write = prev_ptr_write.add(1);
mem::swap(&mut *ptr_read, &mut *ptr_write);
}
next_write += 1;
}
next_read += 1;
}
}
s.split_at_mut(next_write)
}
unsafe fn offset_from<T>(p: *const T, origin: *const T) -> isize
where
T: Sized,
{
let pointee_size = size_of::<T>();
assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
let d = isize::wrapping_sub(p as _, origin as _);
d / (pointee_size as isize)
}
#[repr(transparent)]
pub struct Vec<'a, T: 'a, A: Alloc> {
buf: RawVec<'a, T, A>,
}
impl<'a, T: 'a, A: Alloc> Vec<'a, T, A> {
#[inline]
pub fn new_in(alloc: &'a A) -> Vec<'a, T, A> {
Vec { buf: RawVec::new_in(alloc) }
}
#[inline]
pub fn with_capacity_in(capacity: usize, alloc: &'a A) -> Vec<'a, T, A> {
Vec { buf: RawVec::with_capacity_in(capacity, alloc) }
}
pub fn from_iter_in<I: IntoIterator<Item = T>>(iter: I, alloc: &'a A) -> Vec<'a, T, A> {
let mut v = Vec::new_in(alloc);
v.extend(iter);
v
}
pub unsafe fn from_raw_parts_in(
ptr: *mut T,
length: usize,
capacity: usize,
alloc: &'a A,
) -> Vec<'a, T, A> {
Vec { buf: RawVec::from_raw_parts_in(ptr, length, capacity, alloc) }
}
#[inline]
pub fn len(&self) -> usize {
self.buf.len_usize()
}
#[inline]
fn len_usize(&self) -> usize {
self.buf.len_usize()
}
#[inline]
fn len_u32(&self) -> u32 {
self.buf.len_u32()
}
#[inline]
pub fn capacity(&self) -> usize {
self.buf.capacity_usize()
}
#[inline]
fn capacity_usize(&self) -> usize {
self.buf.capacity_usize()
}
#[inline]
fn capacity_u32(&self) -> u32 {
self.buf.capacity_u32()
}
#[inline]
pub unsafe fn set_len(&mut self, new_len: usize) {
#[expect(clippy::cast_possible_truncation)]
let new_len = new_len as u32;
self.buf.set_len(new_len);
}
pub fn reserve(&mut self, additional: usize) {
self.buf.reserve(self.len_u32(), additional);
}
pub fn reserve_exact(&mut self, additional: usize) {
self.buf.reserve_exact(self.len_u32(), additional);
}
pub fn try_reserve(&mut self, additional: usize) -> Result<(), AllocError> {
self.buf.try_reserve(self.len_u32(), additional)
}
pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), AllocError> {
self.buf.try_reserve_exact(self.len_u32(), additional)
}
pub fn shrink_to_fit(&mut self) {
if self.len_u32() != self.capacity_u32() {
self.buf.shrink_to_fit(self.len_u32());
}
}
pub fn into_bump_slice(self) -> &'a [T] {
unsafe {
let ptr = self.as_ptr();
let len = self.len_usize();
slice::from_raw_parts(ptr, len)
}
}
pub fn into_bump_slice_mut(mut self) -> &'a mut [T] {
let ptr = self.as_mut_ptr();
let len = self.len_usize();
unsafe { slice::from_raw_parts_mut(ptr, len) }
}
pub fn truncate(&mut self, len: usize) {
let current_len = self.len_usize();
if len < current_len {
unsafe { self.set_len(len) };
}
}
#[inline]
pub fn as_slice(&self) -> &[T] {
self
}
#[inline]
pub fn as_mut_slice(&mut self) -> &mut [T] {
self
}
#[inline]
pub fn as_ptr(&self) -> *const T {
let ptr = self.buf.ptr();
unsafe { assert_unchecked(!ptr.is_null()) };
ptr
}
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut T {
let ptr = self.buf.ptr();
unsafe { assert_unchecked(!ptr.is_null()) };
ptr
}
#[inline]
pub fn swap_remove(&mut self, index: usize) -> T {
unsafe {
let hole: *mut T = &raw mut self[index];
let last = ptr::read(self.get_unchecked(self.len_usize() - 1));
self.buf.decrease_len(1);
ptr::replace(hole, last)
}
}
pub fn insert(&mut self, index: usize, element: T) {
let len = self.len_usize();
assert!(index <= len);
if self.len_u32() == self.capacity_u32() {
self.buf.grow_one();
}
unsafe {
{
let p = self.as_mut_ptr().add(index);
ptr::copy(p, p.add(1), len - index);
ptr::write(p, element);
}
self.buf.increase_len(1);
}
}
pub fn remove(&mut self, index: usize) -> T {
let len = self.len_usize();
assert!(index < len);
unsafe {
let ret;
{
let ptr = self.as_mut_ptr().add(index);
ret = ptr::read(ptr);
ptr::copy(ptr.add(1), ptr, len - index - 1);
}
self.set_len(len - 1);
ret
}
}
pub fn retain<F>(&mut self, mut f: F)
where
F: FnMut(&T) -> bool,
{
self.retain_mut(|x| f(x));
}
#[expect(clippy::items_after_statements, clippy::redundant_else)]
pub fn retain_mut<F>(&mut self, mut f: F)
where
F: FnMut(&mut T) -> bool,
{
let original_len = self.len_usize();
if original_len == 0 {
return;
}
unsafe { self.set_len(0) };
struct BackshiftOnDrop<'a, 'v, T, A: Alloc> {
v: &'v mut Vec<'a, T, A>,
processed_len: usize,
deleted_cnt: usize,
original_len: usize,
}
impl<T, A: Alloc> Drop for BackshiftOnDrop<'_, '_, T, A> {
fn drop(&mut self) {
if self.deleted_cnt > 0 {
unsafe {
ptr::copy(
self.v.as_ptr().add(self.processed_len),
self.v.as_mut_ptr().add(self.processed_len - self.deleted_cnt),
self.original_len - self.processed_len,
);
}
}
unsafe {
self.v.set_len(self.original_len - self.deleted_cnt);
}
}
}
let mut g = BackshiftOnDrop { v: self, processed_len: 0, deleted_cnt: 0, original_len };
fn process_loop<F, T, A: Alloc, const DELETED: bool>(
original_len: usize,
f: &mut F,
g: &mut BackshiftOnDrop<'_, '_, T, A>,
) where
F: FnMut(&mut T) -> bool,
{
while g.processed_len != original_len {
let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) };
if !f(cur) {
g.processed_len += 1;
g.deleted_cnt += 1;
unsafe { ptr::drop_in_place(cur) };
if DELETED {
continue;
} else {
break;
}
}
if DELETED {
unsafe {
let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt);
ptr::copy_nonoverlapping(cur, hole_slot, 1);
}
}
g.processed_len += 1;
}
}
process_loop::<F, T, A, false>(original_len, &mut f, &mut g);
process_loop::<F, T, A, true>(original_len, &mut f, &mut g);
drop(g);
}
pub fn drain_filter<'v, F>(&'v mut self, filter: F) -> DrainFilter<'a, 'v, T, A, F>
where
F: FnMut(&mut T) -> bool,
{
let old_len = self.len_usize();
unsafe {
self.set_len(0);
}
DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter }
}
#[inline]
pub fn dedup_by_key<F, K>(&mut self, mut key: F)
where
F: FnMut(&mut T) -> K,
K: PartialEq,
{
self.dedup_by(|a, b| key(a) == key(b))
}
pub fn dedup_by<F>(&mut self, same_bucket: F)
where
F: FnMut(&mut T, &mut T) -> bool,
{
let len = {
let (dedup, _) = partition_dedup_by(self.as_mut_slice(), same_bucket);
dedup.len()
};
self.truncate(len);
}
#[inline]
pub fn push(&mut self, value: T) {
if self.len_u32() == self.capacity_u32() {
self.buf.grow_one();
}
unsafe {
let end = self.buf.ptr().add(self.len_usize());
ptr::write(end, value);
self.buf.increase_len(1);
}
}
#[inline]
pub fn push_fast(&mut self, value: T) {
#[expect(clippy::if_not_else)]
if self.len_u32() != self.capacity_u32() {
unsafe {
let end = self.buf.ptr().add(self.len_usize());
ptr::write(end, value);
self.buf.increase_len(1);
}
} else {
#[cold]
#[inline(never)]
fn push_slow<T, A: Alloc>(v: &mut Vec<'_, T, A>, value: T) {
v.buf.grow_one();
unsafe {
let end = v.buf.ptr().add(v.len_usize());
ptr::write(end, value);
v.buf.increase_len(1);
}
}
push_slow(self, value);
}
}
#[inline]
pub fn pop(&mut self) -> Option<T> {
if self.len_u32() == 0 {
None
} else {
unsafe {
self.buf.decrease_len(1);
Some(ptr::read(self.as_ptr().add(self.len_usize())))
}
}
}
#[inline]
pub fn append(&mut self, other: &mut Self) {
unsafe {
self.append_elements(other.as_slice() as _);
other.set_len(0);
}
}
#[inline]
unsafe fn append_elements(&mut self, other: *const [T]) {
#[allow(clippy::needless_borrow, clippy::allow_attributes)]
let count = (&*other).len();
self.reserve(count);
let len = self.len_usize();
ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count);
#[expect(clippy::cast_possible_truncation)]
let count = count as u32;
self.buf.increase_len(count);
}
pub fn drain<R>(&mut self, range: R) -> Drain<'_, '_, T, A>
where
R: RangeBounds<usize>,
{
let len = self.len_usize();
let start = match range.start_bound() {
Included(&n) => n,
Excluded(&n) => n + 1,
Unbounded => 0,
};
let end = match range.end_bound() {
Included(&n) => n + 1,
Excluded(&n) => n,
Unbounded => len,
};
assert!(start <= end);
assert!(end <= len);
unsafe {
self.set_len(start);
let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start);
Drain {
tail_start: end,
tail_len: len - end,
iter: range_slice.iter(),
vec: NonNull::from(self),
}
}
}
#[inline]
pub fn clear(&mut self) {
self.truncate(0)
}
pub fn is_empty(&self) -> bool {
self.len_u32() == 0
}
#[inline]
#[must_use]
pub fn split_off(&mut self, at: usize) -> Self {
assert!(at <= self.len_usize(), "`at` out of bounds");
let other_len = self.len_usize() - at;
let bump = unsafe { self.buf.bump() };
let mut other = Vec::with_capacity_in(other_len, bump);
unsafe {
self.set_len(at);
other.set_len(other_len);
ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len_usize());
}
other
}
}
impl<'a, T: 'a + Clone, A: Alloc> Vec<'a, T, A> {
pub fn resize(&mut self, new_len: usize, value: T) {
let len = self.len_usize();
if new_len > len {
self.extend_with(new_len - len, ExtendElement(value))
} else {
self.truncate(new_len);
}
}
pub fn extend_from_slice(&mut self, other: &[T]) {
self.extend(other.iter().cloned())
}
}
impl<'a, T: 'a + Copy, A: Alloc> Vec<'a, T, A> {
unsafe fn extend_from_slice_copy_unchecked(&mut self, other: &[T]) {
let old_len = self.len_usize();
debug_assert!(old_len + other.len() <= self.capacity_usize());
unsafe {
let src = other.as_ptr();
let dst = self.as_mut_ptr().add(old_len);
ptr::copy_nonoverlapping(src, dst, other.len());
self.set_len(old_len + other.len());
}
}
pub fn extend_from_slice_copy(&mut self, other: &[T]) {
self.reserve(other.len());
unsafe {
self.extend_from_slice_copy_unchecked(other);
}
}
pub fn extend_from_slices_copy(&mut self, slices: &[&[T]]) {
let total_len = slices.iter().fold(0usize, |total_len, slice| {
let len = slice.len();
unsafe { assert_unchecked!(len <= (isize::MAX as usize)) };
total_len.checked_add(len).unwrap()
});
self.reserve(total_len);
unsafe {
slices.iter().for_each(|slice| {
self.extend_from_slice_copy_unchecked(slice);
});
}
}
}
trait ExtendWith<T> {
fn next(&mut self) -> T;
fn last(self) -> T;
}
struct ExtendElement<T>(T);
impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
fn next(&mut self) -> T {
self.0.clone()
}
fn last(self) -> T {
self.0
}
}
impl<'a, T: 'a, A: Alloc> Vec<'a, T, A> {
fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
self.reserve(n);
unsafe {
let mut ptr = self.as_mut_ptr().add(self.len_usize());
for _ in 1..n {
ptr::write(ptr, value.next());
ptr = ptr.add(1);
}
if n > 0 {
ptr::write(ptr, value.last());
}
#[expect(clippy::cast_possible_truncation)]
let n = n as u32;
self.buf.increase_len(n);
}
}
}
impl<'a, T: 'a + PartialEq, A: Alloc> Vec<'a, T, A> {
#[inline]
pub fn dedup(&mut self) {
self.dedup_by(|a, b| a == b)
}
}
impl<'a, T: 'a + Hash, A: Alloc> Hash for Vec<'a, T, A> {
#[inline]
fn hash<H: hash::Hasher>(&self, state: &mut H) {
Hash::hash(&**self, state)
}
}
impl<T, A: Alloc, I: SliceIndex<[T]>> Index<I> for Vec<'_, T, A> {
type Output = I::Output;
#[inline]
fn index(&self, index: I) -> &Self::Output {
Index::index(&**self, index)
}
}
impl<T, A: Alloc, I: SliceIndex<[T]>> IndexMut<I> for Vec<'_, T, A> {
#[inline]
fn index_mut(&mut self, index: I) -> &mut Self::Output {
IndexMut::index_mut(&mut **self, index)
}
}
impl<'a, T: 'a, A: Alloc> ops::Deref for Vec<'a, T, A> {
type Target = [T];
fn deref(&self) -> &[T] {
unsafe {
let p = self.buf.ptr();
slice::from_raw_parts(p, self.len_usize())
}
}
}
impl<'a, T: 'a, A: Alloc> ops::DerefMut for Vec<'a, T, A> {
fn deref_mut(&mut self) -> &mut [T] {
unsafe {
let ptr = self.buf.ptr();
slice::from_raw_parts_mut(ptr, self.len_usize())
}
}
}
impl<'a, T: 'a, A: Alloc> IntoIterator for Vec<'a, T, A> {
type Item = T;
type IntoIter = IntoIter<'a, T>;
#[inline]
fn into_iter(mut self) -> IntoIter<'a, T> {
unsafe {
let begin = self.as_mut_ptr();
let end = if size_of::<T>() == 0 {
arith_offset(begin as *const i8, self.len_u32() as isize) as *const T
} else {
begin.add(self.len_usize()) as *const T
};
IntoIter { phantom: PhantomData, ptr: begin, end }
}
}
}
impl<'a, T, A: Alloc> IntoIterator for &'a Vec<'_, T, A> {
type Item = &'a T;
type IntoIter = slice::Iter<'a, T>;
fn into_iter(self) -> slice::Iter<'a, T> {
self.iter()
}
}
impl<'a, T, A: Alloc> IntoIterator for &'a mut Vec<'_, T, A> {
type Item = &'a mut T;
type IntoIter = slice::IterMut<'a, T>;
fn into_iter(self) -> slice::IterMut<'a, T> {
self.iter_mut()
}
}
impl<'a, T: 'a, A: Alloc> Extend<T> for Vec<'a, T, A> {
#[inline]
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
let iterator = iter.into_iter();
self.extend_desugared(iterator);
}
}
impl<'a, T: 'a, A: Alloc> Vec<'a, T, A> {
#[track_caller]
fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
while let Some(element) = iterator.next() {
let len = self.len_usize();
if len == self.capacity_usize() {
#[cold]
#[inline(never)]
fn reserve_slow<T, A: Alloc>(v: &mut Vec<T, A>, iterator: &impl Iterator) {
let (lower, _) = iterator.size_hint();
v.reserve(lower.saturating_add(1));
}
reserve_slow(self, &iterator);
}
unsafe {
ptr::write(self.as_mut_ptr().add(len), element);
self.set_len(len + 1);
}
}
}
}
impl<'a, T: 'a, A: Alloc> Vec<'a, T, A> {
#[inline]
pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, '_, I::IntoIter, A>
where
R: RangeBounds<usize>,
I: IntoIterator<Item = T>,
{
Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
}
}
impl<'a, T: 'a + Copy, A: Alloc> Extend<&'a T> for Vec<'_, T, A> {
fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
self.extend(iter.into_iter().cloned())
}
}
macro_rules! __impl_slice_eq1 {
($Rhs: ty) => {
__impl_slice_eq1! { $Rhs, }
};
($Rhs: ty, $($bounds:tt)*) => {
impl<T, U, A, $($bounds)*> PartialEq<$Rhs> for Vec<'_, T, A>
where
T: PartialEq<U>,
A: Alloc,
{
#[inline]
fn eq(&self, other: &$Rhs) -> bool {
self[..] == other[..]
}
}
};
}
__impl_slice_eq1! { Vec<'_, U, A2>, A2: Alloc }
__impl_slice_eq1! { &[U] }
__impl_slice_eq1! { &mut [U] }
macro_rules! __impl_slice_eq1_array {
($Rhs: ty) => {
impl<T, U, A, const N: usize> PartialEq<$Rhs> for Vec<'_, T, A>
where
T: PartialEq<U>,
A: Alloc,
{
#[inline]
fn eq(&self, other: &$Rhs) -> bool {
self[..] == other[..]
}
}
};
}
__impl_slice_eq1_array! { [U; N] }
__impl_slice_eq1_array! { &[U; N] }
__impl_slice_eq1_array! { &mut [U; N] }
impl<'a, T: 'a + PartialOrd, A: Alloc, A2: Alloc> PartialOrd<Vec<'a, T, A2>> for Vec<'a, T, A> {
#[inline]
fn partial_cmp(&self, other: &Vec<'a, T, A2>) -> Option<Ordering> {
PartialOrd::partial_cmp(&**self, &**other)
}
}
impl<'a, T: 'a + Eq, A: Alloc> Eq for Vec<'a, T, A> {}
impl<'a, T: 'a + Ord, A: Alloc> Ord for Vec<'a, T, A> {
#[inline]
fn cmp(&self, other: &Vec<'a, T, A>) -> Ordering {
Ord::cmp(&**self, &**other)
}
}
impl<'a, T: 'a + fmt::Debug, A: Alloc> fmt::Debug for Vec<'a, T, A> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl<'a, T: 'a, A: Alloc> AsRef<Vec<'a, T, A>> for Vec<'a, T, A> {
fn as_ref(&self) -> &Vec<'a, T, A> {
self
}
}
impl<'a, T: 'a, A: Alloc> AsMut<Vec<'a, T, A>> for Vec<'a, T, A> {
fn as_mut(&mut self) -> &mut Vec<'a, T, A> {
self
}
}
impl<'a, T: 'a, A: Alloc> AsRef<[T]> for Vec<'a, T, A> {
fn as_ref(&self) -> &[T] {
self
}
}
impl<'a, T: 'a, A: Alloc> AsMut<[T]> for Vec<'a, T, A> {
fn as_mut(&mut self) -> &mut [T] {
self
}
}
impl<'a, T: 'a, A: Alloc> Borrow<[T]> for Vec<'a, T, A> {
#[inline]
fn borrow(&self) -> &[T] {
&self[..]
}
}
impl<'a, T: 'a, A: Alloc> BorrowMut<[T]> for Vec<'a, T, A> {
#[inline]
fn borrow_mut(&mut self) -> &mut [T] {
&mut self[..]
}
}
pub struct IntoIter<'a, T> {
phantom: PhantomData<&'a [T]>,
ptr: *const T,
end: *const T,
}
impl<T: fmt::Debug> fmt::Debug for IntoIter<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
}
}
impl<'a, T: 'a> IntoIter<'a, T> {
pub fn as_slice(&self) -> &[T] {
unsafe { slice::from_raw_parts(self.ptr, self.len()) }
}
pub fn as_mut_slice(&mut self) -> &mut [T] {
unsafe { slice::from_raw_parts_mut(self.ptr as *mut T, self.len()) }
}
}
unsafe impl<T: Send> Send for IntoIter<'_, T> {}
unsafe impl<T: Sync> Sync for IntoIter<'_, T> {}
impl<'a, T: 'a> Iterator for IntoIter<'a, T> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
unsafe {
if self.ptr == self.end {
None
} else if size_of::<T>() == 0 {
self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
Some(mem::zeroed())
} else {
let old = self.ptr;
self.ptr = self.ptr.add(1);
Some(ptr::read(old))
}
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let exact = if size_of::<T>() == 0 {
(self.end as usize).wrapping_sub(self.ptr as usize)
} else {
unsafe { offset_from(self.end, self.ptr) as usize }
};
(exact, Some(exact))
}
#[inline]
fn count(self) -> usize {
self.len()
}
}
impl<'a, T: 'a> DoubleEndedIterator for IntoIter<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<T> {
unsafe {
if self.end == self.ptr {
None
} else if size_of::<T>() == 0 {
self.end = arith_offset(self.end as *const i8, -1) as *mut T;
Some(mem::zeroed())
} else {
self.end = self.end.sub(1);
Some(ptr::read(self.end))
}
}
}
}
impl<'a, T: 'a> ExactSizeIterator for IntoIter<'a, T> {}
impl<'a, T: 'a> FusedIterator for IntoIter<'a, T> {}
impl<T> Drop for IntoIter<'_, T> {
fn drop(&mut self) {
self.for_each(drop);
}
}
pub struct Drain<'a, 's, T: 'a + 's, A: Alloc> {
tail_start: usize,
tail_len: usize,
iter: slice::Iter<'s, T>,
vec: NonNull<Vec<'a, T, A>>,
}
impl<'a, 's, T: 'a + 's + fmt::Debug, A: Alloc> fmt::Debug for Drain<'a, 's, T, A> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
}
}
unsafe impl<T: Sync, A: Alloc> Sync for Drain<'_, '_, T, A> {}
unsafe impl<T: Send, A: Alloc> Send for Drain<'_, '_, T, A> {}
impl<T, A: Alloc> Iterator for Drain<'_, '_, T, A> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<T, A: Alloc> DoubleEndedIterator for Drain<'_, '_, T, A> {
#[inline]
fn next_back(&mut self) -> Option<T> {
self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
}
}
impl<T, A: Alloc> Drop for Drain<'_, '_, T, A> {
fn drop(&mut self) {
self.for_each(drop);
if self.tail_len > 0 {
unsafe {
let source_vec = self.vec.as_mut();
let start = source_vec.len_usize();
let tail = self.tail_start;
if tail != start {
let src = source_vec.as_ptr().add(tail);
let dst = source_vec.as_mut_ptr().add(start);
ptr::copy(src, dst, self.tail_len);
}
source_vec.set_len(start + self.tail_len);
}
}
}
}
impl<T, A: Alloc> ExactSizeIterator for Drain<'_, '_, T, A> {}
impl<T, A: Alloc> FusedIterator for Drain<'_, '_, T, A> {}
#[derive(Debug)]
pub struct Splice<'a, 'd, I: Iterator + 'a + 'd, A: Alloc> {
drain: Drain<'a, 'd, I::Item, A>,
replace_with: I,
}
impl<I: Iterator, A: Alloc> Iterator for Splice<'_, '_, I, A> {
type Item = I::Item;
fn next(&mut self) -> Option<Self::Item> {
self.drain.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.drain.size_hint()
}
}
impl<I: Iterator, A: Alloc> DoubleEndedIterator for Splice<'_, '_, I, A> {
fn next_back(&mut self) -> Option<Self::Item> {
self.drain.next_back()
}
}
impl<I: Iterator, A: Alloc> ExactSizeIterator for Splice<'_, '_, I, A> {}
impl<I: Iterator, A: Alloc> Drop for Splice<'_, '_, I, A> {
fn drop(&mut self) {
self.drain.by_ref().for_each(drop);
unsafe {
if self.drain.tail_len == 0 {
self.drain.vec.as_mut().extend(self.replace_with.by_ref());
return;
}
if !self.drain.fill(&mut self.replace_with) {
return;
}
let (lower_bound, _upper_bound) = self.replace_with.size_hint();
if lower_bound > 0 {
self.drain.move_tail(lower_bound);
if !self.drain.fill(&mut self.replace_with) {
return;
}
}
let bump = self.drain.vec.as_ref().buf.bump();
let mut collected = Vec::new_in(bump);
collected.extend(self.replace_with.by_ref());
let mut collected = collected.into_iter();
if collected.len() > 0 {
self.drain.move_tail(collected.len());
let filled = self.drain.fill(&mut collected);
debug_assert!(filled);
debug_assert_eq!(collected.len(), 0);
}
}
}
}
impl<T, A: Alloc> Drain<'_, '_, T, A> {
unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool {
let vec = self.vec.as_mut();
let range_start = vec.len_usize();
let range_end = self.tail_start;
let range_slice =
slice::from_raw_parts_mut(vec.as_mut_ptr().add(range_start), range_end - range_start);
for place in range_slice {
if let Some(new_item) = replace_with.next() {
ptr::write(place, new_item);
vec.buf.increase_len(1);
} else {
return false;
}
}
true
}
unsafe fn move_tail(&mut self, extra_capacity: usize) {
let vec = self.vec.as_mut();
let used_capacity = self.tail_start + self.tail_len;
#[expect(clippy::cast_possible_truncation)]
let used_capacity = used_capacity as u32;
vec.buf.reserve(used_capacity, extra_capacity);
let new_tail_start = self.tail_start + extra_capacity;
let src = vec.as_ptr().add(self.tail_start);
let dst = vec.as_mut_ptr().add(new_tail_start);
ptr::copy(src, dst, self.tail_len);
self.tail_start = new_tail_start;
}
}
#[derive(Debug)]
pub struct DrainFilter<'a: 'v, 'v, T: 'a + 'v, A: Alloc, F>
where
F: FnMut(&mut T) -> bool,
{
vec: &'v mut Vec<'a, T, A>,
idx: usize,
del: usize,
old_len: usize,
pred: F,
}
impl<T, A: Alloc, F> Iterator for DrainFilter<'_, '_, T, A, F>
where
F: FnMut(&mut T) -> bool,
{
type Item = T;
fn next(&mut self) -> Option<T> {
unsafe {
while self.idx != self.old_len {
let i = self.idx;
self.idx += 1;
let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
if (self.pred)(&mut v[i]) {
self.del += 1;
return Some(ptr::read(&raw const v[i]));
} else if self.del > 0 {
let del = self.del;
let src: *const T = &raw const v[i];
let dst: *mut T = &raw mut v[i - del];
ptr::copy_nonoverlapping(src, dst, 1);
}
}
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some(self.old_len - self.idx))
}
}
impl<T, A: Alloc, F> Drop for DrainFilter<'_, '_, T, A, F>
where
F: FnMut(&mut T) -> bool,
{
fn drop(&mut self) {
self.for_each(drop);
unsafe {
self.vec.set_len(self.old_len - self.del);
}
}
}