use itertools::Itertools;
pub trait IterExtensions: Iterator {
fn reusable_format(self, sep: &str) -> ReusableIterFormat<'_, Self>
where
Self: Sized,
{
ReusableIterFormat::new(self.format(sep))
}
fn rle_cumulative(self) -> impl Iterator<Item = (usize, Self::Item)>
where
Self: Sized,
Self::Item: PartialEq,
{
let mut cumulative: usize = 0;
self.dedup_with_count().map(move |(count, value)| {
cumulative += count;
(cumulative, value)
})
}
}
pub trait IterExtensionsRle<T>: Iterator<Item = (usize, T)>
where
T: Clone,
{
fn expand_rle(self) -> impl Iterator<Item = T>
where
Self: Sized,
{
self.scan(0usize, |prev, (cum, item)| {
let count = cum.checked_sub(*prev).filter(|&c| c > 0).expect("cumulative counts must be strictly increasing");
*prev = cum;
Some((count, item))
})
.flat_map(|(count, item)| core::iter::repeat_n(item, count))
}
}
impl<I, T> IterExtensionsRle<T> for I
where
I: Iterator<Item = (usize, T)>,
T: Clone,
{
}
impl<T: ?Sized> IterExtensions for T where T: Iterator {}
pub struct ReusableIterFormat<'a, I> {
inner: itertools::Format<'a, I>,
}
impl<'a, I> ReusableIterFormat<'a, I> {
pub fn new(inner: itertools::Format<'a, I>) -> Self {
Self { inner }
}
}
impl<I> core::fmt::Display for ReusableIterFormat<'_, I>
where
I: core::clone::Clone,
I: Iterator,
I::Item: core::fmt::Display,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
self.inner.clone().fmt(f)
}
}
impl<I> core::fmt::Debug for ReusableIterFormat<'_, I>
where
I: core::clone::Clone,
I: Iterator,
I::Item: core::fmt::Debug,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
self.inner.clone().fmt(f)
}
}
#[cfg(feature = "std")]
pub fn parallelism_in_power_steps() -> impl Iterator<Item = usize> {
(1..=(std::thread::available_parallelism().unwrap().get() as f64).log2().ceil() as u32).map(|x| 2usize.pow(x))
}