khora_core/asset/
uuid.rs

1// Copyright 2025 eraflo
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may 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
15use serde::{Deserialize, Serialize};
16use uuid::Uuid;
17
18/// A constant, randomly generated namespace for our asset UUIDs.
19/// This ensures that UUIDs generated from the same path are always the same.
20const ASSET_NAMESPACE_UUID: Uuid = Uuid::from_u128(0x4a6a81e9_f0d1_4b8f_91a8_7e7a5e0b6b4a);
21
22/// A globally unique, persistent identifier for a logical asset.
23///
24/// This UUID represents the "idea" of an asset, completely decoupled from its
25/// physical file path. It is the primary key used by the Virtual File System (VFS)
26/// to track and retrieve asset metadata.
27///
28/// By using a stable UUID, assets can be moved, renamed, or have their source
29/// data modified without breaking references to them in scenes or other assets.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
31pub struct AssetUUID(Uuid);
32
33impl AssetUUID {
34    /// Creates a new, random (version 4) `AssetUUID`.
35    pub fn new() -> Self {
36        Self(Uuid::new_v4())
37    }
38
39    /// Creates a new, stable AssetUUID (version 5) from a given path.
40    ///
41    /// This is the preferred method for generating UUIDs for assets on disk,
42    /// as it guarantees that the UUID will be the same every time the asset
43    /// pipeline is run for the same file.
44    pub fn new_v5(path_str: &str) -> Self {
45        Self(Uuid::new_v5(&ASSET_NAMESPACE_UUID, path_str.as_bytes()))
46    }
47}
48
49impl Default for AssetUUID {
50    /// Creates a new, random (version 4) `AssetUUID`.
51    fn default() -> Self {
52        Self::new()
53    }
54}