1use crate::defaults::{FloatType, IntegerType};
12use crate::error::{Error, Result};
13use crate::notation::{Syllabic, TieType};
14
15pub const WRITTEN_ACCIDENTALS: [(&str, &str); 17] = [
18 ("s", "#"),
19 ("f", "-"),
20 ("ss", "##"),
21 ("x", "##"),
22 ("ff", "--"),
23 ("xs", "###"),
24 ("ts", "###"),
25 ("tf", "---"),
26 ("n", "n"),
27 ("nf", "-"),
28 ("ns", "#"),
29 ("su", "#~"),
30 ("sd", "~"),
31 ("fu", "`"),
32 ("fd", "-`"),
33 ("nu", "~"),
34 ("nd", "`"),
35];
36
37pub const GESTURAL_ACCIDENTALS: [(&str, &str); 9] = [
40 ("s", "#"),
41 ("f", "-"),
42 ("ss", "##"),
43 ("ff", "--"),
44 ("n", "n"),
45 ("su", "#~"),
46 ("sd", "~"),
47 ("fu", "`"),
48 ("fd", "-`"),
49];
50
51pub const DURATIONS: [(&str, FloatType); 14] = [
53 ("long", 16.0),
54 ("breve", 8.0),
55 ("1", 4.0),
56 ("2", 2.0),
57 ("4", 1.0),
58 ("8", 0.5),
59 ("16", 0.25),
60 ("32", 0.125),
61 ("64", 0.0625),
62 ("128", 0.03125),
63 ("256", 0.015625),
64 ("512", 0.0078125),
65 ("1024", 0.00390625),
66 ("2048", 0.001953125),
67];
68
69pub const NO_DURATION: FloatType = 0.00390625;
72
73pub const PLAIN_ARTICULATION: &str = "Articulation";
75
76pub const ARTICULATIONS: [(&str, &str); 30] = [
79 ("acc", "Accent"),
80 ("stacc", "Staccato"),
81 ("ten", "Tenuto"),
82 ("stacciss", "Staccatissimo"),
83 ("marc", "StrongAccent"),
84 ("spicc", "Spiccato"),
85 ("doit", "Doit"),
86 ("plop", "Plop"),
87 ("fall", "Falloff"),
88 ("dnbow", "DownBow"),
89 ("upbow", "UpBow"),
90 ("harm", "Harmonic"),
91 ("snap", "SnapPizzicato"),
92 ("stop", "Stopped"),
93 ("open", "OpenString"),
94 ("dbltongue", "DoubleTongue"),
95 ("toe", "OrganToe"),
96 ("trpltongue", "TripleTongue"),
97 ("heel", "OrganHeel"),
98 ("tap", PLAIN_ARTICULATION),
99 ("lhpizz", PLAIN_ARTICULATION),
100 ("dot", PLAIN_ARTICULATION),
101 ("stroke", PLAIN_ARTICULATION),
102 ("rip", PLAIN_ARTICULATION),
103 ("bend", PLAIN_ARTICULATION),
104 ("flip", PLAIN_ARTICULATION),
105 ("smear", PLAIN_ARTICULATION),
106 ("fingernail", PLAIN_ARTICULATION),
107 ("damp", PLAIN_ARTICULATION),
108 ("dampall", PLAIN_ARTICULATION),
109];
110
111pub const COMPOUND_ARTICULATIONS: [(&str, [&str; 2]); 2] = [
114 ("marc-stacc", ["StrongAccent", "Staccato"]),
115 ("ten-stacc", ["Tenuto", "Staccato"]),
116];
117
118pub const BARLINES: [(&str, &str); 6] = [
121 ("dashed", "dashed"),
122 ("dotted", "dotted"),
123 ("dbl", "double"),
124 ("end", "final"),
125 ("invis", "none"),
126 ("single", "regular"),
127];
128
129pub const REPEAT_PREFIX: &str = "rpt";
131
132pub const TREMOLO_MARKS: [(&str, IntegerType); 8] = [
135 ("8", 1),
136 ("16", 2),
137 ("32", 3),
138 ("64", 4),
139 ("128", 5),
140 ("256", 6),
141 ("512", 7),
142 ("1024", 8),
143];
144
145const DISPLACEMENTS: [(&str, IntegerType); 3] = [("8", 1), ("15", 2), ("22", 3)];
147
148const BELOW: &str = "below";
150
151const STEPS_PER_OCTAVE: i64 = 7;
153const SEMITONES_PER_OCTAVE: i64 = 12;
154
155const STRAY_PER_OCTAVE: i64 = 5;
158
159const WORD_POSITIONS: [(&str, Syllabic); 3] = [
161 ("i", Syllabic::Begin),
162 ("m", Syllabic::Middle),
163 ("t", Syllabic::End),
164];
165
166const CONNECTORS: [(&str, &str); 4] = [("s", " "), ("d", "-"), ("t", "~"), ("u", "_")];
168
169const DEFAULT_CONNECTOR: &str = "-";
171
172pub(crate) fn mei_error(message: impl Into<String>) -> Error {
174 Error::mei(message.into())
175}
176
177pub fn unexpected(name: &str, value: &str) -> String {
180 format!("Unexpected value for \"{name}\" attribute: {value}")
181}
182
183pub fn translate<T: Copy>(table: &[(&str, T)], attribute: &str, name: &str) -> Result<T> {
193 table
194 .iter()
195 .find(|(key, _)| *key == attribute)
196 .map(|(_, value)| *value)
197 .ok_or_else(|| mei_error(unexpected(name, attribute)))
198}
199
200pub fn written_accidental(attribute: Option<&str>) -> Result<Option<&'static str>> {
203 attribute
204 .map(|attribute| translate(&WRITTEN_ACCIDENTALS, attribute, "accid"))
205 .transpose()
206}
207
208pub fn gestural_accidental(attribute: &str) -> Result<&'static str> {
210 translate(&GESTURAL_ACCIDENTALS, attribute, "accid.ges")
211}
212
213pub fn quarter_length(attribute: Option<&str>) -> Result<FloatType> {
216 match attribute {
217 None => Ok(NO_DURATION),
218 Some(attribute) => translate(&DURATIONS, attribute, "dur"),
219 }
220}
221
222pub fn articulation_classes(attribute: &str) -> Result<Vec<&'static str>> {
225 if let Some((_, pair)) = COMPOUND_ARTICULATIONS
226 .iter()
227 .find(|(name, _)| *name == attribute)
228 {
229 return Ok(pair.to_vec());
230 }
231 Ok(vec![translate(&ARTICULATIONS, attribute, "artic")?])
232}
233
234pub fn sharps_of(signature: &str) -> Result<IntegerType> {
245 if signature.starts_with('0') {
246 return Ok(0);
247 }
248 let count: IntegerType = signature
249 .get(..1)
250 .unwrap_or_default()
251 .parse()
252 .map_err(|_| mei_error(format!("the key signature {signature:?} has no number")))?;
253 if signature.ends_with('s') {
254 return Ok(count);
255 }
256 Ok(-count)
257}
258
259pub fn octave_shift(displaced: Option<&str>, place: Option<&str>) -> Result<IntegerType> {
262 let octaves = match displaced {
263 None => 0,
264 Some(displaced) => translate(&DISPLACEMENTS, displaced, "dis")?,
265 };
266 if place == Some(BELOW) {
267 return Ok(-octaves);
268 }
269 Ok(octaves)
270}
271
272pub fn transposition_steps(diatonic: i64, semitones: i64) -> Result<(IntegerType, IntegerType)> {
279 let mut diatonic = diatonic;
280 let octaves = semitones.abs() / SEMITONES_PER_OCTAVE;
281 if (semitones - diatonic).abs() > STRAY_PER_OCTAVE * (octaves + 1) {
282 diatonic += STEPS_PER_OCTAVE * octaves * semitones.signum();
283 }
284 diatonic += diatonic.signum();
285 let too_far = || mei_error(format!("a transposition of {diatonic} steps is too far"));
286 let generic = IntegerType::try_from(diatonic).map_err(|_| too_far())?;
287 let chromatic = IntegerType::try_from(semitones).map_err(|_| too_far())?;
288 Ok((generic, chromatic))
289}
290
291pub fn tie_type(attribute: &str) -> TieType {
293 let has = |mark: char| attribute.contains(mark);
294 if has('m') || (has('t') && has('i')) {
295 return TieType::Continue;
296 }
297 if has('i') {
298 return TieType::Start;
299 }
300 TieType::Stop
301}
302
303pub fn syllable(
307 text: &str,
308 word_position: Option<&str>,
309 connector: Option<&str>,
310) -> Result<(String, Option<Syllabic>)> {
311 let Some(word_position) = word_position else {
312 return Ok((text.to_owned(), None));
313 };
314 let joiner = match connector {
315 None => DEFAULT_CONNECTOR,
316 Some(connector) => translate(&CONNECTORS, connector, "con")?,
317 };
318 let syllabic = translate(&WORD_POSITIONS, word_position, "wordpos")?;
319 let joined = match syllabic {
320 Syllabic::Begin => format!("{text}{joiner}"),
321 Syllabic::Middle => format!("{joiner}{text}{joiner}"),
322 _ => format!("{joiner}{text}"),
323 };
324 Ok((joined, Some(syllabic)))
325}
326
327pub fn tremolo_marks(unit: &str) -> Option<IntegerType> {
330 translate(&TREMOLO_MARKS, unit, "unitdur").ok()
331}
332
333pub fn fresh_uuid(count: usize) -> String {
336 use std::hash::{BuildHasher, Hasher};
337
338 let random = std::collections::hash_map::RandomState::new();
341 let mut halves = [0_u64; 2];
342 for (half, made) in halves.iter_mut().enumerate() {
343 let mut hasher = random.build_hasher();
344 hasher.write_usize(count);
345 hasher.write_usize(half);
346 *made = hasher.finish();
347 }
348 let high = (halves[0] & !0xF000) | 0x4000;
349 let low = (halves[1] & 0x3FFF_FFFF_FFFF_FFFF) | 0x8000_0000_0000_0000;
350 format!(
351 "{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
352 high >> 32,
353 (high >> 16) & 0xFFFF,
354 high & 0xFFFF,
355 low >> 48,
356 low & 0xFFFF_FFFF_FFFF
357 )
358}
359
360pub fn without_hash(id: &str) -> &str {
369 id.strip_prefix('#').unwrap_or(id)
370}
371
372#[cfg(test)]
373mod tests {
374 use super::*;
375
376 #[test]
377 fn a_transposition_past_an_octave_has_its_octaves_put_back() {
378 assert_eq!(transposition_steps(-2, -3).unwrap(), (-3, -3));
379 assert_eq!(transposition_steps(4, 7).unwrap(), (5, 7));
380 assert_eq!(transposition_steps(11, 19).unwrap(), (12, 19));
381 assert_eq!(transposition_steps(0, 12).unwrap(), (8, 12));
382 assert_eq!(transposition_steps(-4, -19).unwrap(), (-12, -19));
383 assert_eq!(transposition_steps(1, 26).unwrap(), (16, 26));
384 }
385
386 #[test]
387 fn a_clef_moves_by_its_octaves() {
388 assert_eq!(octave_shift(Some("15"), Some("above")).unwrap(), 2);
389 assert_eq!(octave_shift(Some("22"), Some("below")).unwrap(), -3);
390 assert_eq!(octave_shift(Some("8"), None).unwrap(), 1);
391 assert_eq!(octave_shift(None, None).unwrap(), 0);
392 assert!(octave_shift(Some("9"), None).is_err());
393 }
394
395 #[test]
396 fn a_tie_names_its_part() {
397 assert_eq!(tie_type("i"), TieType::Start);
398 assert_eq!(tie_type("ti"), TieType::Continue);
399 assert_eq!(tie_type("m"), TieType::Continue);
400 assert_eq!(tie_type("t"), TieType::Stop);
401 }
402
403 #[test]
404 fn a_syllable_is_joined_by_its_place() {
405 let (text, place) = syllable("Chri", Some("i"), Some("s")).unwrap();
406 assert_eq!((text.as_str(), place), ("Chri ", Some(Syllabic::Begin)));
407 let (text, place) = syllable("sto", Some("m"), Some("t")).unwrap();
408 assert_eq!((text.as_str(), place), ("~sto~", Some(Syllabic::Middle)));
409 let (text, place) = syllable("pher", Some("t"), None).unwrap();
410 assert_eq!((text.as_str(), place), ("-pher", Some(Syllabic::End)));
411 assert_eq!(syllable("shoe", None, None).unwrap(), ("shoe".into(), None));
412 }
413
414 #[test]
415 fn an_unknown_value_names_its_attribute() {
416 let refused = translate(&DURATIONS, "9", "dur").unwrap_err();
417 assert!(refused.to_string().contains(&unexpected("dur", "9")));
418 assert_eq!(
419 articulation_classes("marc-stacc").unwrap(),
420 ["StrongAccent", "Staccato"]
421 );
422 assert_eq!(tremolo_marks("16"), Some(2));
423 assert_eq!(tremolo_marks("4"), None);
424 }
425}