pub struct ResolvedNote {
    pub note: NoteName,
    pub accidental: Accidental,
    pub octave: Octave,
    pub midi: u8,
}
Expand description

Represents note, that can be written in score.

It has:

  • precise note
  • enharmonically correct accidental
  • octave

Fields§

§note: NoteName§accidental: Accidental§octave: Octave§midi: u8

Implementations§

Examples found in repository?
src/lib.rs (lines 274-279)
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
    fn resolve_by_accident(
        &self,
        notes_map: &NotesMap,
        midi_note: u8,
        octave: Octave,
    ) -> Option<ResolvedNote> {
        if self.accidental.is_some() {
            let acc = self.accidental.as_ref().unwrap();
            let note = notes_map.get_by_midi(&midi_note).get(&acc);
            if note.is_some() {
                return Some(ResolvedNote::new(
                    note.unwrap().clone(),
                    acc.clone(),
                    octave,
                    octave.apply_to_midi_note(midi_note),
                ));
            }
        }
        None
    }
    pub fn midi(&self) -> u8 {
        self.midi
    }
    pub fn set_midi(&mut self, midi: u8) {
        self.midi = midi;
    }
    pub fn accidental(&self) -> Option<Accidental> {
        self.accidental.clone()
    }
    pub fn set_accidental(&mut self, accidental: Option<Accidental>) {
        self.accidental = accidental;
    }
}
impl From<u8> for Note {
    /// from midi, but without boilerplate.
    fn from(midi: u8) -> Self {
        Self::from_midi(midi, None)
    }
}
impl From<ResolvedNote> for Note {
    fn from(value: ResolvedNote) -> Self {
        Self {
            midi: value.midi,
            accidental: Some(value.accidental),
            octave: value.octave,
        }
    }
}

