microcad_lang/render/
hash.rs

1// Copyright © 2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Render hash functionality.
5
6use std::hash::Hasher;
7
8use derive_more::Deref;
9
10/// Render hash type.
11pub type HashId = u64;
12
13/// Trait to implement for typed that contain a pre-computed hash value.
14pub trait ComputedHash {
15    /// Return computed hash value.
16    fn computed_hash(&self) -> HashId;
17}
18
19/// Generic wrapper that contains the hashed value.
20#[derive(Deref, Debug, Clone)]
21pub struct Hashed<T: std::hash::Hash> {
22    #[deref]
23    inner: T,
24    hash: HashId,
25}
26
27impl<T: std::hash::Hash> Hashed<T> {
28    /// Create a new wrapper with hashed.
29    pub fn new(inner: T) -> Self {
30        let mut hasher = rustc_hash::FxHasher::default();
31        inner.hash(&mut hasher);
32        Self {
33            inner,
34            hash: hasher.finish(),
35        }
36    }
37}
38
39impl<T: std::hash::Hash> ComputedHash for Hashed<T> {
40    fn computed_hash(&self) -> HashId {
41        self.hash
42    }
43}