khora_data/assets/
storage.rs

1// Copyright 2025 eraflo
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! A generic, type-safe storage for loaded asset handles.
16
17use khora_core::asset::{Asset, AssetHandle, AssetUUID};
18use std::collections::HashMap;
19
20/// A central, in-memory cache for a specific type of asset `A`.
21///
22/// This structure maps a unique `AssetUUID` to a shared `AssetHandle<A>`.
23/// This ensures that any given asset is loaded only once. Subsequent requests
24/// for the same asset will receive a clone of the cached handle.
25#[derive(Default)]
26pub struct Assets<A: Asset> {
27    storage: HashMap<AssetUUID, AssetHandle<A>>,
28}
29
30impl<A: Asset> Clone for Assets<A> {
31    fn clone(&self) -> Self {
32        Self {
33            storage: self.storage.clone(),
34        }
35    }
36}
37
38impl<A: Asset> Assets<A> {
39    /// Creates a new, empty asset storage.
40    pub fn new() -> Self {
41        Self {
42            storage: HashMap::new(),
43        }
44    }
45
46    /// Inserts an asset handle into the storage, associated with its UUID.
47    /// If an asset with the same UUID already exists, it will be replaced.
48    /// This operation is always successful.
49    ///
50    /// # Arguments
51    /// * `uuid` - The unique identifier for the asset.
52    /// * `handle` - The handle to the asset to be stored.
53    pub fn insert(&mut self, uuid: AssetUUID, handle: AssetHandle<A>) {
54        self.storage.insert(uuid, handle);
55    }
56
57    /// Retrieves a reference to the asset handle associated with the given UUID.
58    /// Returns `None` if no asset with the specified UUID is found.
59    pub fn get(&self, uuid: &AssetUUID) -> Option<&AssetHandle<A>> {
60        self.storage.get(uuid)
61    }
62
63    /// Checks if an asset with the specified UUID exists in the storage.
64    pub fn contains(&self, uuid: &AssetUUID) -> bool {
65        self.storage.contains_key(uuid)
66    }
67}