gled-model 2.30.0

The data model of gled: projects, scenes, effects, animations, curves and assets
Documentation
//! The assets of one kind, and `Collections`: the assets of every kind.

use super::asset::{Asset, AssetTrait};
use crate::asset_id::AssetId;
use std::{collections::BTreeMap, fmt::Debug, sync::Arc};
use typemap::{Key, ShareCloneMap};
use uuid::Uuid;

#[derive(Debug, Clone, Default)]
pub struct Collection<T: AssetTrait>(BTreeMap<Uuid, Arc<Asset<T>>>);

impl<T: AssetTrait + 'static> Key for Collection<T> {
    type Value = Collection<T>;
}

impl<T: AssetTrait> Collection<T> {
    /// returns all assets in the collection
    pub(crate) fn assets(&self) -> Vec<Arc<Asset<T>>> {
        self.0.values().cloned().collect()
    }

    pub fn get(&self, id: &AssetId<T>) -> Option<&Arc<Asset<T>>> {
        self.0.get(&id.id)
    }

    /// The assets as shared, without copying the list.
    pub fn shared(&self) -> impl Iterator<Item = &Arc<Asset<T>>> {
        self.0.values()
    }

    /// Stores an asset that is already shared.
    pub fn insert_shared(&mut self, asset: Arc<Asset<T>>) {
        self.0.insert(asset.id.id, asset);
    }

    /// Overwrite asset in memory cache
    pub fn set_asset(&mut self, asset: Asset<T>) {
        self.0.insert(asset.id.id, Arc::new(asset));
    }

    pub fn delete_asset(&mut self, id: AssetId<T>) {
        self.0.remove(&id.id);
    }

    /// Assets by id, for loading a collection from storage.
    pub fn from_assets(assets: BTreeMap<Uuid, Arc<Asset<T>>>) -> Self {
        Self(assets)
    }
}

/// The assets of every kind, by kind. Cloning is cheap: each asset is shared.
#[derive(Clone)]
pub struct Collections {
    map: ShareCloneMap,
}

impl Default for Collections {
    fn default() -> Self {
        Self {
            map: ShareCloneMap::custom(),
        }
    }
}

impl Debug for Collections {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Collections").finish_non_exhaustive()
    }
}

impl Collections {
    pub fn insert<T: AssetTrait>(&mut self, collection: Collection<T>) {
        self.map.insert::<Collection<T>>(collection);
    }

    pub fn get<T: AssetTrait>(&self) -> Option<&Collection<T>> {
        self.map.get::<Collection<T>>()
    }

    pub fn get_mut<T: AssetTrait>(&mut self) -> &mut Collection<T> {
        self.map
            .entry::<Collection<T>>()
            .or_insert_with(Default::default)
    }
}