Skip to content

Commit

Permalink
Make serialization of packages deterministic.
Browse files Browse the repository at this point in the history
The nondeterminism is causing cache misses for users of bazel, who depend on this for rules_rust's crate_universe package
(https://github.com/bazelbuild/rules_rust/tree/main/crate_universe).
  • Loading branch information
matts1 committed Apr 3, 2023
1 parent 2876c37 commit 0a73e18
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
use camino::Utf8PathBuf;
#[cfg(feature = "builder")]
use derive_builder::Builder;
use std::collections::HashMap;
use std::collections::{BTreeMap, HashMap};
use std::env;
use std::ffi::OsString;
use std::fmt;
Expand Down Expand Up @@ -109,7 +109,7 @@ pub use messages::{
ArtifactBuilder, ArtifactProfileBuilder, BuildFinishedBuilder, BuildScriptBuilder,
CompilerMessageBuilder,
};
use serde::{Deserialize, Serialize};
use serde::{Deserialize, Serialize, Serializer};

mod dependency;
pub mod diagnostic;
Expand Down Expand Up @@ -139,6 +139,18 @@ fn is_null(value: &serde_json::Value) -> bool {
matches!(value, serde_json::Value::Null)
}

/// Helper to ensure that hashmaps serialize in sorted order, to make
/// serialization deterministic.
fn sorted_map<S: Serializer, K: Serialize + Ord, V: Serialize>(
value: &HashMap<K, V>,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
value
.iter()
.collect::<BTreeMap<_, _>>()
.serialize(serializer)
}

#[derive(Clone, Serialize, Deserialize, Debug)]
#[cfg_attr(feature = "builder", derive(Builder))]
#[non_exhaustive]
Expand Down Expand Up @@ -311,6 +323,7 @@ pub struct Package {
/// Targets provided by the crate (lib, bin, example, test, ...)
pub targets: Vec<Target>,
/// Features provided by the crate, mapped to the features required by that feature.
#[serde(serialize_with = "sorted_map")]
pub features: HashMap<String, Vec<String>>,
/// Path containing the `Cargo.toml`
pub manifest_path: Utf8PathBuf,
Expand Down

0 comments on commit 0a73e18

Please sign in to comment.