Skip to content

Add a new Digest.result_bytes convenience function. #9345

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 25, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/libextra/crypto/cryptoutil.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
25 changes: 12 additions & 13 deletions src/libextra/crypto/digest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -58,23 +60,20 @@ pub trait Digest {

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

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);
/**
* Convenience function that retrieves the result of a digest as a
* ~str in hexadecimal format.
*/
fn result_str(&mut self) -> ~str {
self.result_bytes().to_hex()
}
return s;
}