2023-09-17

How do you iterate over continuous subsequences of a slice that contain equal elements?

I have a sequence of elements of a type which implements PartialEq in a slice. For illustration, let's say it looks like this:

let data = [1,1,1,2,2,3,4,5,5,5,5,6];

I would like to iterate over borrowed slices of this sequence such that all elements of such slices are equal as per PartialEq. For example in the above slice data I would like an iterator which yields:

&data[0..3]   // [1,1,1]
&data[3..5]   // [2,2]
&data[5..6]   // [3]
&data[6..7]   // [4]
&data[7..11]  // [5,5,5,5]
&data[11..12] // [6]

It looks like slice::group_by is exactly what I need, but as of Rust 1.72.0, it is not yet stable. Is there any straightforward way to get this functionality in a stable way, either by use of a 3rd party crate or by combining the use of stable std lib APIs?



No comments:

Post a Comment