casper_node/types/
chunkable.rs

1use std::{borrow::Cow, convert::Infallible};
2
3use casper_types::{
4    bytesrepr::{self, Bytes, ToBytes},
5    execution::{ExecutionResult, ExecutionResultV1, ExecutionResultV2},
6    Digest,
7};
8
9use super::value_or_chunk::HashingTrieRaw;
10
11/// Implemented for types that are chunked when sending over the wire and/or before storing the
12/// trie store.
13pub trait Chunkable {
14    /// Error returned when mapping `Self` into bytes.
15    type Error: std::fmt::Debug;
16    /// Maps `Self` into bytes.
17    ///
18    /// Returns a [`Cow`] instance in case the resulting bytes are the same as input and we don't
19    /// want to reinitialize. This also helps with a case where returning a vector of bytes
20    /// would require instantiating a `Vec<u8>` locally (see [`casper_types::bytesrepr::ToBytes`])
21    /// but can't be returned as reference. Alternative encoding would be to consume `Self` and
22    /// return `Vec<u8>` but that may do it unnecessarily if `Self` would be to used again.
23    fn as_bytes(&self) -> Result<Cow<Vec<u8>>, Self::Error>;
24
25    /// Serializes the `self` using the [`Chunkable`] implementation for that type
26    /// and returns a [`Digest`] of the serialized bytes.
27    fn hash(&self) -> Result<Digest, Self::Error> {
28        let bytes = self.as_bytes()?;
29        Ok(Digest::hash_into_chunks_if_necessary(&bytes))
30    }
31}
32
33impl Chunkable for Vec<u8> {
34    type Error = Infallible;
35
36    fn as_bytes(&self) -> Result<Cow<Vec<u8>>, Self::Error> {
37        Ok(Cow::Borrowed(self))
38    }
39}
40
41impl Chunkable for Bytes {
42    type Error = Infallible;
43
44    fn as_bytes(&self) -> Result<Cow<Vec<u8>>, Self::Error> {
45        Ok(Cow::Borrowed(self.inner_bytes()))
46    }
47}
48
49impl Chunkable for HashingTrieRaw {
50    type Error = Infallible;
51
52    fn as_bytes(&self) -> Result<Cow<Vec<u8>>, Self::Error> {
53        Ok(Cow::Borrowed(self.inner().inner().inner_bytes()))
54    }
55}
56
57impl Chunkable for &Vec<ExecutionResult> {
58    type Error = bytesrepr::Error;
59
60    fn as_bytes(&self) -> Result<Cow<Vec<u8>>, Self::Error> {
61        Ok(Cow::Owned((*self).to_bytes()?))
62    }
63}
64
65impl Chunkable for Vec<ExecutionResult> {
66    type Error = bytesrepr::Error;
67
68    fn as_bytes(&self) -> Result<Cow<Vec<u8>>, Self::Error> {
69        Ok(Cow::Owned(self.to_bytes()?))
70    }
71}
72
73impl Chunkable for Vec<&ExecutionResultV1> {
74    type Error = bytesrepr::Error;
75
76    fn as_bytes(&self) -> Result<Cow<Vec<u8>>, Self::Error> {
77        Ok(Cow::Owned(self.to_bytes()?))
78    }
79}
80
81impl Chunkable for Vec<&ExecutionResultV2> {
82    type Error = bytesrepr::Error;
83
84    fn as_bytes(&self) -> Result<Cow<Vec<u8>>, Self::Error> {
85        Ok(Cow::Owned(self.to_bytes()?))
86    }
87}