Skip to content

Commit

Permalink
Progress with quoted lists
Browse files Browse the repository at this point in the history
  • Loading branch information
paulhauner committed Sep 5, 2020
1 parent 925722c commit c48ba5e
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 4 deletions.
19 changes: 19 additions & 0 deletions common/eth2/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ mod validator_status;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
use types::serde_utils;

pub use types::{Checkpoint, Fork, Hash256, PublicKeyBytes, Slot};
pub use validator_status::{ValidatorData, ValidatorStatus};
Expand Down Expand Up @@ -163,3 +164,21 @@ impl fmt::Display for ValidatorId {
}
}
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CommitteeData {
#[serde(with = "serde_utils::quoted")]
pub index: u64,
pub slot: Slot,
#[serde(with = "serde_utils::quoted_u64_vec")]
pub validators: Vec<u64>,
}

/*
QuotedItem<T>(T);
impl<T: Serialize> fmt::Display for QuotedVec<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
}
}
*/
59 changes: 55 additions & 4 deletions consensus/types/src/utils/serde_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,10 +278,7 @@ pub mod quoted {
type Value = u64;

fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
formatter,
"a string containing digits or an int fitting into u64"
)
write!(formatter, "a quoted or unquoted integer")
}

fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
Expand Down Expand Up @@ -311,3 +308,57 @@ pub mod quoted {
deserializer.deserialize_any(QuotedIntVisitor)
}
}

pub mod quoted_u64_vec {
use super::*;
use serde::ser::SerializeSeq;
use serde_derive::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
#[serde(transparent)]
pub struct QuotedIntWrapper {
#[serde(with = "super::quoted")]
int: u64,
}

pub struct QuotedIntVecVisitor;
impl<'a> serde::de::Visitor<'a> for QuotedIntVecVisitor {
type Value = Vec<u64>;

fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(formatter, "a list of quoted or unquoted integers")
}

fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'a>,
{
let mut vec = vec![];

while let Some(val) = seq.next_element()? {
let val: QuotedIntWrapper = val;
vec.push(val.int);
}

Ok(vec)
}
}

pub fn serialize<S>(value: &Vec<u64>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(Some(value.len()))?;
for &int in value {
seq.serialize_element(&QuotedIntWrapper { int })?;
}
seq.end()
}

pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u64>, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(QuotedIntVecVisitor)
}
}

0 comments on commit c48ba5e

Please sign in to comment.