Skip to main content

music21/
stream.rs

1//! Music on a timeline: music21's `stream.Stream` and the subclasses it
2//! nests inside one another.
3//!
4//! A [`Stream`] is a list of things at quarter-length offsets, and one of
5//! those things may be another stream: a score holds parts, a part holds
6//! measures, a measure holds voices and notes. [`Stream::flatten`] dissolves
7//! that nesting into one timeline the way music21's does, adding each
8//! stream's own offset to its contents'.
9//!
10//! **What is deliberately not here is music21's *sites*.** There an object
11//! can sit in several streams at once and carry a different offset in each,
12//! which is why it needs a back-reference to every stream holding it and why
13//! `getContextByClass` has a graph to walk. A stream here *owns* what it
14//! holds, so the nesting is a tree; asking what key or metre is in force at
15//! an offset is then a backwards look through the flattened timeline rather
16//! than a search through a graph. That is the same answer for music that is
17//! written once, which is all a stream built here can be.
18//!
19//! Where an element sits is asked for, not stored: [`Stream::placed`]
20//! answers each element with its offset, its measure offset and the key,
21//! metre and tempo in force, as one [`Placed`](crate::stream::Placed) value. music21's author
22//! names keeping objects and sites apart this way as what he would do
23//! again.
24
25mod analyze;
26pub(crate) mod chordify;
27mod classes;
28mod consecutive;
29mod editing;
30mod ends;
31pub mod enums;
32pub(crate) mod exact;
33mod filling;
34pub mod iterator;
35mod lookups;
36mod lyrics;
37mod opus;
38mod placed;
39mod queries;
40mod repeats;
41mod seconds;
42mod selection;
43mod slicing;
44mod sounding;
45mod span;
46mod splitting;
47pub mod status;
48mod template;
49mod ties;
50mod voices;
51
52pub use analyze::Analysis;
53pub use chordify::ChordifyOptions;
54pub use consecutive::{ConsecutiveOptions, MelodicInterval};
55pub use editing::Anchor;
56pub use lyrics::{LyricsOptions, SungAt, SungLyric, SungPlace};
57pub use placed::Placed;
58pub use queries::OffsetMapEntry;
59pub use repeats::Expander;
60pub use seconds::TempoSpan;
61pub use span::OffsetSpan;
62pub use splitting::InForce;
63pub use template::{TemplateOptions, removed_by_default};
64pub use voices::VoiceAllocation;
65
66use crate::{
67    bar::{Barline, Ending},
68    chord::Chord,
69    chordsymbol::ChordSymbol,
70    clef::Clef,
71    defaults::{FloatType, IntegerType},
72    duration::Duration,
73    dynamics::Dynamic,
74    error::Result,
75    expressions::{RehearsalMark, TextExpression},
76    instrument::Instrument,
77    interval::Interval,
78    key::{Key, KeySignature},
79    metadata::Metadata,
80    meter::TimeSignature,
81    note::Note,
82    percussion::{PercussionChord, Unpitched},
83    pitch::Pitch,
84    repeat::RepeatExpression,
85    rest::Rest,
86    spanner::{PedalObject, Spanner},
87    tempo::{MetricModulation, MetronomeMark, TempoText},
88};
89
90/// Which of music21's `Stream` subclasses a stream stands for.
91///
92/// music21 makes each of these a class of its own; they carry no behaviour
93/// that a tag does not, and a tag is what the filters here need.
94#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
95#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
96#[non_exhaustive]
97pub enum StreamKind {
98    /// A stream with no particular role: music21's `Stream`.
99    #[default]
100    Stream,
101    /// One independent line inside a measure.
102    Voice,
103    /// One bar.
104    Measure,
105    /// One instrument's line through the piece.
106    Part,
107    /// One staff of a part written on several.
108    PartStaff,
109    /// One line of a page's staves: music21's `System`, which only its
110    /// optical recognition and Capella reader build.
111    System,
112    /// A whole piece, holding parts.
113    Score,
114    /// A collection of scores.
115    Opus,
116}
117
118impl StreamKind {
119    /// Every kind, in music21's order of containment.
120    pub const ALL: [StreamKind; 8] = [
121        StreamKind::Stream,
122        StreamKind::Voice,
123        StreamKind::Measure,
124        StreamKind::Part,
125        StreamKind::PartStaff,
126        StreamKind::System,
127        StreamKind::Score,
128        StreamKind::Opus,
129    ];
130
131    /// music21's class name for this kind.
132    pub fn as_str(self) -> &'static str {
133        match self {
134            StreamKind::Stream => "Stream",
135            StreamKind::Voice => "Voice",
136            StreamKind::Measure => "Measure",
137            StreamKind::Part => "Part",
138            StreamKind::PartStaff => "PartStaff",
139            StreamKind::System => "System",
140            StreamKind::Score => "Score",
141            StreamKind::Opus => "Opus",
142        }
143    }
144}
145
146impl std::fmt::Display for StreamKind {
147    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148        f.write_str(self.as_str())
149    }
150}
151
152/// A musical object that can live on a timeline.
153#[derive(Clone, Debug)]
154#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
155#[non_exhaustive]
156pub enum StreamElement {
157    /// A single pitched note.
158    Note(Note),
159    /// A chord containing one or more notes.
160    Chord(Chord),
161    /// A silent rest.
162    Rest(Rest),
163    /// A stream nested inside this one: a part in a score, a measure in a
164    /// part. Boxed, since a stream holds these by value.
165    Stream(Box<Stream>),
166    /// The clef in force from here on.
167    Clef(Clef),
168    /// The instrument playing from here on. Boxed: an instrument is large.
169    Instrument(Box<Instrument>),
170    /// The key signature in force from here on.
171    KeySignature(KeySignature),
172    /// The key in force from here on: a key signature that also says its
173    /// tonic and mode, as music21's `Key` is a `KeySignature`.
174    Key(Key),
175    /// The metre in force from here on.
176    TimeSignature(TimeSignature),
177    /// The tempo in force from here on.
178    MetronomeMark(MetronomeMark),
179    /// A tempo said in words, `Grave` or `Allegro`.
180    TempoText(TempoText),
181    /// Words written over or under the staff.
182    TextExpression(TextExpression),
183    /// A sign or words saying where to go next, *Fine* or *D.C.*
184    RepeatExpression(RepeatExpression),
185    /// The dynamic in force from here on.
186    Dynamic(Dynamic),
187    /// A chord named over the music. It holds for the time it has been
188    /// given and takes none until then.
189    ChordSymbol(ChordSymbol),
190    /// A stroke with no pitch.
191    Unpitched(Unpitched),
192    /// Several strokes at once.
193    PercussionChord(PercussionChord),
194    /// A barline standing inside a measure rather than at either end of it,
195    /// where a measure's own barlines are kept.
196    Barline(Barline),
197    /// A bounce or a gap in the line of a held pedal, joined by the pedal
198    /// mark it belongs to.
199    PedalObject(PedalObject),
200    /// A letter or number marking a place to rehearse from.
201    RehearsalMark(RehearsalMark),
202    /// A change of tempo written as one note value becoming another. Boxed:
203    /// it holds two tempo marks.
204    MetricModulation(Box<MetricModulation>),
205    /// Where a manuscript's line, page or column breaks.
206    Break(crate::volpiano::Break),
207    /// How the page, a system or a staff is laid out from here on.
208    Layout(crate::layout::Layout),
209    /// Text standing anywhere on a page. Boxed: it carries its style.
210    TextBox(Box<crate::text::TextBox>),
211    /// Another reading of the passage starting here, which takes no time
212    /// itself. Boxed: it holds a stream.
213    Variant(Box<crate::variant::Variant>),
214    /// A `!!` line of a Humdrum file, kept where it was written.
215    GlobalComment(crate::humdrum::GlobalComment),
216    /// A `*` instruction of a Humdrum spine with no object of its own,
217    /// kept where it was written.
218    MiscTandem(crate::humdrum::MiscTandem),
219    /// A `!` comment in one Humdrum spine: music21's `SpineComment`.
220    SpineComment(crate::humdrum::SpineComment),
221    /// Where a braille segment divides; nothing is written for it.
222    BrailleSegmentDivision(crate::braille::SegmentDivision),
223}
224
225impl StreamElement {
226    /// Returns the assigned duration, if present.
227    ///
228    /// The marks that only say what is in force from a point — a key, a
229    /// metre, a tempo, a dynamic — have none, as they take no time in
230    /// music21 either. A chord symbol has one, of no length until it is
231    /// given the time it holds.
232    pub fn duration(&self) -> Option<&Duration> {
233        match self {
234            Self::Note(note) => note.duration(),
235            Self::Chord(chord) => chord.duration(),
236            Self::Unpitched(stroke) => stroke.duration(),
237            Self::PercussionChord(chord) => chord.duration(),
238            Self::Rest(rest) => Some(rest.duration()),
239            Self::ChordSymbol(symbol) => Some(symbol.duration()),
240            Self::Stream(_)
241            | Self::Clef(_)
242            | Self::Instrument(_)
243            | Self::KeySignature(_)
244            | Self::Key(_)
245            | Self::TimeSignature(_)
246            | Self::MetronomeMark(_)
247            | Self::TempoText(_)
248            | Self::TextExpression(_)
249            | Self::RepeatExpression(_)
250            | Self::Dynamic(_)
251            | Self::Barline(_)
252            | Self::PedalObject(_)
253            | Self::RehearsalMark(_)
254            | Self::MetricModulation(_)
255            | Self::Break(_)
256            | Self::Layout(_)
257            | Self::TextBox(_)
258            | Self::Variant(_)
259            | Self::GlobalComment(_)
260            | Self::MiscTandem(_)
261            | Self::SpineComment(_)
262            | Self::BrailleSegmentDivision(_) => None,
263        }
264    }
265
266    /// Returns the duration in quarter lengths.
267    ///
268    /// A nested stream is as long as its own contents; a mark takes no time;
269    /// anything else with no duration of its own defaults to a quarter, as
270    /// music21's does.
271    pub fn quarter_length(&self) -> FloatType {
272        match self {
273            Self::Stream(stream) => stream.end_offset(),
274            Self::Clef(_)
275            | Self::Instrument(_)
276            | Self::KeySignature(_)
277            | Self::Key(_)
278            | Self::TimeSignature(_)
279            | Self::MetronomeMark(_)
280            | Self::TempoText(_)
281            | Self::TextExpression(_)
282            | Self::RepeatExpression(_)
283            | Self::Dynamic(_)
284            | Self::Barline(_)
285            | Self::PedalObject(_)
286            | Self::RehearsalMark(_)
287            | Self::MetricModulation(_)
288            | Self::Break(_)
289            | Self::Layout(_)
290            | Self::TextBox(_)
291            | Self::Variant(_)
292            | Self::GlobalComment(_)
293            | Self::MiscTandem(_)
294            | Self::SpineComment(_)
295            | Self::BrailleSegmentDivision(_) => 0.0,
296            _ => self
297                .duration()
298                .map(Duration::quarter_length)
299                .unwrap_or_else(|| Duration::default().quarter_length()),
300        }
301    }
302
303    /// Returns all pitches contained by this element, a nested stream's
304    /// included.
305    pub fn pitches(&self) -> Vec<Pitch> {
306        match self {
307            Self::Note(note) => vec![note.pitch().clone()],
308            Self::Chord(chord) => chord.pitches(),
309            Self::Stream(stream) => stream.pitches(),
310            Self::PercussionChord(chord) => chord.pitches(),
311            Self::Unpitched(_)
312            | Self::Rest(_)
313            | Self::Clef(_)
314            | Self::Instrument(_)
315            | Self::KeySignature(_)
316            | Self::Key(_)
317            | Self::TimeSignature(_)
318            | Self::MetronomeMark(_)
319            | Self::TempoText(_)
320            | Self::TextExpression(_)
321            | Self::RepeatExpression(_)
322            | Self::Dynamic(_)
323            | Self::ChordSymbol(_)
324            | Self::Barline(_)
325            | Self::PedalObject(_)
326            | Self::RehearsalMark(_)
327            | Self::MetricModulation(_)
328            | Self::Break(_)
329            | Self::Layout(_)
330            | Self::TextBox(_)
331            | Self::Variant(_)
332            | Self::GlobalComment(_)
333            | Self::MiscTandem(_)
334            | Self::SpineComment(_)
335            | Self::BrailleSegmentDivision(_) => Vec::new(),
336        }
337    }
338
339    /// The stream this element is, when it is one.
340    pub fn as_stream(&self) -> Option<&Stream> {
341        match self {
342            Self::Stream(stream) => Some(stream),
343            _ => None,
344        }
345    }
346
347    /// music21's `classSortOrder`: what comes first among the things standing
348    /// at one offset.
349    pub(crate) fn class_sort_order(&self) -> i32 {
350        match self {
351            // music21's `BrailleTranscriptionHelper`.
352            Self::BrailleSegmentDivision(_) => -100,
353            Self::TextBox(_) => -31,
354            Self::TextExpression(_) | Self::RehearsalMark(_) => -30,
355            Self::Instrument(_) => -25,
356            Self::Layout(_) => -10,
357            Self::Stream(stream) if stream.kind() == StreamKind::Voice => 5,
358            Self::Stream(_) => -20,
359            Self::Variant(_) => -22,
360            Self::Barline(_) => -5,
361            Self::Clef(_) => 0,
362            Self::MetronomeMark(_) | Self::TempoText(_) | Self::MetricModulation(_) => 1,
363            Self::KeySignature(_) | Self::Key(_) => 2,
364            Self::TimeSignature(_) => 4,
365            Self::Dynamic(_) => 10,
366            // music21's `RomanNumeral` is a `Harmony`, which sorts before
367            // the notes standing at the same offset as a chord symbol
368            // does; a chord carrying a numeral is one of those.
369            Self::ChordSymbol(_) => 19,
370            Self::Chord(chord) if chord.numeral().is_some() => 19,
371            _ => 20,
372        }
373    }
374
375    /// Whether this element sounds — music21's `.notes`, which is notes and
376    /// chords but not rests.
377    pub fn is_note_or_chord(&self) -> bool {
378        matches!(self, Self::Note(_) | Self::Chord(_))
379    }
380
381    /// Returns a transposed copy.
382    ///
383    /// A key signature moves with the music, as music21's does; a metre and
384    /// a tempo do not depend on pitch and are left alone.
385    pub fn transpose(&self, interval: &Interval) -> Result<Self> {
386        match self {
387            Self::Note(note) => {
388                let mut out = note.clone();
389                out.set_pitch(interval.transpose_pitch(note.pitch())?);
390                Ok(Self::Note(out))
391            }
392            Self::Chord(chord) => Ok(Self::Chord(chord.transpose(interval)?)),
393            Self::Rest(rest) => Ok(Self::Rest(rest.clone())),
394            // A stroke has no pitch to move, and a percussion part is not
395            // transposed with the music.
396            Self::Unpitched(stroke) => Ok(Self::Unpitched(stroke.clone())),
397            Self::PercussionChord(chord) => Ok(Self::PercussionChord(chord.clone())),
398            Self::Stream(stream) => Ok(Self::Stream(Box::new(stream.transpose(interval)?))),
399            Self::Clef(clef) => Ok(Self::Clef(clef.clone())),
400            Self::Instrument(instrument) => Ok(Self::Instrument(instrument.clone())),
401            Self::KeySignature(key) => Ok(Self::KeySignature(key.transpose(interval)?)),
402            Self::Key(key) => Ok(Self::Key(key.transpose(interval)?)),
403            Self::TimeSignature(meter) => Ok(Self::TimeSignature(meter.clone())),
404            Self::MetronomeMark(mark) => Ok(Self::MetronomeMark(mark.clone())),
405            Self::TempoText(text) => Ok(Self::TempoText(text.clone())),
406            Self::TextExpression(text) => Ok(Self::TextExpression(text.clone())),
407            Self::RepeatExpression(mark) => Ok(Self::RepeatExpression(mark.clone())),
408            Self::Dynamic(dynamic) => Ok(Self::Dynamic(dynamic.clone())),
409            Self::ChordSymbol(symbol) => Ok(Self::ChordSymbol(symbol.transpose(interval)?)),
410            Self::Barline(barline) => Ok(Self::Barline(barline.clone())),
411            Self::PedalObject(object) => Ok(Self::PedalObject(object.clone())),
412            Self::RehearsalMark(mark) => Ok(Self::RehearsalMark(mark.clone())),
413            Self::MetricModulation(modulation) => Ok(Self::MetricModulation(modulation.clone())),
414            Self::Break(kind) => Ok(Self::Break(*kind)),
415            Self::Layout(layout) => Ok(Self::Layout(layout.clone())),
416            Self::TextBox(text) => Ok(Self::TextBox(text.clone())),
417            Self::Variant(variant) => Ok(Self::Variant(Box::new(variant.transpose(interval)?))),
418            Self::GlobalComment(said) => Ok(Self::GlobalComment(said.clone())),
419            Self::MiscTandem(tandem) => Ok(Self::MiscTandem(tandem.clone())),
420            Self::SpineComment(said) => Ok(Self::SpineComment(said.clone())),
421            Self::BrailleSegmentDivision(division) => Ok(Self::BrailleSegmentDivision(*division)),
422        }
423    }
424}
425
426impl From<Barline> for StreamElement {
427    fn from(value: Barline) -> Self {
428        Self::Barline(value)
429    }
430}
431
432impl From<PedalObject> for StreamElement {
433    fn from(value: PedalObject) -> Self {
434        Self::PedalObject(value)
435    }
436}
437
438impl From<crate::humdrum::GlobalComment> for StreamElement {
439    fn from(value: crate::humdrum::GlobalComment) -> Self {
440        Self::GlobalComment(value)
441    }
442}
443
444impl From<crate::humdrum::SpineComment> for StreamElement {
445    fn from(value: crate::humdrum::SpineComment) -> Self {
446        Self::SpineComment(value)
447    }
448}
449
450impl From<crate::humdrum::MiscTandem> for StreamElement {
451    fn from(value: crate::humdrum::MiscTandem) -> Self {
452        Self::MiscTandem(value)
453    }
454}
455
456impl From<crate::braille::SegmentDivision> for StreamElement {
457    fn from(value: crate::braille::SegmentDivision) -> Self {
458        Self::BrailleSegmentDivision(value)
459    }
460}
461
462impl From<RehearsalMark> for StreamElement {
463    fn from(value: RehearsalMark) -> Self {
464        Self::RehearsalMark(value)
465    }
466}
467
468impl From<MetricModulation> for StreamElement {
469    fn from(value: MetricModulation) -> Self {
470        Self::MetricModulation(Box::new(value))
471    }
472}
473
474impl From<Note> for StreamElement {
475    fn from(value: Note) -> Self {
476        Self::Note(value)
477    }
478}
479
480impl From<Chord> for StreamElement {
481    fn from(value: Chord) -> Self {
482        Self::Chord(value)
483    }
484}
485
486impl From<Rest> for StreamElement {
487    fn from(value: Rest) -> Self {
488        Self::Rest(value)
489    }
490}
491
492impl From<Stream> for StreamElement {
493    fn from(value: Stream) -> Self {
494        Self::Stream(Box::new(value))
495    }
496}
497
498impl From<Clef> for StreamElement {
499    fn from(value: Clef) -> Self {
500        Self::Clef(value)
501    }
502}
503
504impl From<Instrument> for StreamElement {
505    fn from(value: Instrument) -> Self {
506        Self::Instrument(Box::new(value))
507    }
508}
509
510impl From<Key> for StreamElement {
511    fn from(value: Key) -> Self {
512        Self::Key(value)
513    }
514}
515
516impl From<KeySignature> for StreamElement {
517    fn from(value: KeySignature) -> Self {
518        Self::KeySignature(value)
519    }
520}
521
522impl From<TimeSignature> for StreamElement {
523    fn from(value: TimeSignature) -> Self {
524        Self::TimeSignature(value)
525    }
526}
527
528impl From<Dynamic> for StreamElement {
529    fn from(value: Dynamic) -> Self {
530        Self::Dynamic(value)
531    }
532}
533
534impl From<ChordSymbol> for StreamElement {
535    fn from(value: ChordSymbol) -> Self {
536        Self::ChordSymbol(value)
537    }
538}
539
540impl From<TextExpression> for StreamElement {
541    fn from(value: TextExpression) -> Self {
542        Self::TextExpression(value)
543    }
544}
545
546impl From<Unpitched> for StreamElement {
547    fn from(value: Unpitched) -> Self {
548        Self::Unpitched(value)
549    }
550}
551
552impl From<PercussionChord> for StreamElement {
553    fn from(value: PercussionChord) -> Self {
554        Self::PercussionChord(value)
555    }
556}
557
558impl From<RepeatExpression> for StreamElement {
559    fn from(value: RepeatExpression) -> Self {
560        Self::RepeatExpression(value)
561    }
562}
563
564impl From<TempoText> for StreamElement {
565    fn from(value: TempoText) -> Self {
566        Self::TempoText(value)
567    }
568}
569
570impl From<MetronomeMark> for StreamElement {
571    fn from(value: MetronomeMark) -> Self {
572        Self::MetronomeMark(value)
573    }
574}
575
576/// A timestamped stream item.
577#[derive(Clone, Debug)]
578#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
579pub struct StreamEvent {
580    offset: FloatType,
581    element: StreamElement,
582    /// music21's `priority`, which sorts what stands at one offset ahead
583    /// of its class: nought but where a reader says, as Humdrum's says the
584    /// line each thing was written on.
585    #[cfg_attr(feature = "serde", serde(default))]
586    priority: i32,
587}
588
589impl StreamEvent {
590    /// Creates an event at an offset measured in quarter lengths.
591    pub fn new(offset: FloatType, element: impl Into<StreamElement>) -> Self {
592        Self {
593            offset,
594            element: element.into(),
595            priority: 0,
596        }
597    }
598
599    /// The same event, sorted by `priority` among what shares its offset.
600    pub fn with_priority(mut self, priority: i32) -> Self {
601        self.priority = priority;
602        self
603    }
604
605    /// music21's `priority` for the element, nought unless a reader gave
606    /// one.
607    pub fn priority(&self) -> i32 {
608        self.priority
609    }
610
611    /// Returns the offset in quarter lengths.
612    pub fn offset(&self) -> FloatType {
613        self.offset
614    }
615
616    /// Returns the stream element.
617    pub fn element_mut(&mut self) -> &mut StreamElement {
618        &mut self.element
619    }
620
621    /// The element itself.
622    pub fn element(&self) -> &StreamElement {
623        &self.element
624    }
625
626    /// The offset just past this element.
627    pub fn end_offset(&self) -> FloatType {
628        self.offset + self.element.quarter_length()
629    }
630}
631
632/// An ordered stream of music, which may hold other streams.
633#[derive(Clone, Debug, Default)]
634#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
635#[must_use]
636pub struct Stream {
637    #[cfg_attr(feature = "serde", serde(default))]
638    kind: StreamKind,
639    events: Vec<StreamEvent>,
640    #[cfg_attr(feature = "serde", serde(default))]
641    labels: Labels,
642}
643
644/// How a staff group's barlines are drawn: music21's `barTogether`.
645#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
646#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
647pub enum BarTogether {
648    /// Barlines run through every staff of the group.
649    Yes,
650    /// Each staff is barred on its own.
651    No,
652    /// Barlines run between the staves but not through them.
653    Mensurstrich,
654}
655
656impl BarTogether {
657    /// The setting a word names, as music21's `barTogether` setter reads
658    /// it: `yes`, `no`, or `Mensurstrich` in any case.
659    ///
660    /// ```
661    /// use music21::stream::BarTogether;
662    ///
663    /// assert_eq!(BarTogether::from_word("mensurstrich"), Some(BarTogether::Mensurstrich));
664    /// assert_eq!(BarTogether::from_word("Yes"), None);
665    /// ```
666    #[must_use]
667    pub fn from_word(word: &str) -> Option<Self> {
668        match word {
669            "yes" => Some(Self::Yes),
670            "no" => Some(Self::No),
671            _ if word.to_lowercase() == "mensurstrich" => Some(Self::Mensurstrich),
672            _ => None,
673        }
674    }
675
676    /// The group barline MusicXML writes for it.
677    pub fn as_str(self) -> &'static str {
678        match self {
679            Self::Yes => "yes",
680            Self::No => "no",
681            Self::Mensurstrich => "Mensurstrich",
682        }
683    }
684}
685
686/// Parts of a score bracketed together: music21's `layout.StaffGroup`,
687/// which holds the parts it spans.
688///
689/// The parts are named by where they stand among the score's parts, first
690/// to last, in the order the group was given them.
691#[derive(Clone, Debug, PartialEq)]
692#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
693pub struct StaffGroup {
694    parts: Vec<usize>,
695    name: Option<String>,
696    abbreviation: Option<String>,
697    symbol: Option<String>,
698    bar_together: Option<BarTogether>,
699    name_hidden: bool,
700    /// Where the symbol is drawn and in what colour: music21's `style`.
701    #[cfg_attr(feature = "serde", serde(default))]
702    pub style: crate::style::TextStyle,
703}
704
705impl StaffGroup {
706    /// A group of the parts at these positions, barred together and drawn
707    /// with no symbol, as music21's starts out.
708    pub fn new(parts: Vec<usize>) -> Self {
709        Self {
710            parts,
711            name: None,
712            abbreviation: None,
713            symbol: None,
714            bar_together: Some(BarTogether::Yes),
715            name_hidden: false,
716            style: crate::style::TextStyle::default(),
717        }
718    }
719
720    /// The positions of the parts the group spans.
721    pub fn parts(&self) -> &[usize] {
722        &self.parts
723    }
724
725    /// The group's name.
726    pub fn name(&self) -> Option<&str> {
727        self.name.as_deref()
728    }
729
730    /// Names the group, or clears the name.
731    pub fn set_name(&mut self, name: Option<String>) {
732        self.name = name;
733    }
734
735    /// The group's short name.
736    pub fn abbreviation(&self) -> Option<&str> {
737        self.abbreviation.as_deref()
738    }
739
740    /// Sets the short name, or clears it.
741    pub fn set_abbreviation(&mut self, abbreviation: Option<String>) {
742        self.abbreviation = abbreviation;
743    }
744
745    /// What the group is drawn with: `bracket`, `brace`, `line` or `square`.
746    pub fn symbol(&self) -> Option<&str> {
747        self.symbol.as_deref()
748    }
749
750    /// Sets what the group is drawn with. As in music21, `none` in any case
751    /// clears it, and anything but the four symbols is refused.
752    pub fn set_symbol(&mut self, symbol: Option<&str>) -> Result<()> {
753        self.symbol = match symbol.map(str::to_lowercase) {
754            None => None,
755            Some(symbol) if symbol == "none" => None,
756            Some(symbol) if ["brace", "line", "bracket", "square"].contains(&symbol.as_str()) => {
757                Some(symbol)
758            }
759            Some(symbol) => {
760                return Err(crate::error::Error::Value(format!(
761                    "the symbol value {symbol} is not acceptable"
762                )));
763            }
764        };
765        Ok(())
766    }
767
768    /// How the group's barlines are drawn, where that has been said.
769    pub fn bar_together(&self) -> Option<BarTogether> {
770        self.bar_together
771    }
772
773    /// Says how the group's barlines are drawn.
774    pub fn set_bar_together(&mut self, bar_together: Option<BarTogether>) {
775        self.bar_together = bar_together;
776    }
777
778    /// Whether the name is left unprinted: music21's `hideObjectOnPrint`.
779    pub fn name_hidden(&self) -> bool {
780        self.name_hidden
781    }
782
783    /// Says whether the name is left unprinted.
784    pub fn set_name_hidden(&mut self, hidden: bool) {
785        self.name_hidden = hidden;
786    }
787}
788
789/// What a stream is called and numbered, as distinct from what it holds.
790///
791/// music21 spreads these over its subclasses: a measure has a number, a part
792/// a name. They are kept together here, and a stream of a kind that has no
793/// use for one simply leaves it unset.
794#[derive(Clone, Debug, Default, PartialEq)]
795#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
796struct Labels {
797    number: IntegerType,
798    number_suffix: Option<String>,
799    number_hidden: bool,
800    id: Option<String>,
801    name: Option<String>,
802    abbreviation: Option<String>,
803    name_hidden: bool,
804    abbreviation_hidden: bool,
805    /// Boxed: most streams carry none.
806    metadata: Option<Box<Metadata>>,
807    staff_groups: Vec<StaffGroup>,
808    left_barline: Option<Barline>,
809    right_barline: Option<Barline>,
810    spanners: Vec<Spanner>,
811    ending: Option<Ending>,
812    #[cfg_attr(feature = "serde", serde(default))]
813    padding_left: FloatType,
814    #[cfg_attr(feature = "serde", serde(default))]
815    padding_right: FloatType,
816    /// How wide a measure is drawn: music21's `layoutWidth`.
817    #[cfg_attr(feature = "serde", serde(default))]
818    layout_width: Option<crate::style::StyleValue>,
819    /// music21's `atSoundingPitch`, `None` for its `'unknown'`.
820    #[cfg_attr(feature = "serde", serde(default))]
821    at_sounding_pitch: Option<bool>,
822    #[cfg_attr(feature = "serde", serde(default))]
823    measure_numbering: Option<String>,
824    /// How the stream is drawn as a whole. Boxed: most streams carry none.
825    #[cfg_attr(feature = "serde", serde(default))]
826    style: Option<Box<crate::style::StreamStyle>>,
827}
828
829impl Stream {
830    /// Creates an empty stream.
831    ///
832    /// ```
833    /// use music21::{Note, Stream};
834    ///
835    /// let mut stream = Stream::new();
836    /// stream.push(Note::from_name("C4")?);
837    /// stream.push(Note::from_name("E4")?);
838    /// assert_eq!(stream.len(), 2);
839    /// assert_eq!(stream.end_offset(), 2.0);
840    /// # Ok::<(), music21::Error>(())
841    /// ```
842    pub fn new() -> Self {
843        Self::default()
844    }
845
846    /// Creates an empty stream standing for one of music21's subclasses.
847    ///
848    /// ```
849    /// use music21::{Stream, StreamKind};
850    ///
851    /// let part = Stream::with_kind(StreamKind::Part);
852    /// assert_eq!(part.kind(), StreamKind::Part);
853    /// assert!(part.is_empty());
854    /// ```
855    pub fn with_kind(kind: StreamKind) -> Self {
856        Self {
857            kind,
858            ..Self::default()
859        }
860    }
861
862    /// A measure's number: music21's `Measure.number`, which is nought until
863    /// something numbers it.
864    pub fn number(&self) -> IntegerType {
865        self.labels.number
866    }
867
868    /// Numbers the measure.
869    pub fn set_number(&mut self, number: IntegerType) {
870        self.labels.number = number;
871    }
872
873    /// What follows the number, as the `a` of a measure numbered `12a`:
874    /// music21's `numberSuffix`.
875    pub fn number_suffix(&self) -> Option<&str> {
876        self.labels.number_suffix.as_deref()
877    }
878
879    /// Sets what follows the number, or clears it.
880    pub fn set_number_suffix(&mut self, suffix: Option<String>) {
881        self.labels.number_suffix = suffix;
882    }
883
884    /// The number with its suffix, `12a`: music21's
885    /// `measureNumberWithSuffix`.
886    pub fn number_with_suffix(&self) -> String {
887        format!(
888            "{}{}",
889            self.labels.number,
890            self.labels.number_suffix.as_deref().unwrap_or("")
891        )
892    }
893
894    /// Whether the measure's number is left unshown, as a pickup bar's is:
895    /// music21's `showNumber` set to `NEVER`.
896    pub fn number_hidden(&self) -> bool {
897        self.labels.number_hidden
898    }
899
900    /// Says whether the measure's number is left unshown.
901    pub fn set_number_hidden(&mut self, hidden: bool) {
902        self.labels.number_hidden = hidden;
903    }
904
905    /// How wide the measure is drawn, in tenths, where the score says:
906    /// music21's `layoutWidth`.
907    pub fn layout_width(&self) -> Option<&crate::style::StyleValue> {
908        self.labels.layout_width.as_ref()
909    }
910
911    /// Says how wide the measure is drawn.
912    pub fn set_layout_width(&mut self, width: Option<crate::style::StyleValue>) {
913        self.labels.layout_width = width;
914    }
915
916    /// Which measures' numbers are shown from this measure on, as MusicXML's
917    /// `<measure-numbering>` says it -- `none`, `measure` or `system`:
918    /// music21's `style.measureNumbering`. How the numbers are drawn is not
919    /// kept.
920    pub fn measure_numbering(&self) -> Option<&str> {
921        self.labels.measure_numbering.as_deref()
922    }
923
924    /// Says which measures' numbers are shown from this measure on.
925    pub fn set_measure_numbering(&mut self, numbering: Option<String>) {
926        self.labels.measure_numbering = numbering;
927    }
928
929    /// The name the stream is known by, as a part's `P1`: music21's `id`
930    /// where one was given rather than taken from a memory address.
931    pub fn id(&self) -> Option<&str> {
932        self.labels.id.as_deref()
933    }
934
935    /// Sets the stream's id, or clears it.
936    pub fn set_id(&mut self, id: Option<String>) {
937        self.labels.id = id;
938    }
939
940    /// A part's name, as printed beside its first system: music21's
941    /// `partName`.
942    pub fn name(&self) -> Option<&str> {
943        self.labels.name.as_deref()
944    }
945
946    /// Names the part, or clears the name.
947    pub fn set_name(&mut self, name: Option<String>) {
948        self.labels.name = name;
949    }
950
951    /// A part's short name, as printed beside the systems after the first:
952    /// music21's `partAbbreviation`.
953    pub fn abbreviation(&self) -> Option<&str> {
954        self.labels.abbreviation.as_deref()
955    }
956
957    /// Sets the part's short name, or clears it.
958    pub fn set_abbreviation(&mut self, abbreviation: Option<String>) {
959        self.labels.abbreviation = abbreviation;
960    }
961
962    /// Whether the part's name is left unprinted: music21's
963    /// `style.printPartName` set to false.
964    pub fn name_hidden(&self) -> bool {
965        self.labels.name_hidden
966    }
967
968    /// Says whether the part's name is left unprinted.
969    pub fn set_name_hidden(&mut self, hidden: bool) {
970        self.labels.name_hidden = hidden;
971    }
972
973    /// Whether the part's short name is left unprinted: music21's
974    /// `style.printPartAbbreviation` set to false.
975    pub fn abbreviation_hidden(&self) -> bool {
976        self.labels.abbreviation_hidden
977    }
978
979    /// Says whether the part's short name is left unprinted.
980    pub fn set_abbreviation_hidden(&mut self, hidden: bool) {
981        self.labels.abbreviation_hidden = hidden;
982    }
983
984    /// The title, composer and the rest a score carries: music21's
985    /// `metadata`.
986    pub fn metadata(&self) -> Option<&Metadata> {
987        self.labels.metadata.as_deref()
988    }
989
990    /// Sets the metadata, or clears it.
991    pub fn set_metadata(&mut self, metadata: Option<Metadata>) {
992        self.labels.metadata = metadata.map(Box::new);
993    }
994
995    /// How the stream is drawn as a whole: music21's `StreamStyle`, where
996    /// it says anything.
997    pub fn stream_style(&self) -> Option<&crate::style::StreamStyle> {
998        self.labels.style.as_deref()
999    }
1000
1001    /// Sets how the stream is drawn as a whole, or clears it.
1002    pub fn set_stream_style(&mut self, style: Option<crate::style::StreamStyle>) {
1003        self.labels.style = style.map(Box::new);
1004    }
1005
1006    /// The groups a score brackets its parts in, in the order they were
1007    /// added.
1008    pub fn staff_groups(&self) -> &[StaffGroup] {
1009        &self.labels.staff_groups
1010    }
1011
1012    /// Brackets some of the score's parts together.
1013    pub fn add_staff_group(&mut self, group: StaffGroup) {
1014        self.labels.staff_groups.push(group);
1015    }
1016
1017    /// The barline a measure starts with, where it is not an ordinary one:
1018    /// music21's `leftBarline`.
1019    pub fn left_barline(&self) -> Option<&Barline> {
1020        self.labels.left_barline.as_ref()
1021    }
1022
1023    /// Sets the barline a measure starts with, or clears it.
1024    pub fn set_left_barline(&mut self, barline: Option<Barline>) {
1025        self.labels.left_barline = barline;
1026    }
1027
1028    /// The barline a measure ends with, where it is not an ordinary one:
1029    /// music21's `rightBarline`.
1030    pub fn right_barline(&self) -> Option<&Barline> {
1031        self.labels.right_barline.as_ref()
1032    }
1033
1034    /// Sets the barline a measure ends with, or clears it.
1035    pub fn set_right_barline(&mut self, barline: Option<Barline>) {
1036        self.labels.right_barline = barline;
1037    }
1038
1039    /// How much of a measure's bar goes unfilled before its first note, as
1040    /// a pickup leaves the start of its bar: music21's `paddingLeft`.
1041    pub fn padding_left(&self) -> FloatType {
1042        self.labels.padding_left
1043    }
1044
1045    /// Says how much of the bar goes unfilled before the first note.
1046    pub fn set_padding_left(&mut self, padding: FloatType) {
1047        self.labels.padding_left = padding;
1048    }
1049
1050    /// How much of a measure's bar goes unfilled after its last note, as a
1051    /// measure cut short leaves its end: music21's `paddingRight`.
1052    pub fn padding_right(&self) -> FloatType {
1053        self.labels.padding_right
1054    }
1055
1056    /// Says how much of the bar goes unfilled after the last note.
1057    pub fn set_padding_right(&mut self, padding: FloatType) {
1058        self.labels.padding_right = padding;
1059    }
1060
1061    /// The alternative ending a measure is part of, where it is in one.
1062    pub fn ending(&self) -> Option<&Ending> {
1063        self.labels.ending.as_ref()
1064    }
1065
1066    /// Puts the measure in an alternative ending, or takes it out.
1067    pub fn set_ending(&mut self, ending: Option<Ending>) {
1068        self.labels.ending = ending;
1069    }
1070
1071    /// The slurs and other spanners this stream holds, each naming what it
1072    /// joins by position in this stream's [`Stream::leaves`].
1073    pub fn spanners(&self) -> &[Spanner] {
1074        &self.labels.spanners
1075    }
1076
1077    /// Adds a spanner, naming what it joins by position in this stream's
1078    /// [`Stream::leaves`].
1079    ///
1080    /// ```
1081    /// use music21::{Note, Spanner, Stream};
1082    ///
1083    /// let mut stream = Stream::new();
1084    /// stream.push(Note::from_name("C4")?);
1085    /// stream.push(Note::from_name("D4")?);
1086    /// stream.add_spanner(Spanner::slur(vec![0, 1]));
1087    /// assert_eq!(stream.spanners().len(), 1);
1088    /// # Ok::<(), music21::Error>(())
1089    /// ```
1090    pub fn add_spanner(&mut self, spanner: Spanner) {
1091        self.labels.spanners.push(spanner);
1092    }
1093
1094    /// Takes every spanner off this stream.
1095    pub(crate) fn clear_spanners(&mut self) {
1096        self.labels.spanners.clear();
1097    }
1098
1099    /// Which of music21's `Stream` subclasses this stands for.
1100    pub fn kind(&self) -> StreamKind {
1101        self.kind
1102    }
1103
1104    /// Sets which subclass this stands for.
1105    pub fn set_kind(&mut self, kind: StreamKind) {
1106        self.kind = kind;
1107    }
1108
1109    /// This stream holding other events, in the order given: its kind, name
1110    /// and numbers kept, its spanners dropped, since the places they name
1111    /// are gone.
1112    pub(crate) fn with_events(&self, events: Vec<StreamEvent>) -> Self {
1113        let mut labels = self.labels.clone();
1114        labels.spanners.clear();
1115        Self {
1116            kind: self.kind,
1117            events,
1118            labels,
1119        }
1120    }
1121
1122    /// Creates a stream from events, sorted by offset, those at one offset
1123    /// kept in the order given: a caller that knows music21's order, its
1124    /// priorities among it, hands it in here, where [`Stream::insert`]
1125    /// sorts them by class.
1126    pub fn from_events(events: impl IntoIterator<Item = StreamEvent>) -> Self {
1127        let mut stream = Self {
1128            events: events.into_iter().collect(),
1129            ..Self::default()
1130        };
1131        stream.sort_events();
1132        stream
1133    }
1134
1135    /// Inserts an element at a quarter-length offset.
1136    ///
1137    /// ```
1138    /// use music21::{Note, Stream};
1139    ///
1140    /// let mut stream = Stream::new();
1141    /// stream.insert(2.0, Note::from_name("G4")?);
1142    /// stream.insert(0.0, Note::from_name("C4")?);
1143    /// let offsets: Vec<f64> = stream.events().iter().map(|event| event.offset()).collect();
1144    /// assert_eq!(offsets, [0.0, 2.0]);
1145    /// # Ok::<(), music21::Error>(())
1146    /// ```
1147    pub fn insert(&mut self, offset: FloatType, element: impl Into<StreamElement>) {
1148        self.insert_sorted(vec![StreamEvent::new(offset, element)]);
1149    }
1150
1151    /// Appends an element after the current end of the stream.
1152    ///
1153    /// ```
1154    /// use music21::{Duration, Note, Rest, Stream};
1155    ///
1156    /// let mut stream = Stream::new();
1157    /// stream.push(Note::from_name("C4")?.with_duration(Duration::half()));
1158    /// stream.push(Rest::new(Duration::new(1.0)?));
1159    /// stream.push(Note::from_name("D4")?);
1160    /// assert_eq!(stream.events()[2].offset(), 3.0);
1161    /// # Ok::<(), music21::Error>(())
1162    /// ```
1163    pub fn push(&mut self, element: impl Into<StreamElement>) {
1164        let event = StreamEvent::new(self.end_offset(), element);
1165        // What takes no time can sort before the last element at the end,
1166        // as a clef does before a dynamic; music21 sorts again then.
1167        let sorts_before_last = self
1168            .events
1169            .last()
1170            .is_some_and(|last| crate::makenotation::event_order(&event, last).is_lt());
1171        if sorts_before_last {
1172            self.insert_sorted(vec![event]);
1173            return;
1174        }
1175
1176        self.events.push(event);
1177    }
1178
1179    /// The events in the stream's order, to change each element in place;
1180    /// where an event stands is fixed, as no offset is set through it.
1181    pub fn events_mut(&mut self) -> &mut [StreamEvent] {
1182        &mut self.events
1183    }
1184
1185    /// The events in offset order.
1186    ///
1187    /// ```
1188    /// use music21::{Note, Rest, Stream, StreamElement};
1189    ///
1190    /// let mut stream = Stream::new();
1191    /// stream.push(Note::from_name("C4")?);
1192    /// stream.push(Rest::default());
1193    /// stream.push(Note::from_name("G4")?);
1194    /// let names: Vec<String> = stream
1195    ///     .events()
1196    ///     .iter()
1197    ///     .filter_map(|event| match event.element() {
1198    ///         StreamElement::Note(note) => Some(note.pitch().name_with_octave()),
1199    ///         _ => None,
1200    ///     })
1201    ///     .collect();
1202    /// assert_eq!(names, ["C4", "G4"]);
1203    /// # Ok::<(), music21::Error>(())
1204    /// ```
1205    pub fn events(&self) -> &[StreamEvent] {
1206        &self.events
1207    }
1208
1209    /// Iterates over events in offset order.
1210    pub fn iter(&self) -> impl Iterator<Item = &StreamEvent> {
1211        self.events.iter()
1212    }
1213
1214    /// How many events this stream holds directly, not counting what any
1215    /// nested stream holds.
1216    pub fn len(&self) -> usize {
1217        self.events.len()
1218    }
1219
1220    /// Whether this stream holds nothing at all.
1221    pub fn is_empty(&self) -> bool {
1222        self.events.is_empty()
1223    }
1224
1225    /// The first event in the stream's order, or `None` where it holds
1226    /// nothing: music21's `first`.
1227    ///
1228    /// ```
1229    /// use music21::{Note, Stream, StreamElement};
1230    ///
1231    /// let mut stream = Stream::new();
1232    /// assert!(stream.first().is_none());
1233    /// stream.push(Note::from_name("C4")?);
1234    /// stream.push(Note::from_name("D4")?);
1235    /// let StreamElement::Note(note) = stream.first().unwrap().element() else {
1236    ///     unreachable!()
1237    /// };
1238    /// assert_eq!(note.pitch().name_with_octave(), "C4");
1239    /// assert_eq!(stream.last().unwrap().offset(), 1.0);
1240    /// # Ok::<(), music21::Error>(())
1241    /// ```
1242    pub fn first(&self) -> Option<&StreamEvent> {
1243        self.events.first()
1244    }
1245
1246    /// The last event in the stream's order, or `None` where it holds
1247    /// nothing: music21's `last`.
1248    pub fn last(&self) -> Option<&StreamEvent> {
1249        self.events.last()
1250    }
1251
1252    /// Takes out everything the stream holds, keeping what it says of
1253    /// itself, its kind, number and names: music21's `clear`. Its spanners,
1254    /// staff groups, metadata and a measure's barlines go too, being among
1255    /// music21's elements.
1256    ///
1257    /// ```
1258    /// use music21::{Note, Stream, StreamKind};
1259    ///
1260    /// let mut measure = Stream::with_kind(StreamKind::Measure);
1261    /// measure.set_number(3);
1262    /// measure.push(Note::from_name("C4")?);
1263    /// measure.clear();
1264    /// assert!(measure.is_empty());
1265    /// assert_eq!(measure.number(), 3);
1266    /// # Ok::<(), music21::Error>(())
1267    /// ```
1268    pub fn clear(&mut self) {
1269        self.events.clear();
1270        self.labels.spanners.clear();
1271        self.labels.staff_groups.clear();
1272        self.labels.metadata = None;
1273        self.labels.left_barline = None;
1274        self.labels.right_barline = None;
1275    }
1276
1277    /// The clef the stream opens with: the first it holds itself at
1278    /// nought, music21's `clef`. A clef in a nested stream is not read; the
1279    /// clef in force anywhere is [`Stream::in_force_before`]'s to find.
1280    ///
1281    /// ```
1282    /// use music21::{Clef, Note, Stream, StreamKind};
1283    ///
1284    /// let mut measure = Stream::with_kind(StreamKind::Measure);
1285    /// measure.push(Note::from_name("D3")?);
1286    /// assert!(measure.clef().is_none());
1287    /// measure.insert(0.0, Clef::bass());
1288    /// assert_eq!(measure.clef().unwrap().sign(), Some("F"));
1289    /// # Ok::<(), music21::Error>(())
1290    /// ```
1291    pub fn clef(&self) -> Option<&Clef> {
1292        self.events.iter().find_map(|event| match &event.element {
1293            StreamElement::Clef(clef) if event.offset == 0.0 => Some(clef),
1294            _ => None,
1295        })
1296    }
1297
1298    /// How long the stream lasts, from its start to the end of what ends
1299    /// last: music21's `duration`, a duration of its `highestTime`
1300    /// ([`Stream::end_offset`]). music21 lets a stream be given a duration
1301    /// of its own; a crate stream's is always read off what it holds.
1302    ///
1303    /// ```
1304    /// use music21::{Duration, Note, Stream};
1305    ///
1306    /// let mut stream = Stream::new();
1307    /// stream.insert(3.0, Note::from_name("C4")?);
1308    /// assert_eq!(stream.duration()?.quarter_length(), 4.0);
1309    /// # Ok::<(), music21::Error>(())
1310    /// ```
1311    ///
1312    /// # Errors
1313    ///
1314    /// A stream ending at an infinite offset, which no duration lasts.
1315    pub fn duration(&self) -> Result<Duration> {
1316        Duration::new(self.end_offset())
1317    }
1318
1319    /// The first event this stream holds itself whose id is `id`, matched
1320    /// without regard to case, or `None`: music21's `getElementById`, which
1321    /// looks at this stream's own elements and not into the streams they
1322    /// hold. Only a stream and a note carry an id here.
1323    ///
1324    /// ```
1325    /// use music21::{Stream, StreamKind};
1326    ///
1327    /// let mut score = Stream::with_kind(StreamKind::Score);
1328    /// for id in ["Soprano", "Alto"] {
1329    ///     let mut part = Stream::with_kind(StreamKind::Part);
1330    ///     part.set_id(Some(id.to_string()));
1331    ///     score.insert(0.0, part);
1332    /// }
1333    /// let alto = score.element_by_id("alto").unwrap();
1334    /// assert_eq!(alto.element().as_stream().unwrap().id(), Some("Alto"));
1335    /// assert!(score.element_by_id("Tenor").is_none());
1336    /// ```
1337    pub fn element_by_id(&self, id: &str) -> Option<&StreamEvent> {
1338        let wanted = id.to_lowercase();
1339        self.events.iter().find(|event| {
1340            let held = match &event.element {
1341                StreamElement::Note(note) => note.id(),
1342                StreamElement::Stream(stream) => stream.id(),
1343                _ => None,
1344            };
1345            held.is_some_and(|held| held == id || held.to_lowercase() == wanted)
1346        })
1347    }
1348
1349    /// One timeline with the nesting dissolved: music21's `flatten`.
1350    ///
1351    /// Each nested stream's offset is added to its contents', and the
1352    /// streams themselves are gone; everything else comes through in
1353    /// music21's order: by offset, then at one offset by class -- a clef
1354    /// before a key before a dynamic before a chord symbol before a note --
1355    /// with grace notes first among their class, and otherwise as the
1356    /// nesting held them, part by part.
1357    ///
1358    /// ```
1359    /// use music21::{Duration, Note, Stream, StreamKind};
1360    ///
1361    /// let mut part = Stream::with_kind(StreamKind::Part);
1362    /// for name in ["C4", "D4"] {
1363    ///     let mut measure = Stream::with_kind(StreamKind::Measure);
1364    ///     measure.push(Note::from_name(name)?.with_duration(Duration::whole()));
1365    ///     part.push(measure);
1366    /// }
1367    /// let flat = part.flatten();
1368    /// assert_eq!(flat.len(), 2);
1369    /// assert_eq!(flat.events()[1].offset(), 4.0);
1370    /// # Ok::<(), music21::Error>(())
1371    /// ```
1372    pub fn flatten(&self) -> Self {
1373        let mut flattened = Self::with_kind(self.kind);
1374        self.flatten_into(0.0, &mut flattened.events);
1375        // music21 sorts what stands at one offset by its class order --
1376        // a dynamic before a chord symbol before a note -- and a grace note
1377        // before the rest of its class, and otherwise keeps the order the
1378        // walk met them in.
1379        flattened.events.sort_by(|left, right| {
1380            left.offset
1381                .partial_cmp(&right.offset)
1382                .unwrap_or(std::cmp::Ordering::Equal)
1383                .then_with(|| {
1384                    left.element
1385                        .class_sort_order()
1386                        .cmp(&right.element.class_sort_order())
1387                })
1388                .then_with(|| is_grace(&right.element).cmp(&is_grace(&left.element)))
1389        });
1390        flattened
1391    }
1392
1393    fn flatten_into(&self, base: FloatType, out: &mut Vec<StreamEvent>) {
1394        for event in &self.events {
1395            // Summed as music21 sums them, snapped by `opFrac`, so three
1396            // triplets end on the beat however deep they sit.
1397            let offset = crate::makenotation::op_frac(base + event.offset);
1398            match &event.element {
1399                StreamElement::Stream(stream) => stream.flatten_into(offset, out),
1400                element => out.push(StreamEvent::new(offset, element.clone())),
1401            }
1402        }
1403    }
1404
1405    /// Every element at its offset from this stream's start, nested streams
1406    /// themselves included: music21's `recurse`.
1407    ///
1408    /// ```
1409    /// use music21::{Duration, Note, Stream, StreamKind};
1410    ///
1411    /// let mut part = Stream::with_kind(StreamKind::Part);
1412    /// for name in ["C4", "D4"] {
1413    ///     let mut measure = Stream::with_kind(StreamKind::Measure);
1414    ///     measure.push(Note::from_name(name)?.with_duration(Duration::whole()));
1415    ///     part.push(measure);
1416    /// }
1417    /// // Two measures and the note in each.
1418    /// let offsets: Vec<f64> = part.recurse().iter().map(|(offset, _)| *offset).collect();
1419    /// assert_eq!(offsets, [0.0, 0.0, 4.0, 4.0]);
1420    /// # Ok::<(), music21::Error>(())
1421    /// ```
1422    pub fn recurse(&self) -> Vec<(FloatType, &StreamElement)> {
1423        let mut out = Vec::new();
1424        self.recurse_into(0.0, &mut out);
1425        out
1426    }
1427
1428    fn recurse_into<'a>(&'a self, base: FloatType, out: &mut Vec<(FloatType, &'a StreamElement)>) {
1429        for event in &self.events {
1430            // Summed as music21 sums them, snapped by `opFrac`, so three
1431            // triplets end on the beat however deep they sit.
1432            let offset = crate::makenotation::op_frac(base + event.offset);
1433            out.push((offset, &event.element));
1434            if let StreamElement::Stream(stream) = &event.element {
1435                stream.recurse_into(offset, out);
1436            }
1437        }
1438    }
1439
1440    /// Every element that is not itself a stream, at its offset from this
1441    /// stream's start, in the order [`Stream::for_each_mut`] hands them over.
1442    ///
1443    /// An element's index in this list is its *position*, which is how the
1444    /// walks answering about particular elements say which they mean:
1445    /// [`crate::volume::dynamics_in_force`],
1446    /// [`crate::chordsymbol::chord_symbol_durations`],
1447    /// [`crate::voiceleading::voice_leading_quartet_positions`] and
1448    /// [`crate::voiceleading::verticality_positions_at`]. A caller keeping
1449    /// something of its own beside each element, as a binding keeps the
1450    /// object it was handed, finds it again by the same index.
1451    pub fn leaves(&self) -> Vec<(FloatType, &StreamElement)> {
1452        self.leaves_under_top()
1453            .into_iter()
1454            .map(|(_, offset, element)| (offset, element))
1455            .collect()
1456    }
1457
1458    /// [`Stream::leaves`], each with the index of the event of this stream it
1459    /// came out of: itself for an element held directly, the nested stream
1460    /// holding it otherwise.
1461    pub(crate) fn leaves_under_top(&self) -> Vec<(usize, FloatType, &StreamElement)> {
1462        let mut out = Vec::new();
1463        for (top, event) in self.events.iter().enumerate() {
1464            match &event.element {
1465                StreamElement::Stream(stream) => {
1466                    let mut inner = Vec::new();
1467                    stream.leaves_into(event.offset, &mut inner);
1468                    out.extend(
1469                        inner
1470                            .into_iter()
1471                            .map(|(offset, element)| (top, offset, element)),
1472                    );
1473                }
1474                element => out.push((top, event.offset, element)),
1475            }
1476        }
1477        out
1478    }
1479
1480    /// The positions among [`Stream::leaves`] in the order
1481    /// [`Stream::flatten`] puts them: by offset, then by class order, a
1482    /// grace note ahead of the rest of its class, and otherwise as the walk
1483    /// met them.
1484    ///
1485    /// The two walks are the same walk, so the *n*th leaf is the *n*th
1486    /// element the flattening read; this says where each of those stands
1487    /// once sorted, which is how a walk reading a flattened stream answers
1488    /// in positions a caller can look up.
1489    pub(crate) fn flatten_order(leaves: &[(FloatType, &StreamElement)]) -> Vec<usize> {
1490        let mut order: Vec<usize> = (0..leaves.len()).collect();
1491        order.sort_by(|left, right| {
1492            let (left_offset, left_element) = leaves[*left];
1493            let (right_offset, right_element) = leaves[*right];
1494            left_offset
1495                .total_cmp(&right_offset)
1496                .then(
1497                    left_element
1498                        .class_sort_order()
1499                        .cmp(&right_element.class_sort_order()),
1500                )
1501                .then(is_grace(right_element).cmp(&is_grace(left_element)))
1502        });
1503        order
1504    }
1505
1506    fn leaves_into<'a>(&'a self, base: FloatType, out: &mut Vec<(FloatType, &'a StreamElement)>) {
1507        for event in &self.events {
1508            // Summed as music21 sums them, snapped by `opFrac`, so three
1509            // triplets end on the beat however deep they sit.
1510            let offset = crate::makenotation::op_frac(base + event.offset);
1511            match &event.element {
1512                StreamElement::Stream(stream) => stream.leaves_into(offset, out),
1513                element => out.push((offset, element)),
1514            }
1515        }
1516    }
1517
1518    /// Takes out one of this stream's own events, and with it whatever it
1519    /// holds: music21's `remove`. Every spanner, here or in a nested
1520    /// stream, is moved to where what it names now stands, and names
1521    /// nothing for an element taken out. Nothing is taken out for a place
1522    /// past the end.
1523    pub fn remove_event(&mut self, index: usize) -> Option<StreamEvent> {
1524        if index >= self.events.len() {
1525            return None;
1526        }
1527        let under = self.leaves_under_top();
1528        let doomed: Vec<usize> = under
1529            .iter()
1530            .enumerate()
1531            .filter(|(_, (top, _, _))| *top == index)
1532            .map(|(position, _)| position)
1533            .collect();
1534        let holds_a_stream = matches!(self.events[index].element, StreamElement::Stream(_));
1535        if holds_a_stream {
1536            self.retain_leaves(&mut |position, _| !doomed.contains(&position));
1537            return Some(self.events.remove(index));
1538        }
1539        let removed = self.events[index].clone();
1540        self.retain_leaves(&mut |position, _| !doomed.contains(&position));
1541        Some(removed)
1542    }
1543
1544    /// Hands every element to a closure with its offset from this stream's
1545    /// start, nested streams' contents included, so that it may be changed
1546    /// where it sits.
1547    ///
1548    /// [`Stream::flatten`] and [`Stream::recurse`] hand back copies and
1549    /// references; this is the walk for an edit that has to land in the
1550    /// score itself. Things at one offset come in the same order `flatten`
1551    /// gives them. A nested stream is walked into rather than handed over.
1552    pub fn for_each_mut(&mut self, visit: &mut impl FnMut(FloatType, &mut StreamElement)) {
1553        self.for_each_mut_from(0.0, visit);
1554    }
1555
1556    fn for_each_mut_from(
1557        &mut self,
1558        base: FloatType,
1559        visit: &mut impl FnMut(FloatType, &mut StreamElement),
1560    ) {
1561        for event in &mut self.events {
1562            // Summed as music21 sums them, snapped by `opFrac`, so three
1563            // triplets end on the beat however deep they sit.
1564            let offset = crate::makenotation::op_frac(base + event.offset);
1565            match &mut event.element {
1566                StreamElement::Stream(stream) => stream.for_each_mut_from(offset, visit),
1567                element => visit(offset, element),
1568            }
1569        }
1570    }
1571
1572    /// Keeps the leaves `keep` accepts, handed each with its position in
1573    /// [`Stream::leaves`] to change as it likes, and drops the rest. Every
1574    /// spanner, here or in a nested stream, is moved to where what it names
1575    /// now stands, and names nothing for an element dropped.
1576    pub fn retain_leaves(&mut self, keep: &mut impl FnMut(usize, &mut StreamElement) -> bool) {
1577        let mut seen = 0;
1578        self.retain_leaves_from(&mut seen, keep);
1579    }
1580
1581    /// Puts `replacement` in place of the stream reached by `path`, the
1582    /// index of an event holding a stream at each level down from here.
1583    /// Every spanner of a stream on the way moves past what was replaced
1584    /// to where it now stands, and names nothing for an element replaced.
1585    pub(crate) fn replace_nested(&mut self, path: &[usize], replacement: Stream) {
1586        self.edit_nested(path, |target| {
1587            let gone = vec![None; target.leaf_total()];
1588            *target = replacement;
1589            ((), gone)
1590        });
1591    }
1592
1593    /// Edits the stream reached by `path`, the index of an event holding a
1594    /// stream at each level down from here. `edit` answers what it answers
1595    /// and where each of the stream's leaves went, by old position, having
1596    /// moved that stream's own spanners itself; every spanner of a stream on
1597    /// the way is moved with them. The answer is `edit`'s, and where each of
1598    /// this stream's leaves went.
1599    pub(crate) fn edit_nested<R>(
1600        &mut self,
1601        path: &[usize],
1602        edit: impl FnOnce(&mut Stream) -> (R, Vec<Option<usize>>),
1603    ) -> (R, Vec<Option<usize>>) {
1604        let Some((&first, rest)) = path.split_first() else {
1605            return edit(self);
1606        };
1607        let total = self.leaf_total();
1608        let before: usize = self.events[..first]
1609            .iter()
1610            .map(|event| leaf_count(&event.element))
1611            .sum();
1612        let StreamElement::Stream(inner) = &mut self.events[first].element else {
1613            return edit(self);
1614        };
1615        let old = inner.leaf_total();
1616        let (answer, inner_moved) = inner.edit_nested(rest, edit);
1617        let new = inner.leaf_total();
1618        let moved: Vec<Option<usize>> = (0..total)
1619            .map(|place| {
1620                if place < before {
1621                    Some(place)
1622                } else if place < before + old {
1623                    inner_moved
1624                        .get(place - before)
1625                        .copied()
1626                        .flatten()
1627                        .map(|at| at + before)
1628                } else {
1629                    Some(place - old + new)
1630                }
1631            })
1632            .collect();
1633        for spanner in &mut self.labels.spanners {
1634            spanner.move_places(&moved);
1635        }
1636        (answer, moved)
1637    }
1638
1639    /// How many leaves this stream has.
1640    pub(crate) fn leaf_total(&self) -> usize {
1641        self.events
1642            .iter()
1643            .map(|event| leaf_count(&event.element))
1644            .sum()
1645    }
1646
1647    /// Puts `events` in place of this stream's own, in the order given,
1648    /// each with the index of the event it stood at here, if it did. Every
1649    /// spanner of this stream is moved to where what it names now stands,
1650    /// and names nothing for an element no longer here. The answer is where
1651    /// each leaf went, by old position.
1652    pub(crate) fn replace_events(
1653        &mut self,
1654        events: Vec<(StreamEvent, Option<usize>)>,
1655    ) -> Vec<Option<usize>> {
1656        let mut starts = Vec::with_capacity(self.events.len());
1657        let mut first = 0;
1658        for event in &self.events {
1659            starts.push(first);
1660            first += leaf_count(&event.element);
1661        }
1662        let mut moved: Vec<Option<usize>> = vec![None; first];
1663        let mut placed = 0;
1664        for (event, origin) in &events {
1665            let count = leaf_count(&event.element);
1666            if let Some(&start) = origin.and_then(|origin| starts.get(origin)) {
1667                for leaf in 0..count {
1668                    if let Some(slot) = moved.get_mut(start + leaf) {
1669                        *slot = Some(placed + leaf);
1670                    }
1671                }
1672            }
1673            placed += count;
1674        }
1675        self.events = events.into_iter().map(|(event, _)| event).collect();
1676        for spanner in &mut self.labels.spanners {
1677            spanner.move_places(&moved);
1678        }
1679        moved
1680    }
1681
1682    /// Adds events to this stream's own and puts them all in the order
1683    /// music21 sorts a stream in, an added event after one already here that
1684    /// sorts alike. Every spanner of this stream is moved to where what it
1685    /// names now stands. The answer is where each leaf went, by old
1686    /// position.
1687    pub(crate) fn insert_sorted(&mut self, added: Vec<StreamEvent>) -> Vec<Option<usize>> {
1688        // Each event held here with where its leaves started; nothing for
1689        // one added.
1690        let mut first = 0;
1691        let mut held: Vec<(StreamEvent, Option<usize>)> = Vec::new();
1692        for event in std::mem::take(&mut self.events) {
1693            let count = leaf_count(&event.element);
1694            held.push((event, Some(first)));
1695            first += count;
1696        }
1697        held.extend(added.into_iter().map(|event| (event, None)));
1698        held.sort_by(|left, right| crate::makenotation::event_order(&left.0, &right.0));
1699        let mut moved: Vec<Option<usize>> = vec![None; first];
1700        let mut placed = 0;
1701        for (event, start) in &held {
1702            let count = leaf_count(&event.element);
1703            if let Some(start) = start {
1704                for offset in 0..count {
1705                    moved[start + offset] = Some(placed + offset);
1706                }
1707            }
1708            placed += count;
1709        }
1710        self.events = held.into_iter().map(|(event, _)| event).collect();
1711        for spanner in &mut self.labels.spanners {
1712            spanner.move_places(&moved);
1713        }
1714        moved
1715    }
1716
1717    /// [`Stream::retain_leaves`] below the `seen` leaves already walked; the
1718    /// answer is where each of this stream's leaves went, by old position.
1719    fn retain_leaves_from(
1720        &mut self,
1721        seen: &mut usize,
1722        keep: &mut impl FnMut(usize, &mut StreamElement) -> bool,
1723    ) -> Vec<Option<usize>> {
1724        let mut moved: Vec<Option<usize>> = Vec::new();
1725        let mut kept = 0;
1726        self.events.retain_mut(|event| match &mut event.element {
1727            StreamElement::Stream(inner) => {
1728                let inner_moved = inner.retain_leaves_from(seen, keep);
1729                let count = inner_moved.iter().flatten().count();
1730                moved.extend(
1731                    inner_moved
1732                        .into_iter()
1733                        .map(|place| place.map(|place| place + kept)),
1734                );
1735                kept += count;
1736                true
1737            }
1738            element => {
1739                let position = *seen;
1740                *seen += 1;
1741                if keep(position, element) {
1742                    moved.push(Some(kept));
1743                    kept += 1;
1744                    true
1745                } else {
1746                    moved.push(None);
1747                    false
1748                }
1749            }
1750        });
1751        for spanner in &mut self.labels.spanners {
1752            spanner.move_places(&moved);
1753        }
1754        moved
1755    }
1756
1757    /// Whether this stream holds parts, or streams standing in for them:
1758    /// music21's `hasPartLikeStreams`. A part says so; a measure or a voice,
1759    /// or a stream starting anywhere but the beginning, says not; any other
1760    /// stream holding measures or notes and rests says so, unless a later
1761    /// one says not.
1762    pub fn has_part_like_streams(&self) -> bool {
1763        let mut part_like = false;
1764        for event in &self.events {
1765            let Some(stream) = event.element.as_stream() else {
1766                continue;
1767            };
1768            match stream.kind {
1769                StreamKind::Part | StreamKind::PartStaff => return true,
1770                StreamKind::Measure | StreamKind::Voice => return false,
1771                _ if event.offset != 0.0 => return false,
1772                _ => {}
1773            }
1774            let holds_music = stream.events.iter().any(|inner| {
1775                inner.element.is_instance("GeneralNote")
1776                    || inner
1777                        .element
1778                        .as_stream()
1779                        .is_some_and(|nested| nested.kind == StreamKind::Measure)
1780            });
1781            if holds_music {
1782                part_like = true;
1783            }
1784        }
1785        part_like
1786    }
1787
1788    /// The streams of one kind held directly by this one: music21's `.parts`
1789    /// on a score, `.measures` on a part, `.voices` on a measure.
1790    pub fn streams_of_kind(&self, kind: StreamKind) -> Vec<&Stream> {
1791        self.events
1792            .iter()
1793            .filter_map(|event| event.element.as_stream())
1794            .filter(|stream| stream.kind == kind)
1795            .collect()
1796    }
1797
1798    /// The parts this stream holds, a staff of a part written on several
1799    /// included: music21's `.parts`, which a `PartStaff` is one of.
1800    pub fn parts(&self) -> Vec<&Stream> {
1801        self.events
1802            .iter()
1803            .filter_map(|event| event.element.as_stream())
1804            .filter(|stream| matches!(stream.kind, StreamKind::Part | StreamKind::PartStaff))
1805            .collect()
1806    }
1807
1808    /// The measures this stream holds.
1809    ///
1810    /// ```
1811    /// use music21::{Duration, Note, Stream, StreamKind};
1812    ///
1813    /// let mut part = Stream::with_kind(StreamKind::Part);
1814    /// for name in ["C4", "D4"] {
1815    ///     let mut measure = Stream::with_kind(StreamKind::Measure);
1816    ///     measure.push(Note::from_name(name)?.with_duration(Duration::whole()));
1817    ///     part.push(measure);
1818    /// }
1819    /// assert_eq!(part.measures().len(), 2);
1820    /// assert_eq!(part.measures()[1].len(), 1);
1821    /// # Ok::<(), music21::Error>(())
1822    /// ```
1823    pub fn measures(&self) -> Vec<&Stream> {
1824        self.streams_of_kind(StreamKind::Measure)
1825    }
1826
1827    /// The voices this stream holds.
1828    pub fn voices(&self) -> Vec<&Stream> {
1829        self.streams_of_kind(StreamKind::Voice)
1830    }
1831
1832    /// The measure of a number, or `None`: music21's `measure`.
1833    ///
1834    /// Where every measure is numbered nought, as in a stream nobody has
1835    /// numbered, they are counted from one instead. A number below nought
1836    /// counts back from the last, `-1` being the last. The measure is this
1837    /// stream's own, so it carries none of the clef, key or metre in force
1838    /// before it, as in music21; [`Stream::measures_between`] collects them.
1839    /// A score is not sliced here: `measures_between(n, Some(n))` answers
1840    /// music21's `Score.measure`.
1841    ///
1842    /// ```
1843    /// use music21::{Duration, Note, Stream, StreamKind};
1844    ///
1845    /// let mut part = Stream::with_kind(StreamKind::Part);
1846    /// for (number, name) in [(1, "C4"), (2, "D4")] {
1847    ///     let mut measure = Stream::with_kind(StreamKind::Measure);
1848    ///     measure.set_number(number);
1849    ///     measure.push(Note::from_name(name)?.with_duration(Duration::whole()));
1850    ///     part.push(measure);
1851    /// }
1852    /// assert_eq!(part.measure(2).unwrap().number(), 2);
1853    /// assert_eq!(part.measure(-1).unwrap().number(), 2);
1854    /// assert!(part.measure(3).is_none());
1855    /// # Ok::<(), music21::Error>(())
1856    /// ```
1857    pub fn measure(&self, number: IntegerType) -> Option<&Stream> {
1858        let measures = self.measures();
1859        if number < 0 {
1860            let index = isize::try_from(measures.len()).ok()? + isize::try_from(number).ok()?;
1861            return measures.get(usize::try_from(index).ok()?).copied();
1862        }
1863
1864        let counted = !measures.iter().any(|measure| measure.number() != 0);
1865        measures
1866            .iter()
1867            .enumerate()
1868            .find(|(index, measure)| measure_number(*index, measure, counted) == number)
1869            .map(|(_, measure)| *measure)
1870    }
1871
1872    /// The measures numbered `start` to `end`, both included, or to the last
1873    /// where `end` is `None`: music21's `measures`.
1874    ///
1875    /// The answer is a stream of this one's kind, its first measure at
1876    /// nought, opening with the clef, metre, instrument, key and tempo in
1877    /// force where it starts, those its first measure does not open with
1878    /// itself. A spanner comes along where it joins something in the
1879    /// measures taken, naming nothing for what it joins outside them. A
1880    /// score answers a score of each part's measures, without the score's
1881    /// own spanners. Measures are numbered as [`Stream::measure`] reads
1882    /// them; music21's suffixed numbers (`'4b'`) and indices are not taken.
1883    ///
1884    /// ```
1885    /// use music21::{Clef, Duration, Note, Stream, StreamElement, StreamKind};
1886    ///
1887    /// let mut part = Stream::with_kind(StreamKind::Part);
1888    /// for (number, name) in [(1, "C3"), (2, "D3"), (3, "E3")] {
1889    ///     let mut measure = Stream::with_kind(StreamKind::Measure);
1890    ///     measure.set_number(number);
1891    ///     if number == 1 {
1892    ///         measure.insert(0.0, Clef::bass());
1893    ///     }
1894    ///     measure.push(Note::from_name(name)?.with_duration(Duration::whole()));
1895    ///     part.push(measure);
1896    /// }
1897    /// let excerpt = part.measures_between(2, None);
1898    /// assert!(matches!(excerpt.events()[0].element(), StreamElement::Clef(_)));
1899    /// let numbers: Vec<i32> = excerpt.measures().iter().map(|m| m.number()).collect();
1900    /// assert_eq!(numbers, [2, 3]);
1901    /// assert_eq!(excerpt.events()[1].offset(), 0.0);
1902    /// # Ok::<(), music21::Error>(())
1903    /// ```
1904    pub fn measures_between(&self, start: IntegerType, end: Option<IntegerType>) -> Stream {
1905        if self.kind == StreamKind::Score {
1906            let mut out = self.clone_empty();
1907            out.labels.staff_groups = self.labels.staff_groups.clone();
1908            for part in self.parts() {
1909                out.events
1910                    .push(StreamEvent::new(0.0, part.measures_between(start, end)));
1911            }
1912            return out;
1913        }
1914
1915        let measured: Vec<usize> = self
1916            .events
1917            .iter()
1918            .enumerate()
1919            .filter(|(_, event)| {
1920                event
1921                    .element
1922                    .as_stream()
1923                    .is_some_and(|stream| stream.kind == StreamKind::Measure)
1924            })
1925            .map(|(index, _)| index)
1926            .collect();
1927        let counted = !measured.iter().any(|&index| {
1928            self.events[index]
1929                .element
1930                .as_stream()
1931                .is_some_and(|measure| measure.number() != 0)
1932        });
1933        let matches: Vec<usize> = measured
1934            .iter()
1935            .enumerate()
1936            .filter(|(count, index)| {
1937                let Some(measure) = self.events[**index].element.as_stream() else {
1938                    return false;
1939                };
1940                let number = measure_number(*count, measure, counted);
1941                number >= start && end.is_none_or(|end| number <= end)
1942            })
1943            .map(|(_, index)| *index)
1944            .collect();
1945        let mut out = self.clone_empty();
1946        let Some(&first) = matches.first() else {
1947            return out;
1948        };
1949
1950        let begins = self.events[first].offset;
1951        let mut kept = self.collected_before(first);
1952        kept.extend(matches.iter().map(|&index| {
1953            let event = &self.events[index];
1954            let offset = crate::makenotation::op_frac(event.offset - begins);
1955            (StreamEvent::new(offset, event.element.clone()), Some(index))
1956        }));
1957        out.labels.spanners = self.labels.spanners.clone();
1958        out.events = self.events.clone();
1959        out.replace_events(kept);
1960        out.labels
1961            .spanners
1962            .retain(|spanner| spanner.spanned().iter().any(Option::is_some));
1963        out
1964    }
1965
1966    /// What music21's `measures` collects for the measure at `index`: of
1967    /// each class it collects, the one in force where the measure starts,
1968    /// unless the measure opens with one itself; in music21's order, at
1969    /// nought.
1970    fn collected_before(&self, index: usize) -> Vec<(StreamEvent, Option<usize>)> {
1971        const COLLECTED: [&str; 5] = [
1972            "Clef",
1973            "TimeSignature",
1974            "Instrument",
1975            "KeySignature",
1976            "MetronomeMark",
1977        ];
1978        let Some(measure) = self.events[index].element.as_stream() else {
1979            return Vec::new();
1980        };
1981
1982        let begins = self.events[index].offset;
1983        let flat = self.flatten();
1984        let mut found: Vec<StreamEvent> = COLLECTED
1985            .iter()
1986            .filter(|class| !opens_with(measure, class))
1987            .filter_map(|class| {
1988                flat.events
1989                    .iter()
1990                    .take_while(|event| event.offset <= begins)
1991                    .filter(|event| event.element.is_instance(class))
1992                    .last()
1993                    .map(|event| StreamEvent::new(0.0, event.element.clone()))
1994            })
1995            .collect();
1996        // music21 sorts these before the measure whatever their class.
1997        found.sort_by(crate::makenotation::event_order);
1998        found.into_iter().map(|event| (event, None)).collect()
1999    }
2000
2001    /// Every note and chord on the flattened timeline: music21's
2002    /// `flatten().notes`, which leaves rests out.
2003    ///
2004    /// ```
2005    /// use music21::{Chord, Note, Rest, Stream};
2006    ///
2007    /// let mut stream = Stream::new();
2008    /// stream.push(Note::from_name("C4")?);
2009    /// stream.push(Rest::default());
2010    /// stream.push(Chord::new("E4 G4")?);
2011    /// let offsets: Vec<f64> = stream.notes().iter().map(|(offset, _)| *offset).collect();
2012    /// assert_eq!(offsets, [0.0, 2.0]);
2013    /// # Ok::<(), music21::Error>(())
2014    /// ```
2015    pub fn notes(&self) -> Vec<(FloatType, StreamElement)> {
2016        self.flatten()
2017            .events
2018            .into_iter()
2019            .filter(|event| event.element.is_note_or_chord())
2020            .map(|event| (event.offset, event.element))
2021            .collect()
2022    }
2023
2024    /// Returns the maximum event end offset, a nested stream's own length
2025    /// included, snapped to the fraction it stands for: music21's
2026    /// `highestTime`.
2027    pub fn end_offset(&self) -> FloatType {
2028        crate::makenotation::op_frac(
2029            self.events
2030                .iter()
2031                .map(StreamEvent::end_offset)
2032                .fold(0.0, FloatType::max),
2033        )
2034    }
2035
2036    /// Returns all pitches in timeline order, from nested streams too.
2037    pub fn pitches(&self) -> Vec<Pitch> {
2038        self.flatten()
2039            .events
2040            .iter()
2041            .flat_map(|event| event.element.pitches())
2042            .collect()
2043    }
2044
2045    /// The key signature in force at an offset: the last one written at or
2046    /// before it, anywhere in the nesting.
2047    ///
2048    /// This is what music21 answers with `getContextByClass(KeySignature)`,
2049    /// found by looking back along the flattened timeline rather than by
2050    /// walking the sites an object belongs to.
2051    pub fn key_signature_at(&self, offset: FloatType) -> Option<KeySignature> {
2052        self.in_force_at(offset, |element| match element {
2053            StreamElement::KeySignature(key) => Some(key.clone()),
2054            StreamElement::Key(key) => Some(key.key_signature()),
2055            _ => None,
2056        })
2057    }
2058
2059    /// The metre in force at an offset, found the same way.
2060    pub fn time_signature_at(&self, offset: FloatType) -> Option<TimeSignature> {
2061        self.in_force_at(offset, |element| match element {
2062            StreamElement::TimeSignature(meter) => Some(meter.clone()),
2063            _ => None,
2064        })
2065    }
2066
2067    /// The tempo in force at an offset, found the same way.
2068    pub fn metronome_mark_at(&self, offset: FloatType) -> Option<MetronomeMark> {
2069        self.in_force_at(offset, |element| match element {
2070            StreamElement::MetronomeMark(mark) => Some(mark.clone()),
2071            _ => None,
2072        })
2073    }
2074
2075    /// The last thing of one sort written at or before an offset.
2076    fn in_force_at<T>(
2077        &self,
2078        offset: FloatType,
2079        read: impl Fn(&StreamElement) -> Option<T>,
2080    ) -> Option<T> {
2081        self.flatten()
2082            .events
2083            .iter()
2084            .take_while(|event| event.offset <= offset)
2085            .filter_map(|event| read(&event.element))
2086            .last()
2087    }
2088
2089    /// Returns a transposed copy, nesting and all.
2090    pub fn transpose(&self, interval: &Interval) -> Result<Self> {
2091        let events = self
2092            .events
2093            .iter()
2094            .map(|event| {
2095                Ok(StreamEvent::new(
2096                    event.offset,
2097                    event.element.transpose(interval)?,
2098                ))
2099            })
2100            .collect::<Result<Vec<_>>>()?;
2101        let mut out = Self::with_kind(self.kind);
2102        out.labels = self.labels.clone();
2103        out.events = events;
2104        out.sort_events();
2105        Ok(out)
2106    }
2107
2108    /// Puts the events in offset order, keeping the order they were given
2109    /// in at one offset: how [`Stream::from_events`] takes an order from a
2110    /// caller that knows more of it than the crate does, music21's
2111    /// priorities among them.
2112    fn sort_events(&mut self) {
2113        self.events.sort_by(|left, right| {
2114            left.offset
2115                .partial_cmp(&right.offset)
2116                .unwrap_or(std::cmp::Ordering::Equal)
2117        });
2118    }
2119}
2120
2121/// A measure's number, or where every measure is numbered nought, its
2122/// place counted from one, as music21 reads measures by number.
2123fn measure_number(index: usize, measure: &Stream, counted: bool) -> IntegerType {
2124    if !counted {
2125        return measure.number();
2126    }
2127
2128    IntegerType::try_from(index + 1).unwrap_or(IntegerType::MAX)
2129}
2130
2131/// Whether a stream, or one nested in it, holds something of `class` at
2132/// its own start.
2133fn opens_with(stream: &Stream, class: &str) -> bool {
2134    stream.events.iter().any(|event| {
2135        (event.offset == 0.0 && event.element.is_instance(class))
2136            || event
2137                .element
2138                .as_stream()
2139                .is_some_and(|inner| opens_with(inner, class))
2140    })
2141}
2142
2143/// Whether an element is a grace note or chord, which takes no time.
2144fn is_grace(element: &StreamElement) -> bool {
2145    element.duration().is_some_and(Duration::is_grace)
2146}
2147
2148/// How many leaves an element is: those of a nested stream, or itself.
2149fn leaf_count(element: &StreamElement) -> usize {
2150    match element {
2151        StreamElement::Stream(inner) => inner.leaves().len(),
2152        _ => 1,
2153    }
2154}
2155
2156impl<'a> IntoIterator for &'a Stream {
2157    type Item = &'a StreamEvent;
2158    type IntoIter = std::slice::Iter<'a, StreamEvent>;
2159
2160    fn into_iter(self) -> Self::IntoIter {
2161        self.events.iter()
2162    }
2163}
2164
2165#[cfg(test)]
2166mod tests {
2167    #[test]
2168    fn a_stream_has_part_like_streams_as_music21_decides() {
2169        use super::{Stream, StreamKind};
2170        use crate::note::Note;
2171
2172        // music21's own examples: a part, a measure, one generic stream at
2173        // the start, and a second one appended after it.
2174        let four_notes = |kind: StreamKind| {
2175            let mut stream = Stream::with_kind(kind);
2176            for _ in 0..4 {
2177                stream.push(Note::from_name("C4").unwrap());
2178            }
2179            stream
2180        };
2181        let mut score = Stream::with_kind(StreamKind::Score);
2182        assert!(!score.has_part_like_streams());
2183        score.insert(0.0, four_notes(StreamKind::Part));
2184        assert!(score.has_part_like_streams());
2185
2186        let mut score = Stream::with_kind(StreamKind::Score);
2187        score.push(four_notes(StreamKind::Measure));
2188        assert!(!score.has_part_like_streams());
2189
2190        let mut score = Stream::with_kind(StreamKind::Score);
2191        score.push(four_notes(StreamKind::Stream));
2192        assert!(score.has_part_like_streams());
2193        score.push(four_notes(StreamKind::Stream));
2194        assert!(!score.has_part_like_streams());
2195    }
2196
2197    #[test]
2198    fn a_stream_says_what_kind_it_is_and_walks_its_events() {
2199        use super::{Stream, StreamElement, StreamEvent, StreamKind};
2200        use crate::note::Note;
2201        use crate::pitch::Pitch;
2202        use crate::tempo::MetronomeMark;
2203
2204        assert_eq!(StreamKind::Voice.as_str(), "Voice");
2205        assert_eq!(StreamKind::Voice.to_string(), "Voice");
2206        let mut stream = Stream::new();
2207        assert!(stream.is_empty());
2208        stream.set_kind(StreamKind::Voice);
2209        assert_eq!(stream.kind(), StreamKind::Voice);
2210        assert!(matches!(
2211            StreamElement::from(MetronomeMark::new(120.0)),
2212            StreamElement::MetronomeMark(_)
2213        ));
2214
2215        let note = Note::from_pitch(Pitch::from_name("C4").unwrap());
2216        let rebuilt = Stream::from_events([StreamEvent::new(0.0, note)]);
2217        assert_eq!(rebuilt.iter().count(), 1);
2218        assert!(!rebuilt.is_empty());
2219        assert!(rebuilt.voices().is_empty());
2220        let mut outer = Stream::new();
2221        outer.push(stream);
2222        assert_eq!(outer.voices().len(), 1);
2223    }
2224
2225    use super::*;
2226
2227    #[test]
2228    fn a_stream_iterates_by_reference() {
2229        let mut stream = Stream::new();
2230        stream.push(Note::from_name("C4").unwrap());
2231        stream.push(Note::from_name("E4").unwrap());
2232
2233        let offsets: Vec<FloatType> = (&stream).into_iter().map(StreamEvent::offset).collect();
2234        assert_eq!(offsets, vec![0.0, 1.0]);
2235        assert_eq!((&stream).into_iter().count(), stream.len());
2236    }
2237
2238    #[test]
2239    fn stream_push_uses_durations() {
2240        let mut stream = Stream::new();
2241        stream.push(
2242            Note::from_name("C4")
2243                .unwrap()
2244                .with_duration(Duration::half()),
2245        );
2246        stream.push(Rest::from_quarter_length(0.5).unwrap());
2247        assert_eq!(stream.events()[0].offset(), 0.0);
2248        assert_eq!(stream.events()[1].offset(), 2.0);
2249        assert_eq!(stream.end_offset(), 2.5);
2250    }
2251
2252    #[test]
2253    fn a_clef_inserted_after_a_note_sorts_before_it() {
2254        // music21 sorts what stands at one offset by its class order, so
2255        // a clef put in after a note at the start still comes first.
2256        let mut stream = Stream::new();
2257        stream.insert(0.0, Note::from_name("C4").unwrap());
2258        stream.insert(0.0, Clef::treble());
2259        assert!(matches!(
2260            stream.events()[0].element(),
2261            StreamElement::Clef(_)
2262        ));
2263        assert!(matches!(
2264            stream.events()[1].element(),
2265            StreamElement::Note(_)
2266        ));
2267    }
2268
2269    #[test]
2270    fn a_clef_pushed_after_a_dynamic_sorts_before_it() {
2271        // music21's `append` sorts a stream again where what is appended
2272        // would sort before the last element.
2273        let mut stream = Stream::new();
2274        stream.push(Dynamic::new("p"));
2275        stream.push(Clef::treble());
2276        assert!(matches!(
2277            stream.events()[0].element(),
2278            StreamElement::Clef(_)
2279        ));
2280        assert!(matches!(
2281            stream.events()[1].element(),
2282            StreamElement::Dynamic(_)
2283        ));
2284    }
2285
2286    #[test]
2287    fn first_and_last_follow_the_streams_order() {
2288        let mut stream = Stream::new();
2289        assert!(stream.first().is_none());
2290        assert!(stream.last().is_none());
2291        stream.insert(1.0, Note::from_name("D4").unwrap());
2292        stream.insert(0.0, Note::from_name("C4").unwrap());
2293        stream.insert(0.0, Clef::treble());
2294        assert!(matches!(
2295            stream.first().unwrap().element(),
2296            StreamElement::Clef(_)
2297        ));
2298        assert_eq!(stream.last().unwrap().offset(), 1.0);
2299    }
2300
2301    #[test]
2302    fn clear_takes_out_what_music21_holds_as_elements() {
2303        let mut measure = Stream::with_kind(StreamKind::Measure);
2304        measure.set_number(3);
2305        measure.set_id(Some("m3".to_string()));
2306        measure.push(Note::from_name("C4").unwrap());
2307        measure.set_right_barline(Some(Barline::default()));
2308        measure.set_left_barline(Some(Barline::default()));
2309        measure.set_metadata(Some(Metadata::default()));
2310        measure.add_staff_group(StaffGroup::new(vec![0]));
2311        measure.clear();
2312        assert!(measure.is_empty());
2313        assert!(measure.right_barline().is_none());
2314        assert!(measure.left_barline().is_none());
2315        assert!(measure.metadata().is_none());
2316        assert!(measure.staff_groups().is_empty());
2317        assert!(measure.spanners().is_empty());
2318        assert_eq!(measure.number(), 3);
2319        assert_eq!(measure.id(), Some("m3"));
2320        assert_eq!(measure.kind(), StreamKind::Measure);
2321    }
2322
2323    #[test]
2324    fn the_clef_is_one_held_at_the_start() {
2325        let mut measure = Stream::with_kind(StreamKind::Measure);
2326        measure.insert(2.0, Clef::bass());
2327        assert!(
2328            measure.clef().is_none(),
2329            "a clef later on is not the opening one"
2330        );
2331        measure.insert(0.0, Clef::treble());
2332        assert_eq!(measure.clef().unwrap().sign(), Some("G"));
2333
2334        let mut part = Stream::with_kind(StreamKind::Part);
2335        part.push(measure);
2336        assert!(part.clef().is_none(), "a measure's clef is not its part's");
2337    }
2338
2339    #[test]
2340    fn a_streams_duration_is_its_highest_time() {
2341        let mut stream = Stream::new();
2342        assert_eq!(stream.duration().unwrap().quarter_length(), 0.0);
2343        stream.repeat_insert(
2344            &Note::from_name("C4").unwrap().into(),
2345            &[0.0, 1.0, 2.0, 3.0],
2346        );
2347        assert_eq!(stream.duration().unwrap().quarter_length(), 4.0);
2348        stream.insert(FloatType::INFINITY, Clef::treble());
2349        assert!(stream.duration().is_err());
2350    }
2351
2352    #[test]
2353    fn an_element_is_found_by_its_id_in_any_case() {
2354        let mut note = Note::from_name("C4").unwrap();
2355        note.set_id(Some("green".to_string()));
2356        let mut stream = Stream::new();
2357        stream.push(Rest::default());
2358        stream.push(note);
2359        assert_eq!(stream.element_by_id("Green").unwrap().offset(), 1.0);
2360        assert!(stream.element_by_id("blue").is_none());
2361
2362        // only this stream's own elements are looked at
2363        let mut outer = Stream::new();
2364        outer.push(stream);
2365        assert!(outer.element_by_id("green").is_none());
2366    }
2367
2368    /// A part of measures of these numbers, each a whole note long, the
2369    /// first opening with a bass clef and 4/4, a key change in the third.
2370    fn numbered_part(numbers: &[IntegerType]) -> Stream {
2371        let mut part = Stream::with_kind(StreamKind::Part);
2372        for (index, &number) in numbers.iter().enumerate() {
2373            let mut measure = Stream::with_kind(StreamKind::Measure);
2374            measure.set_number(number);
2375            if index == 0 {
2376                measure.insert(0.0, Clef::bass());
2377                measure.insert(0.0, TimeSignature::new(4, 4).unwrap());
2378                measure.insert(0.0, KeySignature::new(1));
2379            }
2380            if index == 2 {
2381                measure.insert(0.0, KeySignature::new(-2));
2382            }
2383            measure.push(
2384                Note::from_name("C3")
2385                    .unwrap()
2386                    .with_duration(Duration::whole()),
2387            );
2388            part.push(measure);
2389        }
2390        part
2391    }
2392
2393    #[test]
2394    fn a_measure_is_found_by_its_number() {
2395        let part = numbered_part(&[0, 1, 2, 3]);
2396        assert_eq!(part.measure(0).unwrap().number(), 0);
2397        assert_eq!(part.measure(2).unwrap().number(), 2);
2398        assert!(part.measure(9).is_none());
2399        assert_eq!(part.measure(-1).unwrap().number(), 3);
2400        assert_eq!(part.measure(-4).unwrap().number(), 0);
2401        assert!(part.measure(-5).is_none());
2402
2403        // all numbered nought: counted from one
2404        let unnumbered = numbered_part(&[0, 0, 0]);
2405        assert!(unnumbered.measure(0).is_none());
2406        assert_eq!(unnumbered.measure(2).unwrap().end_offset(), 4.0);
2407        assert!(std::ptr::eq(
2408            unnumbered.measure(2).unwrap(),
2409            unnumbered.measures()[1]
2410        ));
2411    }
2412
2413    #[test]
2414    fn measures_between_collect_what_is_in_force() {
2415        let part = numbered_part(&[1, 2, 3, 4]);
2416        let excerpt = part.measures_between(2, Some(3));
2417        assert_eq!(excerpt.kind(), StreamKind::Part);
2418        let classes: Vec<&str> = excerpt
2419            .events()
2420            .iter()
2421            .map(|event| event.element().music21_classes()[0])
2422            .collect();
2423        assert_eq!(
2424            classes,
2425            [
2426                "BassClef",
2427                "KeySignature",
2428                "TimeSignature",
2429                "Measure",
2430                "Measure"
2431            ]
2432        );
2433        assert!(
2434            excerpt
2435                .events()
2436                .iter()
2437                .take(3)
2438                .all(|event| event.offset() == 0.0)
2439        );
2440        let numbers: Vec<IntegerType> = excerpt.measures().iter().map(|m| m.number()).collect();
2441        assert_eq!(numbers, [2, 3]);
2442        assert_eq!(excerpt.events()[4].offset(), 4.0);
2443
2444        // the measure opening with a key of its own takes no other
2445        let from_three = part.measures_between(3, None);
2446        let keys = from_three
2447            .events()
2448            .iter()
2449            .filter(|event| event.element().is_instance("KeySignature"))
2450            .count();
2451        assert_eq!(keys, 0);
2452        assert_eq!(from_three.measures().len(), 2);
2453
2454        // the first measure carries its own; nothing is collected
2455        assert_eq!(part.measures_between(1, Some(1)).len(), 1);
2456        assert!(part.measures_between(7, Some(9)).is_empty());
2457    }
2458
2459    #[test]
2460    fn a_score_answers_measures_of_each_part() {
2461        let mut score = Stream::with_kind(StreamKind::Score);
2462        score.set_id(Some("full".to_string()));
2463        score.insert(0.0, numbered_part(&[1, 2, 3]));
2464        score.insert(0.0, numbered_part(&[1, 2, 3]));
2465        score.add_staff_group(StaffGroup::new(vec![0, 1]));
2466        let slice = score.measures_between(2, Some(2));
2467        assert_eq!(slice.kind(), StreamKind::Score);
2468        assert_eq!(slice.id(), Some("full"));
2469        assert_eq!(slice.parts().len(), 2);
2470        assert_eq!(slice.parts()[1].measures().len(), 1);
2471        assert_eq!(slice.staff_groups().len(), 1);
2472    }
2473
2474    #[test]
2475    fn stream_transposes_notes_and_chords() {
2476        let mut stream = Stream::new();
2477        stream.push(Note::from_name("C4").unwrap());
2478        stream.push(Chord::new("E4 G4").unwrap());
2479        let out = stream
2480            .transpose(&Interval::from_name("M2").unwrap())
2481            .unwrap();
2482        let names = out
2483            .pitches()
2484            .iter()
2485            .map(Pitch::name_with_octave)
2486            .collect::<Vec<_>>();
2487        assert_eq!(names, vec!["D4", "F#4", "A4"]);
2488    }
2489
2490    /// A score of one part of two measures, which is the shape music21 puts
2491    /// almost everything in.
2492    fn two_measure_score() -> Stream {
2493        let mut first = Stream::with_kind(StreamKind::Measure);
2494        first.insert(0.0, KeySignature::new(2));
2495        first.insert(0.0, TimeSignature::new(4, 4).unwrap());
2496        first.push(Note::from_name("D4").unwrap());
2497        first.push(Note::from_name("E4").unwrap());
2498        first.push(Note::from_name("F#4").unwrap());
2499        first.push(Note::from_name("G4").unwrap());
2500
2501        let mut second = Stream::with_kind(StreamKind::Measure);
2502        second.insert(0.0, KeySignature::new(-1));
2503        second.push(Note::from_name("A4").unwrap());
2504        second.push(Note::from_name("Bb4").unwrap());
2505
2506        let mut part = Stream::with_kind(StreamKind::Part);
2507        part.push(first);
2508        part.push(second);
2509
2510        let mut score = Stream::with_kind(StreamKind::Score);
2511        score.push(part);
2512        score
2513    }
2514
2515    #[test]
2516    fn a_nested_stream_flattens_onto_one_timeline() {
2517        let score = two_measure_score();
2518        assert_eq!(score.kind(), StreamKind::Score);
2519        assert_eq!(score.len(), 1, "a score holds its one part, not its notes");
2520        assert_eq!(score.parts().len(), 1);
2521        assert_eq!(score.parts()[0].measures().len(), 2);
2522
2523        // the second measure starts a bar in, so its notes do too
2524        let notes = score.notes();
2525        let offsets: Vec<FloatType> = notes.iter().map(|(offset, _)| *offset).collect();
2526        assert_eq!(offsets, vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0]);
2527        assert_eq!(score.end_offset(), 6.0);
2528
2529        let names: Vec<String> = score
2530            .pitches()
2531            .iter()
2532            .map(Pitch::name_with_octave)
2533            .collect();
2534        assert_eq!(names, ["D4", "E4", "F#4", "G4", "A4", "Bb4"]);
2535
2536        // recurse sees the streams themselves; flatten does not
2537        assert_eq!(score.recurse().len(), 1 + 2 + 6 + 3);
2538        assert_eq!(score.flatten().len(), 6 + 3);
2539    }
2540
2541    #[test]
2542    fn the_key_in_force_is_the_last_one_written_before_it() {
2543        let score = two_measure_score();
2544        assert_eq!(score.key_signature_at(0.0).unwrap().sharps(), 2);
2545        assert_eq!(score.key_signature_at(3.5).unwrap().sharps(), 2);
2546        // the second measure changes it
2547        assert_eq!(score.key_signature_at(4.0).unwrap().sharps(), -1);
2548        assert_eq!(score.key_signature_at(100.0).unwrap().sharps(), -1);
2549        assert_eq!(
2550            score.time_signature_at(5.0).unwrap().ratio_string(),
2551            "4/4",
2552            "a metre stays in force across the bar that follows it"
2553        );
2554        assert!(score.metronome_mark_at(0.0).is_none());
2555
2556        // nothing is in force before the first mark
2557        let mut late = Stream::new();
2558        late.insert(2.0, KeySignature::new(3));
2559        assert!(late.key_signature_at(1.0).is_none());
2560        assert_eq!(late.key_signature_at(2.0).unwrap().sharps(), 3);
2561    }
2562
2563    #[test]
2564    fn transposing_a_score_moves_its_key_signatures_too() {
2565        let score = two_measure_score();
2566        let up = score
2567            .transpose(&Interval::from_name("M2").unwrap())
2568            .unwrap();
2569        assert_eq!(up.key_signature_at(0.0).unwrap().sharps(), 4);
2570        assert_eq!(up.key_signature_at(4.0).unwrap().sharps(), 1);
2571        let names: Vec<String> = up.pitches().iter().map(Pitch::name_with_octave).collect();
2572        assert_eq!(names, ["E4", "F#4", "G#4", "A4", "B4", "C5"]);
2573        assert_eq!(up.kind(), StreamKind::Score);
2574    }
2575}