use crate::PartialArray;
use core::fmt::{self, Debug, Formatter};
use core::iter::FusedIterator;
use core::mem::{self, MaybeUninit};
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
pub struct IntoIter<T, const N: usize> {
array: [MaybeUninit<T>; N],
filled: usize,
read: usize,
}
impl<T, const N: usize> IntoIter<T, N> {
pub(crate) fn new(array: PartialArray<T, N>) -> Self {
let mut array = mem::ManuallyDrop::new(array);
let uninit = [PartialArray::<T, N>::UNINIT; N];
Self {
array: mem::replace(&mut array.array, uninit),
filled: array.filled,
read: 0,
}
}
}
impl<T: Debug, const N: usize> Debug for IntoIter<T, N> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let slice = &self.array[self.read..self.filled];
let slice = unsafe { mem::transmute(slice) };
<[T] as Debug>::fmt(slice, f)
}
}
impl<T, const N: usize> Iterator for IntoIter<T, N> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if self.read != self.filled {
let value = mem::replace(&mut self.array[self.read], PartialArray::<_, N>::UNINIT);
self.read += 1;
Some(unsafe { value.assume_init() })
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.filled - self.read;
(len, Some(len))
}
}
impl<T, const N: usize> DoubleEndedIterator for IntoIter<T, N> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.read != self.filled && self.filled > 0 {
self.filled -= 1;
let value = mem::replace(&mut self.array[self.filled], PartialArray::<_, N>::UNINIT);
Some(unsafe { value.assume_init() })
} else {
None
}
}
}
impl<T, const N: usize> FusedIterator for IntoIter<T, N> {}
impl<T, const N: usize> ExactSizeIterator for IntoIter<T, N> {}
impl<T, const N: usize> Drop for IntoIter<T, N> {
fn drop(&mut self) {
self.for_each(drop);
}
}