holo_hash/
hashable_content.rs

1use crate::HashType;
2use holochain_serialized_bytes::prelude::*;
3
4/// Any implementor of HashableContent may be used in a HoloHashed to pair
5/// data with its HoloHash representation. It also has an associated HashType.
6pub trait HashableContent: Sized {
7    /// The HashType which this content will be hashed to
8    type HashType: HashType;
9
10    /// The HashType which this content will be hashed to
11    fn hash_type(&self) -> Self::HashType;
12
13    /// Return a subset of the content, either as SerializedBytes "content",
14    /// which will be used to compute the hash, or as an already precomputed
15    /// hash which will be used directly
16    fn hashable_content(&self) -> HashableContentBytes;
17}
18
19/// HashableContent can be expressed as "content", or "prehashed", which affects
20/// how a HoloHashed type will be constructed from it.
21pub enum HashableContentBytes {
22    /// Denotes that the hash should be computed for the given data
23    Content(SerializedBytes),
24    /// Denotes that the given bytes already constitute a valid HoloHash
25    Prehashed39(Vec<u8>),
26}
27
28/// A default HashableContent implementation, suitable for content which
29/// is already `TryInto<SerializedBytes>`, and uses a PrimitiveHashType
30#[macro_export]
31macro_rules! impl_hashable_content {
32    ($n: ident, $t: ident) => {
33        impl HashableContent for $n {
34            type HashType = holo_hash::hash_type::$t;
35
36            fn hash_type(&self) -> Self::HashType {
37                use holo_hash::PrimitiveHashType;
38                holo_hash::hash_type::$t::new()
39            }
40
41            fn hashable_content(&self) -> $crate::HashableContentBytes {
42                $crate::HashableContentBytes::Content(
43                    self.try_into()
44                        .expect("Could not serialize HashableContent"),
45                )
46            }
47        }
48    };
49}