wasmer_types/
module_hash.rs

1use std::{
2    fmt::{self, Display, Formatter},
3    hash::Hash,
4};
5
6use rkyv::{Archive, Deserialize as RkyvDeserialize, Serialize as RkyvSerialize};
7#[cfg(feature = "enable-serde")]
8use serde::{Deserialize, Serialize};
9use sha2::Digest;
10
11/// The hash of a WebAssembly module.
12#[derive(
13    Debug,
14    Copy,
15    Clone,
16    PartialEq,
17    Eq,
18    Hash,
19    PartialOrd,
20    Ord,
21    RkyvSerialize,
22    RkyvDeserialize,
23    Archive,
24)]
25#[rkyv(derive(Debug))]
26#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
27pub struct ModuleHash([u8; 32]);
28
29#[cfg(feature = "artifact-size")]
30impl loupe::MemoryUsage for ModuleHash {
31    fn size_of_val(&self, _tracker: &mut dyn loupe::MemoryUsageTracker) -> usize {
32        size_of::<ModuleHash>()
33    }
34}
35
36impl ModuleHash {
37    /// Generate a new [`ModuleHash`] based on the Sha256 hash of some bytes.
38    pub fn new(wasm: impl AsRef<[u8]>) -> Self {
39        let wasm = wasm.as_ref();
40        let hash = sha2::Sha256::digest(wasm).into();
41        Self(hash)
42    }
43
44    /// Generate a new [`ModuleHash`] based on the Sha256 hash of some bytes.
45    pub fn sha256(wasm: impl AsRef<[u8]>) -> Self {
46        Self::new(wasm)
47    }
48
49    /// Create a new [`ModuleHash`] from the raw sha256 hash.
50    pub fn from_bytes(hash: [u8; 32]) -> Self {
51        Self(hash)
52    }
53
54    /// Generate a random [`ModuleHash`]. For when you don't care about caches.
55    pub fn random() -> Self {
56        let mut bytes = [0_u8; _];
57        getrandom::fill(&mut bytes).unwrap();
58        Self(bytes)
59    }
60
61    /// Get the raw hash.
62    pub fn as_bytes(&self) -> &[u8] {
63        &self.0
64    }
65
66    /// Build a short hex representation of the hash (first 4 bytes).
67    pub fn short_hash(&self) -> String {
68        hex::encode_upper(&self.as_bytes()[..4])
69    }
70}
71
72impl Display for ModuleHash {
73    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
74        write!(f, "{}", hex::encode_upper(self.as_bytes()))
75    }
76}