-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathdigest.rs
275 lines (240 loc) · 7.54 KB
/
digest.rs
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
use std::str;
use std::io::{self, Write, Read};
use std::fmt::{self, Write as WriteFmt};
use std::path::{Path, PathBuf};
use std::os::unix::ffi::OsStrExt;
use blake2::Blake2b;
use digest_traits::{Digest as DigestTrait, FixedOutput};
use serde_json;
use sha2::Sha256;
use crate::config::Range;
/// This is a wrapper that has convenience methods for hashing in vagga
/// commands
pub struct Digest {
sha: DebugWriter,
debug: Opt<String>,
}
/// This is internal trait only
pub trait Digestable {
fn digest(&self, title: &str, dig: &mut Digest);
}
enum Opt<W> {
Out(W),
Sink,
}
/// This just copies the hash data into a buffer for debugging
struct DebugWriter {
sha: Blake2b,
data: Opt<Vec<u8>>,
}
/// A wrapper type used for hexlification, use `hex()` function
pub struct ShowHex<'a, T: 'a>(&'a T);
static LOWER_CHARS: &'static[u8] = b"0123456789abcdef";
impl Digest {
pub fn new(debug: bool, raw_debug: bool) -> Digest {
Digest {
sha: DebugWriter {
sha: Blake2b::new(),
data: if raw_debug { Opt::Out(Vec::new()) } else { Opt::Sink },
},
debug: if debug { Opt::Out(String::new()) } else { Opt::Sink },
}
}
//
// --- adding something to digests
//
pub fn field<D: Digestable>(&mut self, key: &str, value: D) {
value.digest(key, self);
}
pub fn command(&mut self, name: &str) {
write!(&mut self.sha, "COMMAND\0{}\0", name).unwrap();
write!(&mut self.debug, "----- Command {} -----\n", name).unwrap();
}
/// This only outputs if field is not None
///
/// This method may be used for adding fields which are None by default,
/// while maintaining backwards compatibility
pub fn opt_field<D: Digestable>(&mut self, key: &str, value: &Option<D>) {
if let Some(ref val) = *value {
self.field(key, val);
}
}
pub fn file(&mut self, name: &Path, reader: &mut dyn Read)
-> Result<(), io::Error>
{
io::copy(reader, &mut self.sha)?;
write!(&mut self.debug, "file {:?}\n", name).unwrap();
Ok(())
}
//
// --- End of digest-adding methods
//
pub fn print_debug_info(&self) {
match self.debug {
Opt::Out(ref x) => println!("{}", x),
Opt::Sink => {}, // unreachable?
}
}
pub fn dump_info(&self) {
match self.sha.data {
Opt::Out(ref x) => io::stdout().write_all(x).unwrap(),
Opt::Sink => {}, // unreachable?
}
}
}
impl<W: io::Write> io::Write for Opt<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
use self::Opt::*;
match *self {
Out(ref mut x) => x.write(buf),
Sink => Ok(buf.len())
}
}
fn flush(&mut self) -> io::Result<()> {
use self::Opt::*;
match *self {
Out(ref mut x) => x.flush(),
Sink => Ok(())
}
}
}
impl io::Write for DebugWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.data.write(buf)?;
self.sha.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.data.flush()?;
self.sha.flush()
}
}
impl<W: fmt::Write> fmt::Write for Opt<W> {
fn write_str(&mut self, str: &str) -> fmt::Result {
use self::Opt::*;
match *self {
Out(ref mut x) => x.write_str(str),
Sink => Ok(())
}
}
}
impl fmt::LowerHex for Digest {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
hexfmt(&self.sha.sha.clone().finalize_fixed(), f)
}
}
fn hexfmt(data: &[u8], f: &mut fmt::Formatter) -> fmt::Result {
assert!(data.len() <= 64);
let max_digits = f.precision().unwrap_or(data.len()*2);
let mut res = [0u8; 128];
for (i, c) in data.iter().take(max_digits/2+1).enumerate() {
res[i*2] = LOWER_CHARS[(c >> 4) as usize];
res[i*2+1] = LOWER_CHARS[(c & 0xF) as usize];
}
f.write_str(unsafe {
str::from_utf8_unchecked(&res[..max_digits])
})?;
Ok(())
}
impl<'a> fmt::LowerHex for ShowHex<'a, Sha256> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
hexfmt(&self.0.clone().finalize_fixed(), f)
}
}
impl<'a> fmt::LowerHex for ShowHex<'a, Blake2b> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
hexfmt(&self.0.clone().finalize_fixed(), f)
}
}
impl Digestable for String {
fn digest(&self, title: &str, dig: &mut Digest) {
display_field(self, title, dig)
}
}
impl Digestable for bool {
fn digest(&self, title: &str, dig: &mut Digest) {
display_field(self, title, dig)
}
}
impl<'a> Digestable for &'a str {
fn digest(&self, title: &str, dig: &mut Digest) {
display_field(self, title, dig)
}
}
impl Digestable for u32 {
fn digest(&self, title: &str, dig: &mut Digest) {
display_field(self, title, dig)
}
}
fn display_field<T: fmt::Display>(value: T, title: &str, dig: &mut Digest) {
write!(&mut dig.sha, "{}\0{}\0", title, value).unwrap();
write!(&mut dig.debug, "field {:?} {}\n", title, value).unwrap();
}
fn path_field<T: AsRef<Path>>(value: T, title: &str, dig: &mut Digest) {
write!(&mut dig.sha, "{}\0", title).unwrap();
dig.sha.write_all(value.as_ref().as_os_str().as_bytes()).unwrap();
dig.sha.write_all(&[0]).unwrap();
write!(&mut dig.debug,
"field:path {:?} {:?}\n", title, value.as_ref()).unwrap();
}
impl Digestable for serde_json::Value {
fn digest(&self, title: &str, dig: &mut Digest) {
write!(&mut dig.sha, "{}\0{}\0", title, self).unwrap();
write!(&mut dig.debug, "field:json {:?} {}\n", title, self).unwrap();
}
}
impl<'a> Digestable for &'a Path {
fn digest(&self, title: &str, dig: &mut Digest) {
path_field(self, title, dig)
}
}
impl<> Digestable for PathBuf {
fn digest(&self, title: &str, dig: &mut Digest) {
path_field(self, title, dig)
}
}
impl<'a> Digestable for &'a Vec<String> {
fn digest(&self, title: &str, dig: &mut Digest) {
write!(&mut dig.sha, "{}\0", title).unwrap();
for val in *self {
write!(&mut dig.sha, "{}\0", val).unwrap();
}
write!(&mut dig.debug, "field:list {:?} {:?}\n", title, self).unwrap();
}
}
impl<'a> Digestable for &'a Vec<PathBuf> {
fn digest(&self, title: &str, dig: &mut Digest) {
write!(&mut dig.sha, "{}\0", title).unwrap();
for val in *self {
dig.sha.write_all(val.as_os_str().as_bytes()).unwrap();
dig.sha.write_all(&[0]).unwrap();
}
write!(&mut dig.debug, "field:list {:?} {:?}\n", title, self).unwrap();
}
}
impl<'a> Digestable for &'a Vec<Range> {
fn digest(&self, title: &str, dig: &mut Digest) {
write!(&mut dig.sha, "{}\0", title).unwrap();
for val in *self {
write!(&mut dig.sha, "{}-{}\0", val.start(), val.end()).unwrap();
}
write!(&mut dig.debug, "field:list {:?} {:?}\n", title, self).unwrap();
}
}
impl<'a> Digestable for &'a Vec<u32> {
fn digest(&self, title: &str, dig: &mut Digest) {
write!(&mut dig.sha, "{}\0", title).unwrap();
for val in *self {
write!(&mut dig.sha, "{}\0", val).unwrap();
}
write!(&mut dig.debug, "field:list {:?} {:?}\n", title, self).unwrap();
}
}
impl<'a, T: Digestable> Digestable for &'a T {
fn digest(&self, title: &str, dig: &mut Digest) {
(*self).digest(title, dig)
}
}
/// Zero-copy formatting of hash value with or without precision
pub fn hex<T>(src: &T) -> ShowHex<T> {
ShowHex(&src)
}