feat: make use of the pallas_crypto::Hash type (#25)

This commit is contained in:
Nicolas Di Prima 2022-01-20 15:11:04 +00:00 committed by GitHub
parent 08b92bd34e
commit b74f46fb4a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 13 deletions

View file

@ -1,3 +1,4 @@
use minicbor::{Decode, Encode};
use std::{fmt, ops::Deref, str::FromStr};
/// data that is a cryptographic [`struct@Hash`] of `BYTES` long.
@ -67,6 +68,30 @@ impl<const BYTES: usize> FromStr for Hash<BYTES> {
}
}
impl<const BYTES: usize> Encode for Hash<BYTES> {
fn encode<W: minicbor::encode::Write>(
&self,
e: &mut minicbor::Encoder<W>,
) -> Result<(), minicbor::encode::Error<W::Error>> {
e.bytes(&self.0)?.ok()
}
}
impl<'a, const BYTES: usize> Decode<'a> for Hash<BYTES> {
fn decode(d: &mut minicbor::Decoder<'a>) -> Result<Self, minicbor::decode::Error> {
let bytes = d.bytes()?;
if bytes.len() == BYTES {
let mut hash = [0; BYTES];
hash.copy_from_slice(bytes);
Ok(Self::new(hash))
} else {
// TODO: minicbor does not allow for expecting a specific size byte array
// (in fact cbor is not good at it at all anyway)
Err(minicbor::decode::Error::Message("Invalid hash size"))
}
}
}
#[cfg(test)]
mod tests {
use super::*;