add serialization and deserialization for BytesHash (#1645)

* add serialization and deserialization for BytesHash

* fix cargo clippy precedence errors

---------

Co-authored-by: fdecroix <fdecroix@eryx.co>
This commit is contained in:
carlogf 2025-01-07 11:17:33 -03:00 committed by GitHub
parent 356aefb686
commit 02e80e9af0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 41 additions and 6 deletions

View File

@ -369,7 +369,7 @@ pub trait Field:
let mut product = Self::ONE;
for j in 0..bits_u64(power) {
if (power >> j & 1) != 0 {
if ((power >> j) & 1) != 0 {
product *= current;
}
current = current.square();

View File

@ -470,7 +470,7 @@ impl<F: RichField + Extendable<D>, const D: usize> CircuitBuilder<F, D> {
if j != 0 {
current = self.square_extension(current);
}
if (exponent >> j & 1) != 0 {
if ((exponent >> j) & 1) != 0 {
product = self.mul_extension(product, current);
}
}

View File

@ -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;
@ -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>)
}
}