]> git.lizzy.rs Git - rust.git/commitdiff
auto merge of #9345 : Dretch/rust/digest-result-bytes, r=cmr
authorbors <bors@rust-lang.org>
Wed, 25 Sep 2013 21:25:52 +0000 (14:25 -0700)
committerbors <bors@rust-lang.org>
Wed, 25 Sep 2013 21:25:52 +0000 (14:25 -0700)
I would find this function useful.

src/libextra/crypto/cryptoutil.rs
src/libextra/crypto/digest.rs

index 4eba3e13eea5985e3978bc190cd89c733bb1d5bf..3573bb55948f109b7f77df587572853b0fc17e74 100644 (file)
@@ -352,6 +352,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.
@@ -372,8 +373,10 @@ pub fn test_digest_1million_random<D: Digest>(digest: &mut D, blocksize: uint, e
         }
 
         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
index d2d6b540cff4cf50bc6b10f67974776823e02d28..85c256c47a3805c9728d2fb7bf22a8a684dd0d9a 100644 (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
@@ -58,23 +60,20 @@ fn input_str(&mut self, input: &str) {
 
     /**
      * 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;
 }
+