summaryrefslogtreecommitdiffstats
path: root/src/hash.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/hash.rs')
-rw-r--r--src/hash.rs52
1 files changed, 52 insertions, 0 deletions
diff --git a/src/hash.rs b/src/hash.rs
index 5de6f3f..8a2d884 100644
--- a/src/hash.rs
+++ b/src/hash.rs
@@ -56,3 +56,55 @@ pub fn recipe_hash(entries: &[(String, String)]) -> String {
pub fn canonical_json<T: serde::Serialize>(v: &T) -> Result<String, serde_json::Error> {
serde_json::to_string(&serde_json::to_value(v)?)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ struct Unserializable;
+
+ impl serde::Serialize for Unserializable {
+ fn serialize<S: serde::Serializer>(&self, _s: S) -> Result<S::Ok, S::Error> {
+ Err(serde::ser::Error::custom("this value cannot be serialized"))
+ }
+ }
+
+ // Moved verbatim from tests/hash.rs. Both tests are a function of their
+ // argument alone; the third test that file held was about `Identity`, not
+ // about hashing, and moved to db::model where it belongs.
+
+ #[test]
+ fn a_value_that_cannot_be_serialized_is_an_error_not_an_empty_object() {
+ let err = canonical_json(&Unserializable).unwrap_err();
+ assert!(err.to_string().contains("cannot be serialized"), "the failure was swallowed: {err}");
+ assert!(canonical_json(&Unserializable).is_err());
+ }
+
+ #[test]
+ fn the_rendering_is_canonical_in_fact_not_in_name() {
+ #[derive(serde::Serialize)]
+ struct Ab {
+ alpha: String,
+ beta: String,
+ }
+ #[derive(serde::Serialize)]
+ struct Ba {
+ beta: String,
+ alpha: String,
+ }
+ let ab = canonical_json(&Ab { alpha: "1".into(), beta: "2".into() }).unwrap();
+ let ba = canonical_json(&Ba { beta: "2".into(), alpha: "1".into() }).unwrap();
+ assert_eq!(ab, ba, "field declaration order leaked into the rendering: {ab} vs {ba}");
+ assert_eq!(ab, r#"{"alpha":"1","beta":"2"}"#, "not the compact sorted rendering");
+
+ let mut one = std::collections::HashMap::new();
+ one.insert("z", 1);
+ one.insert("m", 2);
+ one.insert("a", 3);
+ let mut two = std::collections::HashMap::new();
+ two.insert("a", 3);
+ two.insert("m", 2);
+ two.insert("z", 1);
+ assert_eq!(canonical_json(&one).unwrap(), canonical_json(&two).unwrap());
+ }
+}