|
| 1 | +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT |
| 2 | +// file at the top-level directory of this distribution and at |
| 3 | +// http://rust-lang.org/COPYRIGHT. |
| 4 | +// |
| 5 | +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 7 | +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 8 | +// option. This file may not be copied, modified, or distributed |
| 9 | +// except according to those terms. |
| 10 | + |
| 11 | +use core::prelude::*; |
| 12 | + |
| 13 | +use core::uint; |
| 14 | +use core::vec; |
| 15 | + |
| 16 | +/** |
| 17 | + * The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2 |
| 18 | + * family of digest functions. |
| 19 | + */ |
| 20 | +pub trait Digest { |
| 21 | + /** |
| 22 | + * Provide message data. |
| 23 | + * |
| 24 | + * # Arguments |
| 25 | + * |
| 26 | + * * input - A vector of message data |
| 27 | + */ |
| 28 | + fn input(&mut self, input: &[u8]); |
| 29 | + |
| 30 | + /** |
| 31 | + * Retrieve the digest result. This method may be called multiple times. |
| 32 | + */ |
| 33 | + fn result(&mut self, out: &mut [u8]); |
| 34 | + |
| 35 | + /** |
| 36 | + * Reset the digest. This method must be called after result() and before supplying more |
| 37 | + * data. |
| 38 | + */ |
| 39 | + fn reset(&mut self); |
| 40 | + |
| 41 | + /** |
| 42 | + * Get the output size in bits. |
| 43 | + */ |
| 44 | + fn output_bits(&self) -> uint; |
| 45 | +} |
| 46 | + |
| 47 | +fn to_hex(rr: &[u8]) -> ~str { |
| 48 | + let mut s = ~""; |
| 49 | + for rr.iter().advance() |b| { |
| 50 | + let hex = uint::to_str_radix(*b as uint, 16u); |
| 51 | + if hex.len() == 1 { |
| 52 | + s += "0"; |
| 53 | + } |
| 54 | + s += hex; |
| 55 | + } |
| 56 | + return s; |
| 57 | +} |
| 58 | + |
| 59 | +/// Contains utility methods for Digests. |
| 60 | +/// FIXME: #7339: Convert to default methods when issues with them are resolved. |
| 61 | +pub trait DigestUtil { |
| 62 | + /** |
| 63 | + * Convenience functon that feeds a string into a digest |
| 64 | + * |
| 65 | + * # Arguments |
| 66 | + * |
| 67 | + * * in The string to feed into the digest |
| 68 | + */ |
| 69 | + fn input_str(&mut self, in: &str); |
| 70 | + |
| 71 | + /** |
| 72 | + * Convenience functon that retrieves the result of a digest as a |
| 73 | + * ~str in hexadecimal format. |
| 74 | + */ |
| 75 | + fn result_str(&mut self) -> ~str; |
| 76 | +} |
| 77 | + |
| 78 | +impl<D: Digest> DigestUtil for D { |
| 79 | + fn input_str(&mut self, in: &str) { |
| 80 | + self.input(in.as_bytes()); |
| 81 | + } |
| 82 | + |
| 83 | + fn result_str(&mut self) -> ~str { |
| 84 | + let mut buf = vec::from_elem((self.output_bits()+7)/8, 0u8); |
| 85 | + self.result(buf); |
| 86 | + return to_hex(buf); |
| 87 | + } |
| 88 | +} |
0 commit comments