]> git.proxmox.com Git - proxmox-backup.git/blob - proxmox-protocol/src/types.rs
more formatting & use statement fixups
[proxmox-backup.git] / proxmox-protocol / src / types.rs
1 use std::borrow::Borrow;
2
3 use endian_trait::Endian;
4 use failure::*;
5
6 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
7 pub enum IndexType {
8 Fixed,
9 Dynamic,
10 }
11
12 #[derive(Endian, Clone, Debug, Eq, Hash, PartialEq)]
13 #[repr(transparent)]
14 pub struct FixedChunk(pub [u8; 32]);
15
16 impl FixedChunk {
17 pub fn new(hash: [u8; 32]) -> Self {
18 Self(hash)
19 }
20
21 pub fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Error> {
22 Ok(Self::new(crate::tools::parse_hex_digest(hex.as_ref())?))
23 }
24
25 pub fn from_data(data: &[u8]) -> Self {
26 let mut hasher = openssl::sha::Sha256::new();
27 hasher.update(data);
28 Self::new(hasher.finish())
29 }
30
31 pub fn digest_to_hex(&self) -> String {
32 crate::tools::digest_to_hex(&self.0)
33 }
34 }
35
36 #[derive(Endian, Clone, Copy, Debug, Hash)]
37 #[repr(C, packed)]
38 pub struct ChunkEntry {
39 pub hash: [u8; 32],
40 pub size: u64,
41 }
42
43 impl ChunkEntry {
44 pub fn new(hash: [u8; 32], size: u64) -> Self {
45 Self { hash, size }
46 }
47
48 pub fn from_hex<T: AsRef<[u8]>>(hex: T, size: u64) -> Result<Self, Error> {
49 Ok(Self::new(
50 crate::tools::parse_hex_digest(hex.as_ref())?,
51 size,
52 ))
53 }
54
55 pub fn len(&self) -> u64 {
56 self.size
57 }
58
59 pub fn from_data(data: &[u8]) -> Self {
60 let mut hasher = openssl::sha::Sha256::new();
61 hasher.update(data);
62 Self::new(hasher.finish(), data.len() as u64)
63 }
64
65 pub fn digest_to_hex(&self) -> String {
66 crate::tools::digest_to_hex(&self.hash)
67 }
68
69 pub fn to_fixed(&self) -> FixedChunk {
70 FixedChunk(self.hash)
71 }
72 }
73
74 impl PartialEq for ChunkEntry {
75 fn eq(&self, other: &Self) -> bool {
76 self.size == other.size && self.hash == other.hash
77 }
78 }
79
80 impl Eq for ChunkEntry {}
81
82 impl Into<FixedChunk> for ChunkEntry {
83 fn into(self) -> FixedChunk {
84 FixedChunk(self.hash)
85 }
86 }
87
88 impl Borrow<FixedChunk> for ChunkEntry {
89 fn borrow(&self) -> &FixedChunk {
90 unsafe { std::mem::transmute(&self.hash) }
91 }
92 }
93
94 impl Borrow<FixedChunk> for [u8; 32] {
95 fn borrow(&self) -> &FixedChunk {
96 unsafe { std::mem::transmute(self) }
97 }
98 }