musicxml/datatypes/
comma_separated_text.rs

1use alloc::{string::String, string::ToString, vec::Vec};
2use core::ops::Deref;
3use musicxml_internal::{DatatypeDeserializer, DatatypeSerializer};
4
5/// Used to specify a comma-separated list of text elements, as is used by the `font_family` attribute.
6///
7/// The value of an instance of this type may be accessed by dereferencing the struct: `*datatype_val`.
8#[derive(Debug, PartialEq, Eq)]
9pub struct CommaSeparatedText(pub Vec<String>);
10
11impl Deref for CommaSeparatedText {
12  type Target = Vec<String>;
13  fn deref(&self) -> &Self::Target {
14    &self.0
15  }
16}
17
18impl DatatypeSerializer for CommaSeparatedText {
19  fn serialize(element: &Self) -> String {
20    element.0.join(",")
21  }
22}
23
24impl DatatypeDeserializer for CommaSeparatedText {
25  fn deserialize(value: &str) -> Result<Self, String> {
26    let mut text: Vec<String> = Vec::new();
27    value.split(',').for_each(|item| {
28      let res = item.trim();
29      if !res.is_empty() {
30        text.push(res.to_string());
31      }
32    });
33    Ok(CommaSeparatedText(text))
34  }
35}
36
37#[cfg(test)]
38mod comma_separated_text_tests {
39  use super::*;
40
41  #[test]
42  fn deserialize_valid1() {
43    let result = CommaSeparatedText::deserialize("Ariel");
44    assert!(result.is_ok());
45    assert_eq!(result.unwrap(), CommaSeparatedText(vec![String::from("Ariel")]));
46  }
47
48  #[test]
49  fn deserialize_valid2() {
50    let result = CommaSeparatedText::deserialize("Ariel,Times New Roman");
51    assert!(result.is_ok());
52    assert_eq!(
53      result.unwrap(),
54      CommaSeparatedText(vec![String::from("Ariel"), String::from("Times New Roman")])
55    );
56  }
57
58  #[test]
59  fn deserialize_valid3() {
60    let result = CommaSeparatedText::deserialize("Ariel, Courier,Helvetica");
61    assert!(result.is_ok());
62    assert_eq!(
63      result.unwrap(),
64      CommaSeparatedText(vec![
65        String::from("Ariel"),
66        String::from("Courier"),
67        String::from("Helvetica")
68      ])
69    );
70  }
71
72  #[test]
73  fn deserialize_valid4() {
74    let result = CommaSeparatedText::deserialize(",Ariel, Courier,Helvetica");
75    assert!(result.is_ok());
76    assert_eq!(
77      result.unwrap(),
78      CommaSeparatedText(vec![
79        String::from("Ariel"),
80        String::from("Courier"),
81        String::from("Helvetica")
82      ])
83    );
84  }
85
86  #[test]
87  fn deserialize_valid5() {
88    let result = CommaSeparatedText::deserialize(",Ariel");
89    assert!(result.is_ok());
90    assert_eq!(result.unwrap(), CommaSeparatedText(vec![String::from("Ariel")]));
91  }
92}