use crate::intrinsics::{assert_unsafe_precondition, unchecked_add, unchecked_sub};
use crate::iter::{FusedIterator, TrustedLen};
use crate::num::NonZeroUsize;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct IndexRange {
start: usize,
end: usize,
}
impl IndexRange {
#[inline]
pub const unsafe fn new_unchecked(start: usize, end: usize) -> Self {
unsafe {
assert_unsafe_precondition!(
"IndexRange::new_unchecked requires `start <= end`",
(start: usize, end: usize) => start <= end
)
};
IndexRange { start, end }
}
#[inline]
pub const fn zero_to(end: usize) -> Self {
IndexRange { start: 0, end }
}
#[inline]
pub const fn start(&self) -> usize {
self.start
}
#[inline]
pub const fn end(&self) -> usize {
self.end
}
#[inline]
pub const fn len(&self) -> usize {
unsafe { unchecked_sub(self.end, self.start) }
}
#[inline]
unsafe fn next_unchecked(&mut self) -> usize {
debug_assert!(self.start < self.end);
let value = self.start;
self.start = unsafe { unchecked_add(value, 1) };
value
}
#[inline]
unsafe fn next_back_unchecked(&mut self) -> usize {
debug_assert!(self.start < self.end);
let value = unsafe { unchecked_sub(self.end, 1) };
self.end = value;
value
}
#[inline]
pub fn take_prefix(&mut self, n: usize) -> Self {
let mid = if n <= self.len() {
unsafe { unchecked_add(self.start, n) }
} else {
self.end
};
let prefix = Self { start: self.start, end: mid };
self.start = mid;
prefix
}
#[inline]
pub fn take_suffix(&mut self, n: usize) -> Self {
let mid = if n <= self.len() {
unsafe { unchecked_sub(self.end, n) }
} else {
self.start
};
let suffix = Self { start: mid, end: self.end };
self.end = mid;
suffix
}
}
impl Iterator for IndexRange {
type Item = usize;
#[inline]
fn next(&mut self) -> Option<usize> {
if self.len() > 0 {
unsafe { Some(self.next_unchecked()) }
} else {
None
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
(len, Some(len))
}
#[inline]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> {
let taken = self.take_prefix(n);
NonZeroUsize::new(n - taken.len()).map_or(Ok(()), Err)
}
}
impl DoubleEndedIterator for IndexRange {
#[inline]
fn next_back(&mut self) -> Option<usize> {
if self.len() > 0 {
unsafe { Some(self.next_back_unchecked()) }
} else {
None
}
}
#[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> {
let taken = self.take_suffix(n);
NonZeroUsize::new(n - taken.len()).map_or(Ok(()), Err)
}
}
impl ExactSizeIterator for IndexRange {
#[inline]
fn len(&self) -> usize {
self.len()
}
}
unsafe impl TrustedLen for IndexRange {}
impl FusedIterator for IndexRange {}