Skip to content
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

Hash 💅 #1923

Merged
merged 4 commits into from
Dec 12, 2020
Merged
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
28 changes: 22 additions & 6 deletions lib/cache/src/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ use std::string::ToString;
pub struct Hash([u8; 32]);

impl Hash {
/// Creates a new hash. Has to be encodable as a hex format.
/// Creates a new instance from 32 raw bytes.
/// Does not perform any hashing. In order to create a hash from data,
/// use `Hash::generate`.
pub fn new(bytes: [u8; 32]) -> Self {
Self(bytes)
}
Expand All @@ -20,18 +22,16 @@ impl Hash {
Self::new(hash.into())
}

pub(crate) fn into_array(self) -> [u8; 32] {
let mut total = [0u8; 32];
total[0..32].copy_from_slice(&self.0);
total
pub(crate) fn to_array(&self) -> [u8; 32] {
self.0
}
}

impl ToString for Hash {
/// Create the hexadecimal representation of the
/// stored hash.
fn to_string(&self) -> String {
hex::encode(&self.into_array() as &[u8])
hex::encode(&self.to_array())
}
}

Expand All @@ -56,3 +56,19 @@ impl FromStr for Hash {
})?))
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn hash_to_array_works() {
let original = [
0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x12, 0x65, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF,
0x12, 0x65, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x12, 0x65, 0xAA, 0xBB, 0xCC, 0xDD,
0xEE, 0xFF, 0x12, 0x65,
];
let hash = Hash::new(original);
assert_eq!(hash.to_array(), original);
}
}