Skip to main content

music21_rs/
rest.rs

1use crate::duration::Duration;
2
3/// A silent musical event with a duration.
4#[derive(Clone, Debug, PartialEq)]
5#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
6pub struct Rest {
7    duration: Duration,
8}
9
10impl Rest {
11    /// Creates a rest with the supplied duration.
12    pub fn new(duration: Duration) -> Self {
13        Self { duration }
14    }
15
16    /// Creates a rest from a quarter-length value.
17    pub fn from_quarter_length(quarter_length: crate::FloatType) -> crate::Result<Self> {
18        Ok(Self::new(Duration::new(quarter_length)?))
19    }
20
21    /// Returns the rest duration.
22    pub fn duration(&self) -> &Duration {
23        &self.duration
24    }
25
26    /// Updates the rest duration.
27    pub fn set_duration(&mut self, duration: Duration) {
28        self.duration = duration;
29    }
30
31    /// Returns the duration in quarter lengths.
32    pub fn quarter_length(&self) -> crate::FloatType {
33        self.duration.quarter_length()
34    }
35}
36
37impl Default for Rest {
38    fn default() -> Self {
39        Self::new(Duration::default())
40    }
41}
42
43impl From<Duration> for Rest {
44    fn from(value: Duration) -> Self {
45        Self::new(value)
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52
53    #[test]
54    fn rest_has_duration() {
55        let rest = Rest::from_quarter_length(2.0).unwrap();
56        assert_eq!(rest.quarter_length(), 2.0);
57    }
58
59    #[test]
60    fn rest_supports_default_from_and_updates() {
61        let mut rest = Rest::default();
62        assert_eq!(rest.quarter_length(), 1.0);
63
64        rest.set_duration(Duration::whole());
65        assert_eq!(rest.duration(), &Duration::whole());
66
67        let half_rest = Rest::from(Duration::half());
68        assert_eq!(half_rest.quarter_length(), 2.0);
69        assert!(Rest::from_quarter_length(crate::FloatType::NAN).is_err());
70    }
71}