From 50fd48e9e31aa5d781b5e42c011aa5390ea0871f Mon Sep 17 00:00:00 2001 From: Miguel Piedrafita Date: Sun, 24 Dec 2023 19:10:09 +0100 Subject: [PATCH] hash when serializing from json --- ensemble/src/types/hashed.rs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/ensemble/src/types/hashed.rs b/ensemble/src/types/hashed.rs index e69d508..08b144b 100644 --- a/ensemble/src/types/hashed.rs +++ b/ensemble/src/types/hashed.rs @@ -2,6 +2,8 @@ use serde::{Deserialize, Serialize}; use sha256::{digest, Sha256Digest}; use std::{fmt::Debug, ops::Deref}; +use crate::value::deserializing_from_db; + /// A wrapper around a value that has been hashed with SHA-256. #[derive(Clone, Eq, Default)] pub struct Hashed { @@ -79,10 +81,19 @@ impl Serialize for Hashed { impl<'de, T: Sha256Digest> Deserialize<'de> for Hashed { fn deserialize>(deserializer: D) -> Result { - Ok(Self { - _marker: std::marker::PhantomData, - hash: String::deserialize(deserializer)?, - }) + let value = String::deserialize(deserializer)?; + + if deserializing_from_db::() { + Ok(Self { + hash: value, + _marker: std::marker::PhantomData, + }) + } else { + Ok(Self { + hash: digest(value), + _marker: std::marker::PhantomData, + }) + } } }