#![cfg(feature = "panic-on-alloc")]
use core::{
fmt::{self, Debug},
iter::FusedIterator,
mem,
ptr::{self, NonNull},
slice::{self},
};
use crate::{BumpVec, SizedTypeProperties, traits::BumpAllocatorTyped};
pub struct Drain<'a, T: 'a, A: BumpAllocatorTyped> {
pub(super) tail_start: usize,
pub(super) tail_len: usize,
pub(super) iter: slice::Iter<'a, T>,
pub(super) vec: NonNull<BumpVec<T, A>>,
}
impl<T: Debug, A: BumpAllocatorTyped> Debug for Drain<'_, T, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
}
}
impl<T, A: BumpAllocatorTyped> Drain<'_, T, A> {
#[must_use]
#[inline(always)]
pub fn as_slice(&self) -> &[T] {
self.iter.as_slice()
}
}
impl<T, A: BumpAllocatorTyped> AsRef<[T]> for Drain<'_, T, A> {
#[inline(always)]
fn as_ref(&self) -> &[T] {
self.as_slice()
}
}
impl<T, A: BumpAllocatorTyped> Iterator for Drain<'_, T, A> {
type Item = T;
#[inline(always)]
fn next(&mut self) -> Option<T> {
self.iter.next().map(|elt| unsafe { ptr::read(elt) })
}
#[inline(always)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<T, A: BumpAllocatorTyped> DoubleEndedIterator for Drain<'_, T, A> {
#[inline(always)]
fn next_back(&mut self) -> Option<T> {
self.iter.next_back().map(|elt| unsafe { ptr::read(elt) })
}
}
impl<T, A: BumpAllocatorTyped> Drop for Drain<'_, T, A> {
#[inline]
fn drop(&mut self) {
struct DropGuard<'r, 'a, T, A: BumpAllocatorTyped>(&'r mut Drain<'a, T, A>);
impl<T, A: BumpAllocatorTyped> Drop for DropGuard<'_, '_, T, A> {
fn drop(&mut self) {
if self.0.tail_len > 0 {
unsafe {
let source_vec = self.0.vec.as_mut();
let start = source_vec.len();
let tail = self.0.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.0.tail_len);
}
source_vec.set_len(start + self.0.tail_len);
}
}
}
}
let iter = mem::replace(&mut self.iter, [].iter());
let drop_len = iter.len();
let mut vec = self.vec;
if T::IS_ZST {
unsafe {
let vec = vec.as_mut();
let old_len = vec.len();
vec.set_len(old_len + drop_len + self.tail_len);
vec.truncate(old_len + self.tail_len);
}
return;
}
let _guard = DropGuard(self);
if drop_len == 0 {
return;
}
let drop_ptr = iter.as_slice().as_ptr();
#[expect(clippy::cast_sign_loss)]
unsafe {
let vec_ptr = vec.as_mut().as_mut_ptr();
let drop_offset = drop_ptr.offset_from(vec_ptr) as usize;
let to_drop = ptr::slice_from_raw_parts_mut(vec_ptr.add(drop_offset), drop_len);
ptr::drop_in_place(to_drop);
}
}
}
impl<T, A: BumpAllocatorTyped> ExactSizeIterator for Drain<'_, T, A> {}
impl<T, A: BumpAllocatorTyped> FusedIterator for Drain<'_, T, A> {}