Skip to main content

imdl/
md5_digest.rs

1use crate::common::*;
2
3#[derive(Deserialize, Serialize, Debug, Eq, PartialEq, Copy, Clone)]
4#[serde(transparent)]
5pub(crate) struct Md5Digest {
6  #[serde(with = "SerHex::<serde_hex::Strict>")]
7  bytes: [u8; 16],
8}
9
10impl Md5Digest {
11  #[cfg(test)]
12  pub(crate) fn from_hex(hex: &str) -> Self {
13    assert_eq!(hex.len(), 32);
14
15    let mut bytes: [u8; 16] = [0; 16];
16
17    for (n, byte) in bytes.iter_mut().enumerate() {
18      let i = n * 2;
19      *byte = u8::from_str_radix(&hex[i..i + 2], 16).unwrap();
20    }
21
22    Self { bytes }
23  }
24
25  #[cfg(test)]
26  pub(crate) fn from_data(data: impl AsRef<[u8]>) -> Self {
27    md5::compute(data).into()
28  }
29}
30
31impl From<md5::Digest> for Md5Digest {
32  fn from(digest: md5::Digest) -> Self {
33    Self { bytes: digest.0 }
34  }
35}
36
37impl Display for Md5Digest {
38  fn fmt(&self, f: &mut Formatter) -> fmt::Result {
39    for byte in &self.bytes {
40      write!(f, "{byte:02x}")?;
41    }
42
43    Ok(())
44  }
45}
46
47#[cfg(test)]
48mod tests {
49  use super::*;
50
51  #[test]
52  fn ser() {
53    let digest = Md5Digest {
54      bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
55    };
56
57    let bytes = bendy::serde::ser::to_bytes(&digest).unwrap();
58
59    assert_eq!(
60      str::from_utf8(&bytes).unwrap(),
61      "32:000102030405060708090a0b0c0d0e0f"
62    );
63
64    let string_bytes = bendy::serde::ser::to_bytes(&"000102030405060708090a0b0c0d0e0f").unwrap();
65
66    assert_eq!(bytes, string_bytes);
67  }
68
69  #[test]
70  fn display() {
71    let digest = Md5Digest {
72      bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
73    };
74
75    assert_eq!(digest.to_string(), "000102030405060708090a0b0c0d0e0f");
76  }
77}