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
use crate::{borrowed, SIZE_OF_SHA1_DIGEST};
use bstr::ByteSlice;
use quick_error::quick_error;
use std::{fmt, io, ops::Deref};
quick_error! {
#[derive(Debug)]
#[allow(missing_docs)]
pub enum Error {
HexDecode(err: String) {
display("Failed to hex hash: {}", err)
}
}
}
#[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone, Copy)]
#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
pub struct Digest([u8; SIZE_OF_SHA1_DIGEST]);
impl Digest {
pub fn kind(&self) -> crate::Kind {
crate::Kind::Sha1
}
pub fn to_borrowed(&self) -> borrowed::Digest<'_> {
borrowed::Digest::from(&self.0)
}
pub fn as_slice(&self) -> &[u8] {
self.0.as_ref()
}
pub fn as_mut_slice(&mut self) -> &mut [u8] {
self.0.as_mut()
}
pub fn write_hex_to(&self, mut out: impl io::Write) -> io::Result<()> {
out.write_all(&self.to_sha1_hex())
}
}
impl Digest {
pub fn from_40_bytes_in_hex(buffer: &[u8]) -> Result<Digest, Error> {
use hex::FromHex;
Ok(Digest(
<[u8; 20]>::from_hex(buffer).map_err(|err| Error::HexDecode(err.to_string()))?,
))
}
pub fn sha1(&self) -> &[u8; SIZE_OF_SHA1_DIGEST] {
&self.0
}
pub fn to_sha1_hex(&self) -> [u8; SIZE_OF_SHA1_DIGEST * 2] {
let mut hex_buf = [0u8; 40];
hex::encode_to_slice(self.0, &mut hex_buf).expect("we can count");
hex_buf
}
pub fn to_sha1_hex_string(&self) -> String {
let buf = self.to_sha1_hex();
std::str::from_utf8(&buf).expect("hex is valid UTF-8").to_string()
}
pub fn new_sha1(id: [u8; SIZE_OF_SHA1_DIGEST]) -> Self {
Digest(id)
}
pub fn from_20_bytes(b: &[u8]) -> Digest {
let mut id = [0; SIZE_OF_SHA1_DIGEST];
id.copy_from_slice(b);
Digest(id)
}
pub fn from_borrowed_sha1(b: &[u8; SIZE_OF_SHA1_DIGEST]) -> Digest {
let mut id = [0; SIZE_OF_SHA1_DIGEST];
id.copy_from_slice(&b[..]);
Digest(id)
}
pub fn null_sha1() -> Digest {
Digest([0u8; 20])
}
}
impl From<[u8; SIZE_OF_SHA1_DIGEST]> for Digest {
fn from(v: [u8; 20]) -> Self {
Self::new_sha1(v)
}
}
impl Deref for Digest {
type Target = [u8; SIZE_OF_SHA1_DIGEST];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl fmt::Display for Digest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", &self.to_sha1_hex().as_bstr())
}
}