Skip to content

Commit

Permalink
hash when serializing from json
Browse files Browse the repository at this point in the history
  • Loading branch information
m1guelpf committed Dec 24, 2023
1 parent 5e4b1fc commit 50fd48e
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions ensemble/src/types/hashed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use serde::{Deserialize, Serialize};
use sha256::{digest, Sha256Digest};
use std::{fmt::Debug, ops::Deref};

use crate::value::deserializing_from_db;

Check failure on line 5 in ensemble/src/types/hashed.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unresolved import `crate::value::deserializing_from_db`

/// A wrapper around a value that has been hashed with SHA-256.
#[derive(Clone, Eq, Default)]
pub struct Hashed<T: Sha256Digest> {
Expand Down Expand Up @@ -79,10 +81,19 @@ impl<T: Sha256Digest> Serialize for Hashed<T> {

impl<'de, T: Sha256Digest> Deserialize<'de> for Hashed<T> {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(Self {
_marker: std::marker::PhantomData,
hash: String::deserialize(deserializer)?,
})
let value = String::deserialize(deserializer)?;

if deserializing_from_db::<D>() {
Ok(Self {
hash: value,
_marker: std::marker::PhantomData,
})
} else {
Ok(Self {
hash: digest(value),
_marker: std::marker::PhantomData,
})
}
}
}

Expand Down

0 comments on commit 50fd48e

Please sign in to comment.