Skip to main content

firewood_ffi/value/
hash_key.rs

1// Copyright (C) 2025, Ava Labs, Inc. All rights reserved.
2// See the file LICENSE.md for licensing terms.
3
4use std::fmt;
5
6/// A database hash key, used in FFI functions that require hashes.
7/// This type requires no allocation and can be copied freely and
8/// dropped without any additional overhead.
9///
10/// This is useful because it is the same size as 4 words which is equivalent
11/// to 2 heap-allocated slices (pointer + length each), or 1.5 vectors (which
12/// uses an extra word for allocation capacity) and it can be passed around
13/// without needing to allocate or deallocate memory.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
15// Must use `repr(C)` instead of `repr(transparent)` to ensure it is a struct
16// with one field instead of a type alias of an array of 32 element, which is
17// necessary for FFI compatibility so that `HashKey` can be passed by value;
18// otherwise, it would look like a pointer to an array of 32 bytes.
19#[repr(C)]
20pub struct HashKey([u8; 32]);
21
22impl fmt::Display for HashKey {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        super::DisplayHex(&self.0).fmt(f)
25    }
26}
27
28impl From<firewood::api::HashKey> for HashKey {
29    fn from(value: firewood::api::HashKey) -> Self {
30        Self(value.into())
31    }
32}
33
34impl From<HashKey> for firewood::api::HashKey {
35    fn from(value: HashKey) -> Self {
36        value.0.into()
37    }
38}