use std::{borrow::Cow, convert::Infallible};
use casper_types::{
bytesrepr::{self, Bytes, ToBytes},
execution::{ExecutionResult, ExecutionResultV1, ExecutionResultV2},
Digest,
};
use super::value_or_chunk::HashingTrieRaw;
pub trait Chunkable {
type Error: std::fmt::Debug;
fn as_bytes(&self) -> Result<Cow<Vec<u8>>, Self::Error>;
fn hash(&self) -> Result<Digest, Self::Error> {
let bytes = self.as_bytes()?;
Ok(Digest::hash_into_chunks_if_necessary(&bytes))
}
}
impl Chunkable for Vec<u8> {
type Error = Infallible;
fn as_bytes(&self) -> Result<Cow<Vec<u8>>, Self::Error> {
Ok(Cow::Borrowed(self))
}
}
impl Chunkable for Bytes {
type Error = Infallible;
fn as_bytes(&self) -> Result<Cow<Vec<u8>>, Self::Error> {
Ok(Cow::Borrowed(self.inner_bytes()))
}
}
impl Chunkable for HashingTrieRaw {
type Error = Infallible;
fn as_bytes(&self) -> Result<Cow<Vec<u8>>, Self::Error> {
Ok(Cow::Borrowed(self.inner().inner().inner_bytes()))
}
}
impl Chunkable for &Vec<ExecutionResult> {
type Error = bytesrepr::Error;
fn as_bytes(&self) -> Result<Cow<Vec<u8>>, Self::Error> {
Ok(Cow::Owned((*self).to_bytes()?))
}
}
impl Chunkable for Vec<ExecutionResult> {
type Error = bytesrepr::Error;
fn as_bytes(&self) -> Result<Cow<Vec<u8>>, Self::Error> {
Ok(Cow::Owned(self.to_bytes()?))
}
}
impl Chunkable for Vec<&ExecutionResultV1> {
type Error = bytesrepr::Error;
fn as_bytes(&self) -> Result<Cow<Vec<u8>>, Self::Error> {
Ok(Cow::Owned(self.to_bytes()?))
}
}
impl Chunkable for Vec<&ExecutionResultV2> {
type Error = bytesrepr::Error;
fn as_bytes(&self) -> Result<Cow<Vec<u8>>, Self::Error> {
Ok(Cow::Owned(self.to_bytes()?))
}
}