Skip to content

Commit

Permalink
add slice_chunks
Browse files Browse the repository at this point in the history
  • Loading branch information
ngtkana committed Dec 13, 2024
1 parent a5bed60 commit 4709928
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
2 changes: 2 additions & 0 deletions libs/riff/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ mod bitmask_operations;
mod change_min_max;
mod numeric_traits;
mod pop_if;
mod slice_chunks;

pub use binary_search::BinarySearch;
pub use bitmask_iterators::bitmask_combinations;
Expand All @@ -14,3 +15,4 @@ pub use bitmask_operations::i2powm1;
pub use change_min_max::ChangeMinMax;
pub use numeric_traits::Unsigned;
pub use pop_if::PopIf;
pub use slice_chunks::SliceChunks;
44 changes: 44 additions & 0 deletions libs/riff/src/slice_chunks.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/// A trait for slices.
pub trait SliceChunks {
type Item;
/// Groups adjacent elements by a predicate.
/// (Rust 1.77.0)
fn chunk_by<F>(&self, f: F) -> SliceChunkBy<'_, Self::Item, F>
where
F: FnMut(&Self::Item, &Self::Item) -> bool;
}
impl<T> SliceChunks for [T] {
type Item = T;

fn chunk_by<F>(&self, f: F) -> SliceChunkBy<'_, Self::Item, F>
where
F: FnMut(&Self::Item, &Self::Item) -> bool,
{
SliceChunkBy { a: self, f }
}
}

pub struct SliceChunkBy<'a, T, F> {
a: &'a [T],
f: F,
}
impl<'a, T, F> Iterator for SliceChunkBy<'a, T, F>
where
F: FnMut(&T, &T) -> bool,
{
type Item = &'a [T];

fn next(&mut self) -> Option<Self::Item> {
let Self { a, f } = self;
if a.is_empty() {
return None;
}
let mut end = 1;
while end < a.len() && f(&a[end - 1], &a[end]) {
end += 1;
}
let (prefix, rest) = a.split_at(end);
self.a = rest;
Some(prefix)
}
}

0 comments on commit 4709928

Please sign in to comment.