wasmer_wasix/runtime/module_cache/
hashed_module.rs

1use shared_buffer::OwnedBuffer;
2use wasmer_types::ModuleHash;
3
4use crate::bin_factory::BinaryPackageCommand;
5
6/// A wrapper around Webassembly code and its hash.
7///
8/// Allows passing around WASM code and it's hash without the danger of
9/// using a wrong hash.
10///
11/// Safe by construction: can only be created from a [`BinaryPackageCommand`](crate::bin_factory::BinaryPackageCommand), which
12/// already has the hash embedded, or from bytes that will be hashed in the
13/// constructor.
14///
15/// Can be cloned cheaply.
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub struct HashedModuleData {
18    hash: ModuleHash,
19    wasm: OwnedBuffer,
20}
21
22impl HashedModuleData {
23    pub fn new(bytes: impl Into<OwnedBuffer>) -> Self {
24        Self::new_sha256(bytes)
25    }
26
27    pub fn new_sha256(bytes: impl Into<OwnedBuffer>) -> Self {
28        let wasm = bytes.into();
29        let hash = ModuleHash::sha256(&wasm);
30        Self { hash, wasm }
31    }
32
33    /// Create new [`HashedModuleData`] from the given bytes, hashing the
34    /// the bytes into a [`ModuleHash`] with xxhash.
35    pub fn new_xxhash(bytes: impl Into<OwnedBuffer>) -> Self {
36        let wasm = bytes.into();
37        let hash = ModuleHash::xxhash(&wasm);
38        Self { hash, wasm }
39    }
40
41    /// Create new [`HashedModuleData`] from the given [`BinaryPackageCommand`](crate::bin_factory::BinaryPackageCommand).
42    ///
43    /// This is very cheap, as the hash is already available in the command.
44    pub fn from_command(command: &BinaryPackageCommand) -> Self {
45        Self {
46            hash: *command.hash(),
47            wasm: command.atom(),
48        }
49    }
50
51    /// Get the module hash.
52    pub fn hash(&self) -> &ModuleHash {
53        &self.hash
54    }
55
56    /// Get the WASM code.
57    pub fn wasm(&self) -> &OwnedBuffer {
58        &self.wasm
59    }
60
61    pub fn into_parts(self) -> (ModuleHash, OwnedBuffer) {
62        (self.hash, self.wasm)
63    }
64}