diff options
author | Lars Wirzenius <liw@liw.fi> | 2021-09-18 15:03:15 +0000 |
---|---|---|
committer | Lars Wirzenius <liw@liw.fi> | 2021-09-18 15:03:15 +0000 |
commit | 7f3f30b0e4b7713d0a6106babf662127ac457210 (patch) | |
tree | 9bb7ec9420c2bbd6e3fb9103ee298c445746d3d7 /src/checksummer.rs | |
parent | d6728974b98a821b8d633197abd97cf2fc9357f5 (diff) | |
parent | 97b9327ac7f73b3a2629cd90da20d1655bf9478e (diff) | |
download | obnam2-7f3f30b0e4b7713d0a6106babf662127ac457210.tar.gz |
Merge branch 'checksum-type' into 'main'
refactor: define a Checksum type and use it where appropriate
Closes #136
See merge request obnam/obnam!180
Diffstat (limited to 'src/checksummer.rs')
-rw-r--r-- | src/checksummer.rs | 32 |
1 files changed, 27 insertions, 5 deletions
diff --git a/src/checksummer.rs b/src/checksummer.rs index 162c26b..18b8afb 100644 --- a/src/checksummer.rs +++ b/src/checksummer.rs @@ -1,8 +1,30 @@ use sha2::{Digest, Sha256}; +use std::fmt; -pub fn sha256(data: &[u8]) -> String { - let mut hasher = Sha256::new(); - hasher.update(data); - let hash = hasher.finalize(); - format!("{:x}", hash) +/// A checksum of some data. +#[derive(Debug, Clone)] +pub enum Checksum { + Sha256(String), +} + +impl Checksum { + pub fn sha256(data: &[u8]) -> Self { + let mut hasher = Sha256::new(); + hasher.update(data); + let hash = hasher.finalize(); + Self::Sha256(format!("{:x}", hash)) + } + + pub fn sha256_from_str_unchecked(hash: &str) -> Self { + Self::Sha256(hash.to_string()) + } +} + +impl fmt::Display for Checksum { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let hash = match self { + Self::Sha256(hash) => hash, + }; + write!(f, "{}", hash) + } } |