#[derive(Debug, PartialEq, PartialOrd, Hash, Eq, Clone, Copy, Serialize, Deserialize)]
pub enum Accidental {
    White,
    Sharp,
    DoubleSharp,
    Flat,
    DoubleFlat,
}
impl Accidental {
    pub fn to_string_by_note(&self, note: NoteName) -> String {
        match self {
            Self::DoubleFlat | Self::Flat => {
                if note.need_trunk() {
                    self.to_string().remove(0).to_string()
                } else {
                    self.to_string()
                }
            }
            _ => self.to_string(),
        }
    }
    /// "es" is Flat, "is" is Sharp, "white" is White.
    pub fn from_str(name: &str) -> Option<Self> {
        match name.to_lowercase().as_str() {
            "s" | "es" => Some(Self::Flat),
            "eses" => Some(Self::DoubleFlat),
            "is" => Some(Self::Sharp),
            "isis" => Some(Self::DoubleSharp),
            "white" => Some(Self::White),
            _ => None,
        }
    }
}
impl Default for Accidental {
    fn default() -> Self {
        Self::White
    }
}
impl ToString for Accidental {
    fn to_string(&self) -> String {
        match self {
            Accidental::White => "white".to_string(),
            Accidental::Sharp => "is".to_string(),
            Accidental::DoubleSharp => "isis".to_string(),
            Accidental::Flat => "es".to_string(),
            Accidental::DoubleFlat => "eses".to_string(),
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Serialize, Deserialize)]
pub struct Key {
    pub tonic: (NoteName, Accidental),
    pub scale: Scale,
}
impl Key {
    pub fn new(note: NoteName, accidental: Accidental, scale: Scale) -> Self {
        Self {
            tonic: (note, accidental),
            scale,
        }
    }
    /// `[root_midi, root_index]`
    ///
    /// `root_midi` is `u8` in rage 0..12, based on note name and accidental.
    /// `root_index` is `u8` in rage 0..7, based only on note name.
    pub fn get_root(&self) -> [u8; 2] {
        let (tonic_note, tonic_acc) = self.tonic.clone();
        let root_midi = NotesMap::get().get_by_note(tonic_note.clone(), tonic_acc);
        let root_idx = tonic_note.index();
        [root_midi, root_idx]
    }
    /// Returns concrete Scale representation (grades) for the key.
    fn resolve_scale(&self, notes_map: &NotesMap) -> ResolvedScale {
        self.scale.resolve_for_key(notes_map, self)
    }
    /// "as" or "eis" — without octave.
    pub fn from_str(name: &str, scale: Scale) -> Option<Self> {
        Some(Self {
            tonic: note_from_str(name)?,
            scale,
        })
    }
}
impl Default for Key {
    fn default() -> Self {
        Self::new(Default::default(), Default::default(), Default::default())
    }
}
impl From<(&String, Scale)> for Key {
    fn from(value: (&String, Scale)) -> Self {
        let (name, scale) = value;
        Self {
            tonic: note_from_str(name).unwrap(),
            scale,
        }
    }
}

fn note_from_str(name: &str) -> Option<(NoteName, Accidental)> {
    let note = &name[0..1];
    match NoteName::from_str(note) {
        Some(note) => {
            if name.len() <= 1 {
                return Some((note, Accidental::White));
            } else {
                match Accidental::from_str(&name[1..]) {
                    Some(acc) => Some((note, acc)),
                    None => None,
                }
            }
        }
        None => None,
    }
}

#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy, PartialOrd, Serialize, Deserialize)]
pub enum NoteName {
    C,
    D,
    E,
    F,
    G,
    A,
    B,
}
impl NoteName {
    fn need_trunk(&self) -> bool {
        match self {
            Self::A | Self::E => true,
            _ => false,
        }
    }
    fn index(self) -> u8 {
        match self {
            Self::C => 0,
            Self::D => 1,
            Self::E => 2,
            Self::F => 3,
            Self::G => 4,
            Self::A => 5,
            Self::B => 6,
        }
    }
    pub fn from_str(name: &str) -> Option<Self> {
        match name.to_uppercase().as_str() {
            "C" => Some(Self::C),
            "D" => Some(Self::D),
            "E" => Some(Self::E),
            "F" => Some(Self::F),
            "G" => Some(Self::G),
            "A" => Some(Self::A),
            "B" => Some(Self::B),
            _ => None,
        }
    }
    fn by_index(mut index: u8) -> Self {
        let names = [
            Self::C,
            Self::D,
            Self::E,
            Self::F,
            Self::G,
            Self::A,
            Self::B,
        ];
        if index > 6 {
            index -= 7;
        }
        names[index as usize].clone()
    }
}
impl Default for NoteName {
    fn default() -> Self {
        Self::C
    }
}
impl ToString for NoteName {
    fn to_string(&self) -> String {
        match self {
            Self::C => String::from("c"),
            Self::D => String::from("d"),
            Self::E => String::from("e"),
            Self::F => String::from("f"),
            Self::G => String::from("g"),
            Self::A => String::from("a"),
            Self::B => String::from("b"),
        }
    }
}

/// Concrete Scale representation, based on the given root note.
///
/// Used to estimate alteration for notes, can be alterated by scale rules.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResolvedScale {
    pub key: Key,
    /// 0..12 midi bytes, representing every grade of the scale.
    /// E.g. for C-Dur it would be: `[0, 2, 4, 5, 7, 9, 11]`,
    /// and for A-moll: `[9, 11, 0, 2, 4, 5, 7]`
    pub degree_midi: [u8; 7],
    /// the same, but, holding Tuples of note names and accidentals.
    pub degree_notes: [(NoteName, Accidental); 7],
    /// Collects accidentals, used for degrees to estimate, which
    /// alteration of non-degree notes is preferable.
    /// TODO: think on using this as weight.
    pub used_accidentals: Vec<Accidental>,
}
impl ResolvedScale {
    pub fn resolve_pitch(
        &self,
        notes_map: &NotesMap,
        midi_note: u8,
        octave: Octave,
    ) -> ResolvedNote {
        let note: (NoteName, Accidental);
        let key_root_midi = self.key.get_root()[0];
        match self.degree_midi.binary_search(&midi_note) {
            Ok(note_index) => {
                note = self.degree_notes[note_index];
                // println!("found note from scale {:?} at index {:?}", note, note_index);
            }
            Err(_err) => {
                if midi_note == key_root_midi + 1 && self.key.scale == Scale::Minor {
                    // println!("that is minor II♭");
                    note = notes_map
                        .resolve_note_for_midi(self.degree_notes[1 as usize], midi_note)
                        .unwrap();
                } else if midi_note == (key_root_midi + 8) % 12 && self.key.scale == Scale::Major {
                    // println!("that is major VI♭");
                    let candidate_note = self.degree_notes[5 as usize];
                    note = notes_map
                        .resolve_note_for_midi(candidate_note, midi_note)
                        .unwrap();
                } else {
                    // println!("just search for anything for midi: {:?}", midi_note);
                    note = notes_map
                        .resolve_enharmonic(self.used_accidentals.last().copied(), midi_note);
                }
            }
        }
        ResolvedNote::new(note.0, note.1, octave, octave.apply_to_midi_note(midi_note))
    }

“cisis3” resolved to C## 3 (62 raw MIDI note) with raw Octave{octave:5}.

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Deserialize this value from the given Serde deserializer. Read more
Converts to this type from the input type.
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
This method returns an ordering between self and other values if one exists. Read more
This method tests less than (for self and other) and is used by the < operator. Read more
This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
This method tests greater than (for self and other) and is used by the > operator. Read more
This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.