Skip to content

Commit

Permalink
Deterministic serialization of PIL's JSON. (#95)
Browse files Browse the repository at this point in the history
  • Loading branch information
lvella authored Aug 18, 2023
1 parent 78112b9 commit d0bc225
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions starky/src/types.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#![allow(non_snake_case)]
use serde::ser::SerializeMap;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
Expand Down Expand Up @@ -143,6 +144,7 @@ pub struct PIL {
pub nIm: usize,
pub nConstants: usize,
pub publics: Vec<Public>,
#[serde(serialize_with = "ordered_map")]
pub references: HashMap<String, Reference>,
pub expressions: Vec<Expression>,
pub polIdentities: Vec<PolIdentity>,
Expand All @@ -156,6 +158,26 @@ pub struct PIL {
pub q2exp: Vec<usize>,
}

/// Sorted serialization of HashMap.
///
/// For use with serde's [serialize_with] attribute.
fn ordered_map<S, K: Ord + Serialize, V: Serialize>(
value: &HashMap<K, V>,
serializer: S,
) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut ordered = value.iter().collect::<Vec<_>>();
ordered.sort_by_key(|(k, _)| *k);

let mut map = serializer.serialize_map(Some(ordered.len()))?;
for (k, v) in ordered {
map.serialize_entry(k, v)?;
}
map.end()
}

impl fmt::Display for PIL {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let obj = json!(self);
Expand Down

0 comments on commit d0bc225

Please sign in to comment.