-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
/// A trait for slices. | ||
pub trait SliceExt { | ||
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> SliceExt 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) | ||
} | ||
} |