Skip to content

Commit 24d46a0

Browse files
committed
auto merge of #9345 : Dretch/rust/digest-result-bytes, r=cmr
I would find this function useful.
2 parents af25f58 + b82e0d3 commit 24d46a0

File tree

2 files changed

+16
-14
lines changed

2 files changed

+16
-14
lines changed

src/libextra/crypto/cryptoutil.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,7 @@ mod test {
352352

353353
use cryptoutil::{add_bytes_to_bits, add_bytes_to_bits_tuple};
354354
use digest::Digest;
355+
use hex::FromHex;
355356

356357
/// Feed 1,000,000 'a's into the digest with varying input sizes and check that the result is
357358
/// correct.
@@ -372,8 +373,10 @@ mod test {
372373
}
373374

374375
let result_str = digest.result_str();
376+
let result_bytes = digest.result_bytes();
375377

376-
assert!(expected == result_str);
378+
assert_eq!(expected, result_str.as_slice());
379+
assert_eq!(expected.from_hex().unwrap(), result_bytes);
377380
}
378381

379382
// A normal addition - no overflow occurs

src/libextra/crypto/digest.rs

+12-13
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010

1111
use std::vec;
1212

13+
use hex::ToHex;
14+
1315

1416
/**
1517
* The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2
@@ -58,23 +60,20 @@ pub trait Digest {
5860

5961
/**
6062
* Convenience function that retrieves the result of a digest as a
61-
* ~str in hexadecimal format.
63+
* newly allocated vec of bytes.
6264
*/
63-
fn result_str(&mut self) -> ~str {
65+
fn result_bytes(&mut self) -> ~[u8] {
6466
let mut buf = vec::from_elem((self.output_bits()+7)/8, 0u8);
6567
self.result(buf);
66-
return to_hex(buf);
68+
buf
6769
}
68-
}
6970

70-
fn to_hex(rr: &[u8]) -> ~str {
71-
let mut s = ~"";
72-
for b in rr.iter() {
73-
let hex = (*b as uint).to_str_radix(16u);
74-
if hex.len() == 1 {
75-
s.push_char('0');
76-
}
77-
s.push_str(hex);
71+
/**
72+
* Convenience function that retrieves the result of a digest as a
73+
* ~str in hexadecimal format.
74+
*/
75+
fn result_str(&mut self) -> ~str {
76+
self.result_bytes().to_hex()
7877
}
79-
return s;
8078
}
79+

0 commit comments

Comments
 (0)