musicxml/datatypes/
font_size.rs

1use super::css_font_size::CssFontSize;
2use alloc::string::{String, ToString};
3use musicxml_internal::{DatatypeDeserializer, DatatypeSerializer};
4
5/// Can be one of the [CSS font sizes](https://www.w3.org/2021/06/musicxml40/musicxml-reference/data-types/css-font-size/)
6/// or a [decimal](https://www.w3.org/2021/06/musicxml40/musicxml-reference/data-types/xsd-decimal/) point size.
7#[derive(Debug, PartialEq)]
8pub enum FontSize {
9  /// One of the [CSS font sizes](https://www.w3.org/2021/06/musicxml40/musicxml-reference/data-types/css-font-size/).
10  Css(CssFontSize),
11  /// A [decimal](https://www.w3.org/2021/06/musicxml40/musicxml-reference/data-types/xsd-decimal/) point size.
12  Decimal(f32),
13}
14
15impl Eq for FontSize {}
16
17impl DatatypeSerializer for FontSize {
18  fn serialize(element: &Self) -> String {
19    match element {
20      Self::Css(font_size) => CssFontSize::serialize(font_size),
21      Self::Decimal(number) => number.to_string(),
22    }
23  }
24}
25
26impl DatatypeDeserializer for FontSize {
27  fn deserialize(value: &str) -> Result<Self, String> {
28    if let Ok(dec_val) = value.parse::<f32>() {
29      if dec_val > 0.0 {
30        Ok(FontSize::Decimal(dec_val))
31      } else {
32        Err(format!("Value {value} is invalid for the <font-size> data type"))
33      }
34    } else if let Ok(font_size) = CssFontSize::deserialize(value) {
35      Ok(FontSize::Css(font_size))
36    } else {
37      Err(format!("Value {value} is invalid for the <font-size> data type"))
38    }
39  }
40}
41
42#[cfg(test)]
43mod font_size_tests {
44  use super::*;
45
46  #[test]
47  fn deserialize_valid1() {
48    let result = FontSize::deserialize("xx-small");
49    assert!(result.is_ok());
50    assert_eq!(result.unwrap(), FontSize::Css(CssFontSize::XxSmall));
51  }
52
53  #[test]
54  fn deserialize_valid2() {
55    let result = FontSize::deserialize("3");
56    assert!(result.is_ok());
57    assert_eq!(result.unwrap(), FontSize::Decimal(3.0));
58  }
59
60  #[test]
61  fn deserialize_invalid1() {
62    let result = FontSize::deserialize("Big");
63    assert!(result.is_err());
64  }
65
66  #[test]
67  fn deserialize_invalid2() {
68    let result = FontSize::deserialize("0");
69    assert!(result.is_err());
70  }
71
72  #[test]
73  fn deserialize_invalid3() {
74    let result = FontSize::deserialize("-4");
75    assert!(result.is_err());
76  }
77}