1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
use std::fmt;
use tag::Tag;
use uvar::Uvar;
#[cfg(feature = "sha-1")]
mod sha1;
#[cfg(feature = "sha-1")]
pub use self::sha1::Sha1;
#[cfg(feature = "sha2")]
mod sha2;
#[cfg(feature = "sha2")]
pub use self::sha2::{Sha2256, Sha2512};
#[cfg(feature = "sha3")]
mod sha3;
#[cfg(feature = "sha3")]
pub use self::sha3::{Sha3224, Sha3256, Sha3384, Sha3512};
#[cfg(feature = "blake2")]
mod blake2;
#[cfg(feature = "blake2")]
pub use self::blake2::{Blake2b512, Blake2s256};
pub trait Multihash: Default + PartialEq {
type Digester: Default;
fn length(&self) -> u8;
fn code(&self) -> Uvar;
fn name(&self) -> &str;
fn digester(&self) -> Self::Digester {
Self::Digester::default()
}
fn digest_primitive(&self, tag: Tag, bytes: &[u8]) -> Harvest;
fn digest_collection(&self, tag: Tag, list: Vec<Vec<u8>>) -> Harvest;
}
#[derive(Debug)]
pub enum MultihashError {
Unknown,
}
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct Harvest(Box<[u8]>);
impl AsRef<[u8]> for Harvest {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl fmt::Display for Harvest {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
for byte in self.0.as_ref() {
write!(formatter, "{:02x}", byte)?;
}
Ok(())
}
}
impl Harvest {
pub fn as_slice(&self) -> &[u8] {
&self.0
}
}
impl From<Vec<u8>> for Harvest {
fn from(vec: Vec<u8>) -> Self {
Harvest(vec.into_boxed_slice())
}
}
impl From<Box<[u8]>> for Harvest {
fn from(b: Box<[u8]>) -> Self {
Harvest(b)
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct Hash<T: Multihash> {
tag: T,
digest: Harvest,
}
impl<T: Multihash> Hash<T> {
pub fn new<D: Into<Harvest>>(tag: T, digest: D) -> Hash<T> {
Hash {
tag,
digest: digest.into(),
}
}
pub fn digest(&self) -> &Harvest {
&self.digest
}
pub fn tag(&self) -> &T {
&self.tag
}
}
impl<T: Multihash> fmt::Display for Hash<T> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "{:02x}", &self.tag.code())?;
write!(formatter, "{:02x}", &self.tag.length())?;
write!(formatter, "{}", &self.digest)?;
Ok(())
}
}