Skip to main content

music21/metadata/
bundles.rs

1//! The metadata of many scores, searched and cached together: music21's
2//! `metadata.bundles`.
3//!
4//! A [`MetadataBundle`] maps a key made from each score's corpus path to a
5//! [`MetadataEntry`]: where the score is and its [`RichMetadata`]. music21
6//! keeps the bundle of each corpus as a gzipped pickle; [`MetadataBundle::
7//! from_cache`] reads the pickle music21 writes and [`MetadataBundle::
8//! to_cache`] writes one music21 reads. Compressing is the caller's.
9//!
10//! ```
11//! use music21::metadata::Metadata;
12//! use music21::metadata::bundles::{MetadataBundle, MetadataEntry};
13//! use music21::metadata::rich::{RichMetadata, RichQuery};
14//!
15//! let mut metadata = Metadata::new();
16//! metadata.add_contributor("composer", "Arcangelo Corelli");
17//! let mut bundle = MetadataBundle::new(None);
18//! bundle.insert(MetadataEntry::new("corelli/opus3no1/1grave.xml", None, Some(RichMetadata::of(metadata))));
19//!
20//! let found = bundle.search(&RichQuery::Text("corelli"), Some("composer"), &[]);
21//! assert_eq!(found.keys(), ["corelli_opus3no1_1grave_xml"]);
22//!
23//! let read = MetadataBundle::from_cache(&bundle.to_cache())?;
24//! assert_eq!(read.len(), 1);
25//! # Ok::<(), music21::Error>(())
26//! ```
27
28use std::cmp::Ordering;
29use std::collections::{HashMap, HashSet};
30use std::path::{Component, Path};
31use std::sync::Arc;
32
33use super::primitives::{Contributor, Date, DateKind, DatePart, DatePrimitive, Relevance, Text};
34use super::rich::{AmbitusShort, RichMetadata, RichQuery};
35use super::{Metadata, MetadataContent, MetadataValue};
36use crate::common::numbertools::OffsetQL;
37use crate::common::pickle::{Construction, Pickle, PickleValue, ValueId};
38use crate::defaults::IntegerType;
39use crate::error::{Error, Result};
40
41/// The module music21 defines bundles in, which its cache names.
42const BUNDLES_MODULE: &str = "music21.metadata.bundles";
43/// The module music21 defines `RichMetadata` and `AmbitusShort` in.
44const METADATA_MODULE: &str = "music21.metadata";
45/// The module music21 defines its metadata primitives in.
46const PRIMITIVES_MODULE: &str = "music21.metadata.primitives";
47
48/// How a path was given to [`corpus_path_to_key`]: music21 reads a
49/// `pathlib.Path` by its parts and a string by its text.
50#[derive(Clone, Copy, Debug)]
51pub enum KeySource<'a> {
52    /// A path, and the corpus directory it is read relative to where it
53    /// lies inside it.
54    Path {
55        /// The path.
56        path: &'a Path,
57        /// music21's `common.getSourceFilePath() / 'corpus'`.
58        corpus: Option<&'a Path>,
59    },
60    /// A string.
61    Text(&'a str),
62}
63
64/// The key a score is filed under in a bundle: its corpus path with every
65/// separator and dot an underscore, and its number in an opus after it:
66/// music21's `MetadataBundle.corpusPathToKey`.
67///
68/// ```
69/// use music21::metadata::bundles::{KeySource, corpus_path_to_key};
70///
71/// let key = corpus_path_to_key(KeySource::Text("corelli/opus3no1/1grave.xml"), Some("3"));
72/// assert_eq!(key, "corelli_opus3no1_1grave_xml_3");
73/// ```
74pub fn corpus_path_to_key(source: KeySource<'_>, number: Option<&str>) -> String {
75    let path = match source {
76        KeySource::Path { path, corpus } => {
77            let relative = corpus
78                .and_then(|corpus| path.strip_prefix(corpus).ok())
79                .unwrap_or(path);
80            let mut parts: Vec<String> = relative
81                .components()
82                .map(|part| match part {
83                    Component::RootDir => "/".to_string(),
84                    other => other.as_os_str().to_string_lossy().into_owned(),
85                })
86                .collect();
87            if parts.len() > 1 && parts[0] == "/" {
88                parts.remove(0);
89            }
90            parts.join("_")
91        }
92        KeySource::Text(text) => {
93            let after = text.rsplit("corpus").next().unwrap_or(text);
94            let after = after
95                .strip_prefix(std::path::MAIN_SEPARATOR)
96                .unwrap_or(after);
97            after.replace(['/', std::path::MAIN_SEPARATOR], "_")
98        }
99    };
100    let key = path.replace('.', "_");
101    match number {
102        Some(number) => format!("{key}_{number}"),
103        None => key,
104    }
105}
106
107/// One score in a bundle: music21's `MetadataEntry`.
108#[derive(Clone, Debug, PartialEq)]
109pub struct MetadataEntry {
110    /// Where the score is, usually relative to the corpus directory.
111    pub source_path: String,
112    /// Which score of an opus it is, where it is one.
113    pub number: Option<String>,
114    /// Its metadata; nothing for the stand-in a whole opus is filed under.
115    pub metadata: Option<RichMetadata>,
116    /// The corpus it came from.
117    pub corpus_name: String,
118}
119
120impl MetadataEntry {
121    /// An entry of no named corpus.
122    pub fn new(
123        source_path: impl Into<String>,
124        number: Option<String>,
125        metadata: Option<RichMetadata>,
126    ) -> Self {
127        Self {
128            source_path: source_path.into(),
129            number,
130            metadata,
131            corpus_name: String::new(),
132        }
133    }
134
135    /// The key it is filed under: music21's `corpusPath`, which reads the
136    /// source path as a `pathlib.Path`.
137    pub fn corpus_path(&self, corpus: Option<&Path>) -> String {
138        let source = KeySource::Path {
139            path: Path::new(&self.source_path),
140            corpus,
141        };
142        corpus_path_to_key(source, self.number.as_deref())
143    }
144
145    /// Its source path's parts, which entries are sorted by, as
146    /// `pathlib.Path`s compare.
147    fn path_parts(&self) -> Vec<&str> {
148        self.source_path
149            .split('/')
150            .filter(|part| !part.is_empty())
151            .collect()
152    }
153
154    /// Its source path's suffix with the dot, `.xml`.
155    fn suffix(&self) -> &str {
156        let name = self.source_path.rsplit('/').next().unwrap_or("");
157        match name.rfind('.') {
158            Some(at) if at > 0 && at + 1 < name.len() => &name[at..],
159            _ => "",
160        }
161    }
162}
163
164/// Which set of keys a combination of two bundles keeps.
165#[derive(Clone, Copy, Debug, PartialEq, Eq)]
166pub enum SetOperation {
167    /// Keys in either.
168    Union,
169    /// Keys in both.
170    Intersection,
171    /// Keys in the first alone.
172    Difference,
173    /// Keys in one alone.
174    SymmetricDifference,
175}
176
177/// The metadata of many scores, filed by key in the order they were
178/// filed: music21's `MetadataBundle`.
179///
180/// Entries are shared, not copied, between a bundle and what is searched
181/// or combined out of it, so two bundles hold the same entries where
182/// music21's would hold the same objects.
183#[derive(Clone, Debug, Default)]
184pub struct MetadataBundle {
185    name: Option<String>,
186    entries: Vec<(String, Arc<MetadataEntry>)>,
187    index: HashMap<String, usize>,
188}
189
190impl PartialEq for MetadataBundle {
191    /// The same entries under the same keys in the same order, as music21
192    /// compares two bundles' `OrderedDict`s of the same objects.
193    fn eq(&self, other: &Self) -> bool {
194        self.entries.len() == other.entries.len()
195            && self
196                .entries
197                .iter()
198                .zip(&other.entries)
199                .all(|(left, right)| left.0 == right.0 && Arc::ptr_eq(&left.1, &right.1))
200    }
201}
202
203impl MetadataBundle {
204    /// An empty bundle, of the corpus `name` or of none.
205    pub fn new(name: Option<String>) -> Self {
206        Self {
207            name,
208            ..Self::default()
209        }
210    }
211
212    /// The corpus it belongs to: `core`, `local` or a local corpus's name.
213    pub fn name(&self) -> Option<&str> {
214        self.name.as_deref()
215    }
216
217    /// How many entries it has.
218    pub fn len(&self) -> usize {
219        self.entries.len()
220    }
221
222    /// Whether it has none.
223    pub fn is_empty(&self) -> bool {
224        self.entries.is_empty()
225    }
226
227    /// Its keys, in order.
228    pub fn keys(&self) -> Vec<&str> {
229        self.entries.iter().map(|(key, _)| key.as_str()).collect()
230    }
231
232    /// The entry at a place, with its key.
233    pub fn get(&self, at: usize) -> Option<(&str, &Arc<MetadataEntry>)> {
234        self.entries
235            .get(at)
236            .map(|(key, entry)| (key.as_str(), entry))
237    }
238
239    /// The entry filed under a key.
240    pub fn entry(&self, key: &str) -> Option<&Arc<MetadataEntry>> {
241        self.index.get(key).map(|at| &self.entries[*at].1)
242    }
243
244    /// Every entry with its key, in order.
245    pub fn iter(&self) -> impl Iterator<Item = (&str, &Arc<MetadataEntry>)> {
246        self.entries
247            .iter()
248            .map(|(key, entry)| (key.as_str(), entry))
249    }
250
251    /// Files an entry under its corpus path, in place of one already there.
252    pub fn insert(&mut self, entry: MetadataEntry) {
253        let key = entry.corpus_path(None);
254        self.insert_shared(key, Arc::new(entry));
255    }
256
257    /// Files a shared entry under a key, in place of one already there.
258    pub fn insert_shared(&mut self, key: String, entry: Arc<MetadataEntry>) {
259        if let Some(at) = self.index.get(&key) {
260            self.entries[*at].1 = entry;
261            return;
262        }
263        self.index.insert(key.clone(), self.entries.len());
264        self.entries.push((key, entry));
265    }
266
267    /// Removes every entry: music21's `clear`.
268    pub fn clear(&mut self) {
269        self.entries.clear();
270        self.index.clear();
271    }
272
273    /// Keeps the entries whose score `exists` finds, answering how many
274    /// went: music21's `validate`, which leaves finding files to its
275    /// caller here.
276    pub fn validate(&mut self, exists: impl Fn(&str) -> bool) -> usize {
277        let before = self.entries.len();
278        let mut known: HashMap<String, bool> = HashMap::new();
279        self.entries.retain(|(_, entry)| {
280            *known.entry(entry.source_path.clone()).or_insert_with(|| {
281                entry.source_path.starts_with("http:") || exists(&entry.source_path)
282            })
283        });
284        self.reindex();
285        before - self.entries.len()
286    }
287
288    fn reindex(&mut self) {
289        self.index = self
290            .entries
291            .iter()
292            .enumerate()
293            .map(|(at, (key, _))| (key.clone(), at))
294            .collect();
295    }
296
297    /// Sorts the entries by source path, keeping the order of those that
298    /// share one.
299    fn sort_by_path(&mut self) {
300        self.entries
301            .sort_by(|left, right| left.1.path_parts().cmp(&right.1.path_parts()));
302        self.reindex();
303    }
304
305    /// The entries whose metadata a query matches, sorted by source path,
306    /// in a bundle of no corpus: music21's `search`. `extensions`, where
307    /// given, are the suffixes kept, dots and all.
308    pub fn search(
309        &self,
310        query: &RichQuery<'_>,
311        field: Option<&str>,
312        extensions: &[String],
313    ) -> MetadataBundle {
314        let mut found = MetadataBundle::new(None);
315        for (key, entry) in &self.entries {
316            let Some(metadata) = &entry.metadata else {
317                continue;
318            };
319            if !extensions.is_empty() && !extensions.iter().any(|kept| kept == entry.suffix()) {
320                continue;
321            }
322            if found.index.contains_key(key) {
323                continue;
324            }
325            if metadata.search(query, field).is_some() {
326                found.insert_shared(key.clone(), Arc::clone(entry));
327            }
328        }
329        found.sort_by_path();
330        found
331    }
332
333    /// The entries of the keys an operation keeps, from this bundle where
334    /// it has them, sorted by source path, in a bundle of no corpus.
335    pub fn combine(&self, other: &MetadataBundle, operation: SetOperation) -> MetadataBundle {
336        let mine: HashSet<&str> = self.index.keys().map(String::as_str).collect();
337        let theirs: HashSet<&str> = other.index.keys().map(String::as_str).collect();
338        let keeps = |key: &str| match operation {
339            SetOperation::Union => true,
340            SetOperation::Intersection => mine.contains(key) && theirs.contains(key),
341            SetOperation::Difference => !theirs.contains(key),
342            SetOperation::SymmetricDifference => mine.contains(key) != theirs.contains(key),
343        };
344        let mut result = MetadataBundle::new(None);
345        for (key, entry) in self.entries.iter().chain(&other.entries) {
346            if keeps(key) && !result.index.contains_key(key) {
347                result.insert_shared(key.clone(), Arc::clone(entry));
348            }
349        }
350        result.sort_by_path();
351        result
352    }
353
354    /// How this bundle's keys stand to another's: `Less` for a proper
355    /// subset, `Equal` for the same keys, `Greater` for a proper superset,
356    /// and nothing where neither holds the other.
357    pub fn compare_keys(&self, other: &MetadataBundle) -> Option<Ordering> {
358        let subset = self.index.keys().all(|key| other.index.contains_key(key));
359        let superset = other.index.keys().all(|key| self.index.contains_key(key));
360        match (subset, superset) {
361            (true, true) => Some(Ordering::Equal),
362            (true, false) => Some(Ordering::Less),
363            (false, true) => Some(Ordering::Greater),
364            (false, false) => None,
365        }
366    }
367
368    /// Whether no key is in both.
369    pub fn is_disjoint(&self, other: &MetadataBundle) -> bool {
370        !self.index.keys().any(|key| other.index.contains_key(key))
371    }
372
373    /// Reads a bundle from the pickle music21 caches one as.
374    ///
375    /// # Errors
376    ///
377    /// Bytes that are no pickle, or a pickle of anything but a bundle.
378    pub fn from_cache(bytes: &[u8]) -> Result<Self> {
379        let pickle = Pickle::read(bytes)?;
380        CacheReader { pickle: &pickle }.bundle()
381    }
382
383    /// The pickle music21 caches a bundle as, protocol 5: music21 reads it
384    /// with `pickle.load`.
385    pub fn to_cache(&self) -> Vec<u8> {
386        let mut writer = CacheWriter::default();
387        let root = writer.bundle(self);
388        writer.pickle.set_root(root);
389        writer.pickle.write()
390    }
391}
392
393fn cache_error(message: impl Into<String>) -> Error {
394    Error::Metadata(format!("metadata cache: {}", message.into()))
395}
396
397/// Reads music21's pickled objects into the crate's.
398struct CacheReader<'a> {
399    pickle: &'a Pickle,
400}
401
402impl CacheReader<'_> {
403    fn text(&self, id: Option<ValueId>) -> Option<String> {
404        id.and_then(|id| self.pickle.as_text(id))
405            .map(str::to_string)
406    }
407
408    fn integer(&self, id: Option<ValueId>) -> Option<IntegerType> {
409        match id.map(|id| self.pickle.get(id)) {
410            Some(PickleValue::Int(value)) => Some(*value as IntegerType),
411            _ => None,
412        }
413    }
414
415    fn bundle(&self) -> Result<MetadataBundle> {
416        let root = self.pickle.root();
417        if self.pickle.class_of(root) != Some((BUNDLES_MODULE, "MetadataBundle")) {
418            return Err(cache_error("not a pickled MetadataBundle"));
419        }
420        let name = self.text(self.pickle.dict_get(root, "_name"));
421        let mut bundle = MetadataBundle::new(name);
422        let Some(entries) = self.pickle.dict_get(root, "_metadataEntries") else {
423            return Ok(bundle);
424        };
425        for (key, entry) in self.pickle.dict_items(entries) {
426            let Some(key) = self.pickle.as_text(*key) else {
427                continue;
428            };
429            bundle.insert_shared(key.to_string(), Arc::new(self.entry(*entry)?));
430        }
431        Ok(bundle)
432    }
433
434    fn entry(&self, id: ValueId) -> Result<MetadataEntry> {
435        let field = |name| self.pickle.dict_get(id, name);
436        let source_path = self.text(field("_sourcePath")).unwrap_or_default();
437        let number = match field("_number").map(|number| self.pickle.get(number)) {
438            Some(PickleValue::Text(text)) => Some(text.clone()),
439            Some(PickleValue::Int(value)) => Some(value.to_string()),
440            _ => None,
441        };
442        let metadata = match field("_metadataPayload") {
443            Some(payload) if self.pickle.class_of(payload).is_some() => Some(self.rich(payload)?),
444            _ => None,
445        };
446        Ok(MetadataEntry {
447            source_path,
448            number,
449            metadata,
450            corpus_name: self.text(field("_corpusName")).unwrap_or_default(),
451        })
452    }
453
454    fn rich(&self, id: ValueId) -> Result<RichMetadata> {
455        let field = |name| self.pickle.dict_get(id, name);
456        let mut metadata = Metadata::new();
457        if let Some(contents) = field("_contents") {
458            for (name, values) in self.pickle.dict_items(contents) {
459                let Some(name) = self.pickle.as_text(*name) else {
460                    continue;
461                };
462                for value in self.pickle.members(*values) {
463                    if let Some(value) = self.value(*value)? {
464                        metadata.add(name, value);
465                    }
466                }
467            }
468        }
469        let texts = |name| {
470            field(name).map_or_else(Vec::new, |list| {
471                self.pickle
472                    .members(list)
473                    .iter()
474                    .filter_map(|id| self.pickle.as_text(*id).map(str::to_string))
475                    .collect()
476            })
477        };
478        let key_signatures = field("keySignatures").map_or_else(Vec::new, |list| {
479            self.pickle
480                .members(list)
481                .iter()
482                .filter_map(|id| self.integer(Some(*id)))
483                .collect()
484        });
485        Ok(RichMetadata {
486            metadata,
487            ambitus: field("ambitus").and_then(|ambitus| self.ambitus(ambitus)),
488            key_signature_first: self.integer(field("keySignatureFirst")),
489            key_signatures,
490            note_count: self.integer(field("noteCount")),
491            number_of_parts: self.integer(field("numberOfParts")),
492            pitch_highest: self.text(field("pitchHighest")),
493            pitch_lowest: self.text(field("pitchLowest")),
494            score_quarter_length: field("scoreQuarterLength")
495                .map_or(OffsetQL::Float(0.0), |length| self.length(length)),
496            source_path: self.text(field("sourcePath")).unwrap_or_default(),
497            tempo_first: self.text(field("tempoFirst")),
498            tempos: texts("tempos"),
499            time_signature_first: self.text(field("timeSignatureFirst")),
500            time_signatures: texts("timeSignatures"),
501        })
502    }
503
504    fn ambitus(&self, id: ValueId) -> Option<AmbitusShort> {
505        let args = self.pickle.args_of(id);
506        if args.len() < 4 {
507            return None;
508        }
509        Some(AmbitusShort {
510            semitones: self.integer(Some(args[0]))?,
511            diatonic: self.text(Some(args[1]))?,
512            pitch_lowest: self.text(Some(args[2])),
513            pitch_highest: self.text(Some(args[3])),
514        })
515    }
516
517    fn length(&self, id: ValueId) -> OffsetQL {
518        match self.pickle.get(id) {
519            PickleValue::Float(value) => OffsetQL::Float(*value),
520            PickleValue::Int(value) => OffsetQL::Float(*value as f64),
521            PickleValue::Object { .. } => {
522                // `Fraction` pickles as `Fraction('5077/12')`.
523                let written = self
524                    .text(self.pickle.args_of(id).first().copied())
525                    .unwrap_or_default();
526                let (numerator, denominator) = written.split_once('/').unwrap_or((&written, "1"));
527                OffsetQL::Fraction {
528                    numerator: numerator.parse().unwrap_or(0),
529                    denominator: denominator.parse().unwrap_or(1),
530                }
531            }
532            _ => OffsetQL::Float(0.0),
533        }
534    }
535
536    /// One of music21's primitives as a value: a `Text`, `Copyright`,
537    /// `Contributor` or one of the four dates. Anything else is left out.
538    fn value(&self, id: ValueId) -> Result<Option<MetadataValue>> {
539        let Some((_, class)) = self.pickle.class_of(id) else {
540            return Ok(self.pickle.as_text(id).map(MetadataValue::new));
541        };
542        let value = match class {
543            "Text" | "Copyright" => MetadataValue::of_text(self.text_primitive(id)),
544            "Contributor" => {
545                let mut contributor = Contributor::unnamed();
546                contributor.set_role(self.text(self.pickle.dict_get(id, "_role")));
547                let names = self
548                    .pickle
549                    .dict_get(id, "_names")
550                    .map_or_else(Vec::new, |names| {
551                        self.pickle
552                            .members(names)
553                            .iter()
554                            .map(|name| self.text_primitive(*name))
555                            .collect()
556                    });
557                contributor.set_names(names);
558                contributor.set_birth(self.date_field(id, "birth")?);
559                contributor.set_death(self.date_field(id, "death")?);
560                MetadataValue::of_contributor(contributor)
561            }
562            "DateSingle" | "DateRelative" | "DateBetween" | "DateSelection" => {
563                MetadataValue::of_date(self.date(id)?)
564            }
565            _ => return Ok(None),
566        };
567        Ok(Some(value))
568    }
569
570    fn text_primitive(&self, id: ValueId) -> Text {
571        let field = |name| self.pickle.dict_get(id, name);
572        let mut text = Text::new(self.text(field("_data")).unwrap_or_default());
573        text.set_language(self.text(field("_language")));
574        text.set_encoding_scheme(self.text(field("encodingScheme")));
575        if let Some(PickleValue::Bool(translated)) =
576            field("isTranslated").map(|id| self.pickle.get(id))
577        {
578            text.set_translated(Some(*translated));
579        }
580        if self.pickle.class_of(id).map(|(_, class)| class) == Some("Copyright") {
581            text.set_role(self.text(field("role")));
582        }
583        text
584    }
585
586    fn date_field(&self, id: ValueId, name: &str) -> Result<Option<DatePrimitive>> {
587        match self.pickle.dict_get(id, name) {
588            Some(date) if self.pickle.class_of(date).is_some() => Ok(Some(self.date(date)?)),
589            _ => Ok(None),
590        }
591    }
592
593    fn date(&self, id: ValueId) -> Result<DatePrimitive> {
594        let kind = match self.pickle.class_of(id).map(|(_, class)| class) {
595            Some("DateRelative") => DateKind::Relative,
596            Some("DateBetween") => DateKind::Between,
597            Some("DateSelection") => DateKind::Selection,
598            _ => DateKind::Single,
599        };
600        let relevance = self
601            .text(self.pickle.dict_get(id, "_relevance"))
602            .and_then(|name| Relevance::named(&name))
603            .unwrap_or_else(|| kind.default_relevance());
604        let dates = self
605            .pickle
606            .dict_get(id, "_data")
607            .map_or_else(Vec::new, |dates| {
608                self.pickle
609                    .members(dates)
610                    .iter()
611                    .map(|date| self.one_date(*date))
612                    .collect()
613            });
614        DatePrimitive::of_dates(dates, relevance, kind)
615    }
616
617    fn one_date(&self, id: ValueId) -> Date {
618        let mut date = Date::new();
619        for part in DatePart::ALL {
620            let value = self.integer(self.pickle.dict_get(id, part.name()));
621            let error = self
622                .text(self.pickle.dict_get(id, &format!("{}Error", part.name())))
623                .and_then(|name| super::primitives::Certainty::named(&name));
624            date.set_unchecked(part, value, error);
625        }
626        date
627    }
628}
629
630/// Writes the crate's objects as music21 pickles its own.
631#[derive(Default)]
632struct CacheWriter {
633    pickle: Pickle,
634    none: Option<ValueId>,
635}
636
637impl CacheWriter {
638    fn none(&mut self) -> ValueId {
639        if let Some(none) = self.none {
640            return none;
641        }
642        let none = self.pickle.push(PickleValue::None);
643        self.none = Some(none);
644        none
645    }
646
647    fn optional_text(&mut self, text: Option<&str>) -> ValueId {
648        match text {
649            Some(text) => self.pickle.text(text),
650            None => self.none(),
651        }
652    }
653
654    fn optional_integer(&mut self, value: Option<IntegerType>) -> ValueId {
655        match value {
656            Some(value) => self.pickle.push(PickleValue::Int(value as i64)),
657            None => self.none(),
658        }
659    }
660
661    /// An object of a class of music21's, made with `NEWOBJ` and given a
662    /// `__dict__`.
663    fn object(&mut self, module: &str, class: &str, state: Vec<(&str, ValueId)>) -> ValueId {
664        let class = self.pickle.global(module, class);
665        let items = state
666            .into_iter()
667            .map(|(name, value)| (self.pickle.text(name), value))
668            .collect();
669        let state = self.pickle.push(PickleValue::Dict(items));
670        self.pickle.push(PickleValue::Object {
671            class,
672            construction: Construction::New,
673            args: Vec::new(),
674            state: Some(state),
675            items: Vec::new(),
676            entries: Vec::new(),
677        })
678    }
679
680    fn list(&mut self, members: Vec<ValueId>) -> ValueId {
681        self.pickle.push(PickleValue::List(members))
682    }
683
684    fn bundle(&mut self, bundle: &MetadataBundle) -> ValueId {
685        let ordered = self.pickle.global("collections", "OrderedDict");
686        let mut entries = Vec::with_capacity(bundle.len());
687        for (key, entry) in bundle.iter() {
688            let key = self.pickle.text(key);
689            entries.push((key, self.entry(entry)));
690        }
691        let ordered = self.pickle.push(PickleValue::Object {
692            class: ordered,
693            construction: Construction::Call,
694            args: Vec::new(),
695            state: None,
696            items: Vec::new(),
697            entries,
698        });
699        let corpus = self.none();
700        let name = self.optional_text(bundle.name());
701        self.object(
702            BUNDLES_MODULE,
703            "MetadataBundle",
704            vec![
705                ("_metadataEntries", ordered),
706                ("_corpus", corpus),
707                ("_name", name),
708            ],
709        )
710    }
711
712    fn entry(&mut self, entry: &MetadataEntry) -> ValueId {
713        let source_path = self.pickle.text(&entry.source_path);
714        let number = self.optional_text(entry.number.as_deref());
715        let payload = match &entry.metadata {
716            Some(rich) => self.rich(rich),
717            None => self.none(),
718        };
719        let corpus_name = self.pickle.text(&entry.corpus_name);
720        self.object(
721            BUNDLES_MODULE,
722            "MetadataEntry",
723            vec![
724                ("_sourcePath", source_path),
725                ("_number", number),
726                ("_metadataPayload", payload),
727                ("_corpusName", corpus_name),
728            ],
729        )
730    }
731
732    /// `RichMetadata`, with the `Music21Object` attributes music21 pickles
733    /// for an element in no stream.
734    fn rich(&mut self, rich: &RichMetadata) -> ValueId {
735        let mut state = self.element_state();
736        let contents = self.contents(&rich.metadata);
737        state.push(("_contents", contents));
738
739        let ambitus = match &rich.ambitus {
740            Some(ambitus) => self.ambitus(ambitus),
741            None => self.none(),
742        };
743        state.push(("ambitus", ambitus));
744        let key_first = self.optional_integer(rich.key_signature_first);
745        state.push(("keySignatureFirst", key_first));
746        let keys = rich
747            .key_signatures
748            .iter()
749            .map(|sharps| self.pickle.push(PickleValue::Int(*sharps as i64)))
750            .collect();
751        let keys = self.list(keys);
752        state.push(("keySignatures", keys));
753        let notes = self.optional_integer(rich.note_count);
754        state.push(("noteCount", notes));
755        let parts = self.optional_integer(rich.number_of_parts);
756        state.push(("numberOfParts", parts));
757        let highest = self.optional_text(rich.pitch_highest.as_deref());
758        state.push(("pitchHighest", highest));
759        let lowest = self.optional_text(rich.pitch_lowest.as_deref());
760        state.push(("pitchLowest", lowest));
761        let length = self.length(rich.score_quarter_length);
762        state.push(("scoreQuarterLength", length));
763        let source = self.pickle.text(&rich.source_path);
764        state.push(("sourcePath", source));
765        let tempo_first = self.optional_text(rich.tempo_first.as_deref());
766        state.push(("tempoFirst", tempo_first));
767        let tempos = self.texts(&rich.tempos);
768        state.push(("tempos", tempos));
769        let meter_first = self.optional_text(rich.time_signature_first.as_deref());
770        state.push(("timeSignatureFirst", meter_first));
771        let meters = self.texts(&rich.time_signatures);
772        state.push(("timeSignatures", meters));
773        self.object(METADATA_MODULE, "RichMetadata", state)
774    }
775
776    fn texts(&mut self, texts: &[String]) -> ValueId {
777        let members = texts.iter().map(|text| self.pickle.text(text)).collect();
778        self.list(members)
779    }
780
781    /// What `Music21Object.__getstate__` gives for an element in no
782    /// stream, as music21's cache holds it.
783    fn element_state(&mut self) -> Vec<(&'static str, ValueId)> {
784        let none = self.none();
785        let offset = self.pickle.push(PickleValue::Float(0.0));
786        let priority = self.pickle.push(PickleValue::Int(0));
787        let cache = self.pickle.push(PickleValue::Dict(Vec::new()));
788        let groups_class = self.pickle.global("music21.base", "Groups");
789        let groups = self.pickle.push(PickleValue::Object {
790            class: groups_class,
791            construction: Construction::New,
792            args: Vec::new(),
793            state: None,
794            items: Vec::new(),
795            entries: Vec::new(),
796        });
797        let sites = self.sites();
798        vec![
799            ("_id", none),
800            ("_activeSite", none),
801            ("_naiveOffset", offset),
802            ("_activeSiteStoredOffset", none),
803            ("_derivation", none),
804            ("_style", none),
805            ("_editorial", none),
806            ("_duration", none),
807            ("_priority", priority),
808            ("_cache", cache),
809            ("groups", groups),
810            ("sites", sites),
811        ]
812    }
813
814    /// `Sites` holding only the dead reference to no site that every
815    /// element starts with.
816    fn sites(&mut self) -> ValueId {
817        let none = self.none();
818        let minus_two = self.pickle.push(PickleValue::Int(-2));
819        let dead = self.pickle.push(PickleValue::Bool(true));
820        let site_ref = self.object(
821            "music21.sites",
822            "SiteRef",
823            vec![
824                ("siteWeakref", none),
825                ("siteIndex", minus_two),
826                ("globalSiteIndex", minus_two),
827                ("classString", none),
828                ("isDead", dead),
829            ],
830        );
831        let ordered = self.pickle.global("collections", "OrderedDict");
832        let site_dict = self.pickle.push(PickleValue::Object {
833            class: ordered,
834            construction: Construction::Call,
835            args: Vec::new(),
836            state: None,
837            items: Vec::new(),
838            entries: vec![(none, site_ref)],
839        });
840        let index = self.pickle.push(PickleValue::Int(0));
841        let last = self.pickle.push(PickleValue::Int(-1));
842        self.object(
843            "music21.sites",
844            "Sites",
845            vec![
846                ("_siteIndex", index),
847                ("siteDict", site_dict),
848                ("_lastID", last),
849            ],
850        )
851    }
852
853    fn contents(&mut self, metadata: &Metadata) -> ValueId {
854        let mut names: Vec<(&str, Vec<ValueId>)> = Vec::new();
855        for (name, value) in metadata.all() {
856            let written = self.value(value);
857            match names.iter_mut().find(|(found, _)| *found == name) {
858                Some((_, values)) => values.push(written),
859                None => names.push((name, vec![written])),
860            }
861        }
862        let items = names
863            .into_iter()
864            .map(|(name, values)| (self.pickle.text(name), self.list(values)))
865            .collect();
866        self.pickle.push(PickleValue::Dict(items))
867    }
868
869    fn value(&mut self, value: &MetadataValue) -> ValueId {
870        match value.content() {
871            MetadataContent::Text(text) => self.text_primitive(text),
872            MetadataContent::Contributor(contributor) => self.contributor(contributor),
873            MetadataContent::Date(date) => self.date(date),
874        }
875    }
876
877    fn text_primitive(&mut self, text: &Text) -> ValueId {
878        let data = self.pickle.text(text.data());
879        let language = self.optional_text(text.language());
880        let translated = match text.is_translated() {
881            Some(translated) => self.pickle.push(PickleValue::Bool(translated)),
882            None => self.none(),
883        };
884        let scheme = self.optional_text(text.encoding_scheme());
885        let mut state = vec![
886            ("_data", data),
887            ("_language", language),
888            ("isTranslated", translated),
889            ("encodingScheme", scheme),
890        ];
891        let class = match text.role() {
892            Some(role) => {
893                let role = self.pickle.text(role);
894                state.push(("role", role));
895                "Copyright"
896            }
897            None => "Text",
898        };
899        self.object(PRIMITIVES_MODULE, class, state)
900    }
901
902    fn contributor(&mut self, contributor: &Contributor) -> ValueId {
903        let role = self.optional_text(contributor.role());
904        let names = contributor
905            .names()
906            .iter()
907            .map(|name| self.text_primitive(name))
908            .collect();
909        let names = self.list(names);
910        let nationality = self.list(Vec::new());
911        let birth = match contributor.birth() {
912            Some(date) => self.date(date),
913            None => self.none(),
914        };
915        let death = match contributor.death() {
916            Some(date) => self.date(date),
917            None => self.none(),
918        };
919        self.object(
920            PRIMITIVES_MODULE,
921            "Contributor",
922            vec![
923                ("_role", role),
924                ("_names", names),
925                ("_nationality", nationality),
926                ("birth", birth),
927                ("death", death),
928            ],
929        )
930    }
931
932    fn date(&mut self, date: &DatePrimitive) -> ValueId {
933        let dates: Vec<ValueId> = date.dates().iter().map(|one| self.one_date(one)).collect();
934        let count = dates.len();
935        let dates = self.list(dates);
936        let relevance = self.pickle.text(date.relevance().name());
937
938        // A single date's certainty is its relevance; the others have none.
939        let uncertainty = match date.kind() {
940            DateKind::Single => vec![self.pickle.text(date.relevance().name())],
941            _ => vec![self.none(); count],
942        };
943        let uncertainty = self.list(uncertainty);
944        self.object(
945            PRIMITIVES_MODULE,
946            date.kind().name(),
947            vec![
948                ("_data", dates),
949                ("_relevance", relevance),
950                ("_dataUncertainty", uncertainty),
951            ],
952        )
953    }
954
955    fn one_date(&mut self, date: &Date) -> ValueId {
956        let mut state = Vec::new();
957        for part in DatePart::ALL {
958            let value = self.optional_integer(date.value(part));
959            state.push((part.name().to_string(), value));
960        }
961        for part in DatePart::ALL {
962            let error = self.optional_text(date.certainty(part).map(|certainty| certainty.name()));
963            state.push((format!("{}Error", part.name()), error));
964        }
965        let names = DatePart::ALL
966            .iter()
967            .map(|part| self.pickle.text(part.name()))
968            .collect();
969        let names = self.pickle.push(PickleValue::Tuple(names));
970        state.push(("attrNames".to_string(), names));
971        let class = self.pickle.global(PRIMITIVES_MODULE, "Date");
972        let items = state
973            .into_iter()
974            .map(|(name, value)| (self.pickle.text(&name), value))
975            .collect();
976        let state = self.pickle.push(PickleValue::Dict(items));
977        self.pickle.push(PickleValue::Object {
978            class,
979            construction: Construction::New,
980            args: Vec::new(),
981            state: Some(state),
982            items: Vec::new(),
983            entries: Vec::new(),
984        })
985    }
986
987    fn ambitus(&mut self, ambitus: &AmbitusShort) -> ValueId {
988        let class = self.pickle.global(METADATA_MODULE, "AmbitusShort");
989        let semitones = self.pickle.push(PickleValue::Int(ambitus.semitones as i64));
990        let diatonic = self.pickle.text(&ambitus.diatonic);
991        let lowest = self.optional_text(ambitus.pitch_lowest.as_deref());
992        let highest = self.optional_text(ambitus.pitch_highest.as_deref());
993        self.pickle.push(PickleValue::Object {
994            class,
995            construction: Construction::New,
996            args: vec![semitones, diatonic, lowest, highest],
997            state: None,
998            items: Vec::new(),
999            entries: Vec::new(),
1000        })
1001    }
1002
1003    fn length(&mut self, length: OffsetQL) -> ValueId {
1004        match length {
1005            OffsetQL::Float(value) => self.pickle.push(PickleValue::Float(value)),
1006            OffsetQL::Fraction {
1007                numerator,
1008                denominator,
1009            } => {
1010                let class = self.pickle.global("fractions", "Fraction");
1011                let written = self.pickle.text(&format!("{numerator}/{denominator}"));
1012                self.pickle.push(PickleValue::Object {
1013                    class,
1014                    construction: Construction::Call,
1015                    args: vec![written],
1016                    state: None,
1017                    items: Vec::new(),
1018                    entries: Vec::new(),
1019                })
1020            }
1021        }
1022    }
1023}
1024
1025#[cfg(test)]
1026mod tests {
1027    use super::*;
1028
1029    fn entry(path: &str, composer: &str, meter: &str) -> MetadataEntry {
1030        let mut metadata = Metadata::new();
1031        metadata.add_contributor("composer", composer);
1032        let mut rich = RichMetadata::of(metadata);
1033        rich.time_signature_first = Some(meter.to_string());
1034        rich.time_signatures = vec![meter.to_string()];
1035        rich.score_quarter_length = OffsetQL::Fraction {
1036            numerator: 5077,
1037            denominator: 12,
1038        };
1039        MetadataEntry::new(path, None, Some(rich))
1040    }
1041
1042    fn bundle() -> MetadataBundle {
1043        let mut bundle = MetadataBundle::new(Some("core".to_string()));
1044        bundle.insert(entry("bach/bwv7.7.mxl", "J.S. Bach", "4/4"));
1045        bundle.insert(entry("bach/bwv11.6.mxl", "J.S. Bach", "3/4"));
1046        bundle.insert(entry(
1047            "corelli/opus3no1/1grave.xml",
1048            "Arcangelo Corelli",
1049            "4/4",
1050        ));
1051        bundle.insert(MetadataEntry::new("airdsAirs/book1.abc", None, None));
1052        bundle
1053    }
1054
1055    #[test]
1056    fn keys_read_strings_and_paths_as_music21_does() {
1057        // music21 strips only the platform's own separator after "corpus".
1058        let sep = std::path::MAIN_SEPARATOR;
1059        let written = format!("{sep}music21{sep}corpus{sep}bach{sep}bwv1007{sep}prelude");
1060        let text = KeySource::Text(&written);
1061        assert_eq!(corpus_path_to_key(text, None), "bach_bwv1007_prelude");
1062        let path = KeySource::Path {
1063            path: Path::new("/m21/corpus/bach/bwv66.6.mxl"),
1064            corpus: Some(Path::new("/m21/corpus")),
1065        };
1066        assert_eq!(corpus_path_to_key(path, Some("2")), "bach_bwv66_6_mxl_2");
1067        let outside = KeySource::Path {
1068            path: Path::new("/tmp/myFile.xml"),
1069            corpus: None,
1070        };
1071        assert_eq!(corpus_path_to_key(outside, None), "tmp_myFile_xml");
1072    }
1073
1074    #[test]
1075    fn a_search_skips_stubs_and_sorts_by_path() {
1076        let bach = bundle().search(&RichQuery::Text("bach"), Some("composer"), &[]);
1077        assert_eq!(bach.keys(), ["bach_bwv11_6_mxl", "bach_bwv7_7_mxl"]);
1078        assert_eq!(bach.name(), None);
1079        let xml = [".xml".to_string()];
1080        assert_eq!(
1081            bundle().search(&RichQuery::Text("4/4"), None, &xml).len(),
1082            1
1083        );
1084    }
1085
1086    #[test]
1087    fn set_operations_work_on_keys() {
1088        let core = bundle();
1089        let bach = core.search(&RichQuery::Text("bach"), Some("composer"), &[]);
1090        let triple = core.search(&RichQuery::Text("3/4"), None, &[]);
1091        assert_eq!(bach.combine(&triple, SetOperation::Intersection).len(), 1);
1092        assert_eq!(bach.combine(&triple, SetOperation::Difference).len(), 1);
1093        assert_eq!(
1094            bach.combine(&triple, SetOperation::SymmetricDifference)
1095                .len(),
1096            1
1097        );
1098        assert_eq!(bach.combine(&core, SetOperation::Union).len(), 4);
1099        assert_eq!(triple.compare_keys(&bach), Some(Ordering::Less));
1100        assert!(!bach.is_disjoint(&triple));
1101        assert_eq!(
1102            bach,
1103            core.search(&RichQuery::Text("bach"), Some("composer"), &[])
1104        );
1105    }
1106
1107    #[test]
1108    fn the_cache_reads_back_what_it_writes() {
1109        let core = bundle();
1110        let read = MetadataBundle::from_cache(&core.to_cache()).unwrap();
1111        assert_eq!(read.name(), Some("core"));
1112        assert_eq!(read.keys(), core.keys());
1113        let (_, first) = read.get(0).unwrap();
1114        assert_eq!(**first, **core.get(0).unwrap().1);
1115        assert!(
1116            read.entry("airdsAirs_book1_abc")
1117                .unwrap()
1118                .metadata
1119                .is_none()
1120        );
1121    }
1122
1123    #[test]
1124    fn validate_drops_what_is_not_there() {
1125        let mut core = bundle();
1126        assert_eq!(core.validate(|path| path.starts_with("bach")), 2);
1127        assert_eq!(core.keys(), ["bach_bwv7_7_mxl", "bach_bwv11_6_mxl"]);
1128    }
1129}