Skip to content

Commit

Permalink
add serialization and deserialization for BytesHash
Browse files Browse the repository at this point in the history
  • Loading branch information
carlogf authored and fdecroix committed Jan 6, 2025
1 parent 356aefb commit fb4291a
Showing 1 changed file with 39 additions and 4 deletions.
43 changes: 39 additions & 4 deletions plonky2/src/hash/hash_types.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use core::fmt;

use anyhow::ensure;
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::field::goldilocks_field::GoldilocksField;
Expand Down Expand Up @@ -193,19 +195,52 @@ impl<F: RichField, const N: usize> GenericHashOut<F> for BytesHash<N> {
}

impl<const N: usize> Serialize for BytesHash<N> {
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
todo!()
serializer.serialize_bytes(&self.0)
}
}

struct ByteHashVisitor<const N: usize>;

impl<'de, const N: usize> Visitor<'de> for ByteHashVisitor<N> {
type Value = BytesHash<N>;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "an array containing exactly {} bytes", N)
}

fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: de::SeqAccess<'de>,
{
let mut bytes = [0u8; N];
for i in 0..N {
let next_element = seq.next_element()?;
match next_element {
Some(value) => bytes[i] = value,
None => return Err(de::Error::invalid_length(i, &self)),
}
}
Ok(BytesHash(bytes))
}

fn visit_bytes<E>(self, s: &[u8]) -> Result<Self::Value, E>
where
E: de::Error,
{
let bytes = s.try_into().unwrap();
Ok(BytesHash(bytes))
}
}

impl<'de, const N: usize> Deserialize<'de> for BytesHash<N> {
fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
todo!()
deserializer.deserialize_seq(ByteHashVisitor::<N>)
}
}

0 comments on commit fb4291a

Please sign in to comment.