Convert items from library directly to hashmap
All checks were successful
Cargo CI / Build and Test (pull_request) Successful in 1m5s
Cargo CI / Lint (pull_request) Successful in 45s

This commit is contained in:
Wojciech Kozlowski 2024-01-14 14:57:11 +01:00
parent f3b0cc4035
commit 639e464ff5

View File

@ -5,7 +5,7 @@ pub mod library;
use std::{
cmp::Ordering,
collections::{HashMap, HashSet},
collections::HashMap,
fmt::{self, Debug, Display},
iter::Peekable,
mem,
@ -856,15 +856,15 @@ impl<LIB, DB> MusicHoard<LIB, DB> {
fn sort(collection: &mut [Artist]) {
Self::sort_artists(collection);
Self::sort_albums_and_tracks(collection);
Self::sort_albums_and_tracks(collection.iter_mut());
}
fn sort_artists(collection: &mut [Artist]) {
collection.sort_unstable();
}
fn sort_albums_and_tracks(collection: &mut [Artist]) {
for artist in collection.iter_mut() {
fn sort_albums_and_tracks<'a, COL: Iterator<Item = &'a mut Artist>>(collection: COL) {
for artist in collection {
artist.albums.sort_unstable();
for album in artist.albums.iter_mut() {
album.tracks.sort_unstable();
@ -872,11 +872,9 @@ impl<LIB, DB> MusicHoard<LIB, DB> {
}
}
fn merge_with_primary(&mut self, primary: Vec<Artist>) {
let primary_map: HashMap<ArtistId, Artist> =
primary.into_iter().map(|a| (a.id.clone(), a)).collect();
fn merge_with_primary(&mut self, primary: HashMap<ArtistId, Artist>) {
let collection = mem::take(&mut self.collection);
self.collection = Self::merge_collections(primary_map, collection);
self.collection = Self::merge_collections(primary, collection);
}
fn merge_with_secondary<SEC: IntoIterator<Item = Artist>>(&mut self, secondary: SEC) {
@ -904,9 +902,8 @@ impl<LIB, DB> MusicHoard<LIB, DB> {
collection
}
fn items_to_artists(items: Vec<Item>) -> Result<Vec<Artist>, Error> {
let mut artists: Vec<Artist> = vec![];
let mut album_ids = HashMap::<ArtistId, HashSet<AlbumId>>::new();
fn items_to_artists(items: Vec<Item>) -> Result<HashMap<ArtistId, Artist>, Error> {
let mut collection = HashMap::<ArtistId, Artist>::new();
for item in items.into_iter() {
let artist_id = ArtistId {
@ -932,19 +929,14 @@ impl<LIB, DB> MusicHoard<LIB, DB> {
},
};
let artist = if album_ids.contains_key(&artist_id) {
// Assume results are in some order which means they will likely be grouped by
// artist. Therefore, we look from the back since the last inserted artist is most
// likely the one we are looking for.
artists
.iter_mut()
.rev()
.find(|a| a.id == artist_id)
.unwrap()
} else {
album_ids.insert(artist_id.clone(), HashSet::<AlbumId>::new());
artists.push(Artist::new(artist_id.clone()));
artists.last_mut().unwrap()
// There are usually many entries per artist. Therefore, we avoid simply calling
// .entry(artist_id.clone()).or_insert_with(..), because of the clone. The flipside is
// that insertions will thus do an additional lookup.
let artist = match collection.get_mut(&artist_id) {
Some(artist) => artist,
None => collection
.entry(artist_id.clone())
.or_insert_with(|| Artist::new(artist_id)),
};
if artist.sort.is_some() {
@ -960,30 +952,23 @@ impl<LIB, DB> MusicHoard<LIB, DB> {
artist.sort = artist_sort;
}
if album_ids[&artist_id].contains(&album_id) {
// Assume results are in some order which means they will likely be grouped by
// album. Therefore, we look from the back since the last inserted album is most
// likely the one we are looking for.
let album = artist
// Do a linear search as few artists have more than a handful of albums. Search from the
// back as the original items vector is usually already sorted.
match artist
.albums
.iter_mut()
.rev()
.find(|a| a.id == album_id)
.unwrap();
album.tracks.push(track);
} else {
album_ids
.get_mut(&artist_id)
.unwrap()
.insert(album_id.clone());
artist.albums.push(Album {
.find(|album| album.id == album_id)
{
Some(album) => album.tracks.push(track),
None => artist.albums.push(Album {
id: album_id,
tracks: vec![track],
});
}),
}
}
Ok(artists)
Ok(collection)
}
fn get_artist(&self, artist_id: &ArtistId) -> Option<&Artist> {
@ -1006,7 +991,7 @@ impl<LIB: ILibrary, DB> MusicHoard<LIB, DB> {
pub fn rescan_library(&mut self) -> Result<(), Error> {
let items = self.library.list(&Query::new())?;
let mut library_collection = Self::items_to_artists(items)?;
Self::sort_albums_and_tracks(&mut library_collection);
Self::sort_albums_and_tracks(library_collection.values_mut());
self.merge_with_primary(library_collection);
Ok(())
@ -1017,7 +1002,7 @@ impl<LIB, DB: IDatabase> MusicHoard<LIB, DB> {
/// Load the database and merge with the in-memory collection.
pub fn load_from_database(&mut self) -> Result<(), Error> {
let mut database_collection = self.database.load()?;
Self::sort_albums_and_tracks(&mut database_collection);
Self::sort_albums_and_tracks(database_collection.iter_mut());
self.merge_with_secondary(database_collection);
Ok(())
@ -1994,14 +1979,21 @@ mod tests {
expected.sort_unstable();
let merged = MusicHoard::<NoLibrary, NoDatabase>::merge_collections(
left.clone().into_iter().map(|a| (a.id.clone(), a)).collect(),
left.clone()
.into_iter()
.map(|a| (a.id.clone(), a))
.collect(),
right.clone(),
);
assert_eq!(expected, merged);
// The merge is completele non-overlapping so it should be commutative.
let merged = MusicHoard::<NoLibrary, NoDatabase>::merge_collections(
right.clone().into_iter().map(|a| (a.id.clone(), a)).collect(),
right
.clone()
.into_iter()
.map(|a| (a.id.clone(), a))
.collect(),
left.clone(),
);
assert_eq!(expected, merged);
@ -2018,14 +2010,21 @@ mod tests {
expected.sort_unstable();
let merged = MusicHoard::<NoLibrary, NoDatabase>::merge_collections(
left.clone().into_iter().map(|a| (a.id.clone(), a)).collect(),
left.clone()
.into_iter()
.map(|a| (a.id.clone(), a))
.collect(),
right.clone(),
);
assert_eq!(expected, merged);
// The merge does not overwrite any data so it should be commutative.
let merged = MusicHoard::<NoLibrary, NoDatabase>::merge_collections(
right.clone().into_iter().map(|a| (a.id.clone(), a)).collect(),
right
.clone()
.into_iter()
.map(|a| (a.id.clone(), a))
.collect(),
left.clone(),
);
assert_eq!(expected, merged);
@ -2055,7 +2054,10 @@ mod tests {
expected.rotate_right(1);
let merged = MusicHoard::<NoLibrary, NoDatabase>::merge_collections(
left.clone().into_iter().map(|a| (a.id.clone(), a)).collect(),
left.clone()
.into_iter()
.map(|a| (a.id.clone(), a))
.collect(),
right.clone(),
);
assert_eq!(expected.len(), merged.len());
@ -2063,7 +2065,11 @@ mod tests {
// The merge overwrites the sort data, but no data is erased so it should be commutative.
let merged = MusicHoard::<NoLibrary, NoDatabase>::merge_collections(
right.clone().into_iter().map(|a| (a.id.clone(), a)).collect(),
right
.clone()
.into_iter()
.map(|a| (a.id.clone(), a))
.collect(),
left.clone(),
);
assert_eq!(expected.len(), merged.len());