Skip to main content

opys_core/
integrity.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
4#[serde(untagged)]
5pub enum HashEntry {
6    Sha256 { sha256: String },
7    Sha1 { sha1: String },
8    Md5 { md5: String },
9}
10
11/// One entry, multiple entries, or omitted (= skip verification).
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13#[serde(untagged)]
14pub enum Integrity {
15    One(HashEntry),
16    Many(Vec<HashEntry>),
17}
18
19impl Integrity {
20    /// Borrow as a slice of hash entries — `One` becomes a one-element slice.
21    pub fn entries(&self) -> &[HashEntry] {
22        match self {
23            Integrity::One(h) => std::slice::from_ref(h),
24            Integrity::Many(v) => v.as_slice(),
25        }
26    }
27
28    /// Collapse a single-element list back to a bare entry.
29    pub fn collapsed(self) -> Self {
30        match self {
31            Integrity::Many(mut v) if v.len() == 1 => Integrity::One(v.pop().unwrap()),
32            other => other,
33        }
34    }
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub enum HashAlgo {
39    Sha1,
40    Sha256,
41    Md5,
42}
43
44impl HashAlgo {
45    pub fn hex_len(self) -> usize {
46        match self {
47            HashAlgo::Sha1 => 40,
48            HashAlgo::Sha256 => 64,
49            HashAlgo::Md5 => 32,
50        }
51    }
52}
53
54impl HashEntry {
55    pub fn algo(&self) -> HashAlgo {
56        match self {
57            HashEntry::Sha256 { .. } => HashAlgo::Sha256,
58            HashEntry::Sha1 { .. } => HashAlgo::Sha1,
59            HashEntry::Md5 { .. } => HashAlgo::Md5,
60        }
61    }
62
63    pub fn hex(&self) -> &str {
64        match self {
65            HashEntry::Sha256 { sha256 } => sha256,
66            HashEntry::Sha1 { sha1 } => sha1,
67            HashEntry::Md5 { md5 } => md5,
68        }
69    }
70}