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> Assets<A> {
31    /// Creates a new, empty asset storage.
32    pub fn new() -> Self {
33        Self {
34            storage: HashMap::new(),
35        }
36    }
37
38    /// Inserts an asset handle into the storage, associated with its UUID.
39    /// If an asset with the same UUID already exists, it will be replaced.
40    /// This operation is always successful.
41    ///
42    /// # Arguments
43    /// * `uuid` - The unique identifier for the asset.
44    /// * `handle` - The handle to the asset to be stored.
45    pub fn insert(&mut self, uuid: AssetUUID, handle: AssetHandle<A>) {
46        self.storage.insert(uuid, handle);
47    }
48
49    /// Retrieves a reference to the asset handle associated with the given UUID.
50    /// Returns `None` if no asset with the specified UUID is found.
51    pub fn get(&self, uuid: &AssetUUID) -> Option<&AssetHandle<A>> {
52        self.storage.get(uuid)
53    }
54
55    /// Checks if an asset with the specified UUID exists in the storage.
56    pub fn contains(&self, uuid: &AssetUUID) -> bool {
57        self.storage.contains_key(uuid)
58    }
59}