assemblyline_models/types/
sha256.rs1use std::str::FromStr;
2
3use serde_with::{DeserializeFromStr, SerializeDisplay};
4use struct_metadata::Described;
5
6use crate::{ElasticMeta, ModelError};
7
8
9#[derive(Debug, SerializeDisplay, DeserializeFromStr, Described, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
11#[metadata(normalizer="lowercase_normalizer")]
12#[metadata_type(ElasticMeta)]
13pub struct Sha256(String);
14
15impl std::fmt::Display for Sha256 {
16 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17 f.write_str(&self.0)
18 }
19}
20
21impl std::ops::Deref for Sha256 {
22 type Target = str;
23
24 fn deref(&self) -> &Self::Target {
25 &self.0
26 }
27}
28
29pub fn is_sha256(hex: &str) -> bool {
30 hex.len() == 64 && hex.chars().all(|c|c.is_ascii_hexdigit())
31}
32
33impl FromStr for Sha256 {
34 type Err = ModelError;
35
36 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
37 let hex = s.trim().to_ascii_lowercase();
38 if !is_sha256(&hex) {
39 return Err(ModelError::InvalidSha256(hex))
40 }
41 Ok(Sha256(hex))
42 }
43}
44
45impl TryFrom<&[u8]> for Sha256 {
46 type Error = ModelError;
47
48 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
49 Self::from_str(&hex::encode(value))
50 }
51}
52
53
54#[cfg(feature = "rand")]
55impl rand::distr::Distribution<Sha256> for rand::distr::StandardUniform {
56 fn sample<R: rand::prelude::Rng + ?Sized>(&self, rng: &mut R) -> Sha256 {
57 use crate::random_hex;
58
59 Sha256(random_hex(rng, 64))
60 }
61}