Add a new Digest.result_bytes convenience function.

This commit is contained in:
Gareth Smith 2013-09-20 00:05:27 +01:00
parent d2b0b11aeb
commit b82e0d32ce
2 changed files with 17 additions and 15 deletions

View File

@ -353,6 +353,7 @@ mod test {
use cryptoutil::{add_bytes_to_bits, add_bytes_to_bits_tuple};
use digest::Digest;
use hex::FromHex;
/// Feed 1,000,000 'a's into the digest with varying input sizes and check that the result is
/// correct.
@ -373,8 +374,10 @@ mod test {
}
let result_str = digest.result_str();
let result_bytes = digest.result_bytes();
assert!(expected == result_str);
assert_eq!(expected, result_str.as_slice());
assert_eq!(expected.from_hex().unwrap(), result_bytes);
}
// A normal addition - no overflow occurs

View File

@ -10,6 +10,8 @@
use std::vec;
use hex::ToHex;
/**
* The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2
@ -56,25 +58,22 @@ pub trait Digest {
self.input(input.as_bytes());
}
/**
* Convenience function that retrieves the result of a digest as a
* newly allocated vec of bytes.
*/
fn result_bytes(&mut self) -> ~[u8] {
let mut buf = vec::from_elem((self.output_bits()+7)/8, 0u8);
self.result(buf);
buf
}
/**
* Convenience function that retrieves the result of a digest as a
* ~str in hexadecimal format.
*/
fn result_str(&mut self) -> ~str {
let mut buf = vec::from_elem((self.output_bits()+7)/8, 0u8);
self.result(buf);
return to_hex(buf);
self.result_bytes().to_hex()
}
}
fn to_hex(rr: &[u8]) -> ~str {
let mut s = ~"";
for b in rr.iter() {
let hex = (*b as uint).to_str_radix(16u);
if hex.len() == 1 {
s.push_char('0');
}
s.push_str(hex);
}
return s;
}