Skip to main content

music21/stream/
iterator.rs

1//! What music21's `stream.iterator` decides that is not about Python
2//! objects: how `OffsetIterator` groups what it walks.
3
4use std::ops::Range;
5
6/// The runs of neighbours standing at one offset, as music21's
7/// `OffsetIterator` hands them out: each run the positions of elements
8/// next to one another in walking order whose offsets are equal. Two
9/// elements at one offset with another between them are two runs.
10///
11/// ```
12/// use music21::stream::iterator::offset_runs;
13///
14/// assert_eq!(offset_runs(&[0.0, 0.0, 1.0, 2.0, 2.0]), vec![0..2, 2..3, 3..5]);
15/// assert!(offset_runs(&[]).is_empty());
16/// ```
17pub fn offset_runs(offsets: &[f64]) -> Vec<Range<usize>> {
18    let mut runs = Vec::new();
19    let mut start = 0;
20    for at in 1..=offsets.len() {
21        if at == offsets.len() || offsets[at] != offsets[start] {
22            runs.push(start..at);
23            start = at;
24        }
25    }
26    runs
27}
28
29#[cfg(test)]
30mod tests {
31    use super::offset_runs;
32
33    /// An offset met again after another starts a run of its own.
34    #[test]
35    fn offset_met_again_is_a_new_run() {
36        assert_eq!(offset_runs(&[1.0, 2.0, 1.0]), vec![0..1, 1..2, 2..3]);
37    }
38
39    /// One element is one run.
40    #[test]
41    fn one_element_is_one_run() {
42        assert_eq!(offset_runs(&[3.5]), vec![0..1]);
43    }
44}