blob: 283201a008b00811770bc4b5db9e96be484684b8 [file] [log] [blame]
// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use super::api;
use fuchsia_merkle::Hash as FuchsiaMerkleHash;
use std::fmt;
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub(crate) struct Hash(FuchsiaMerkleHash);
#[cfg(test)]
impl Hash {
/// Constructs a [`Hash`] that represents the contents read from `contents`.
pub fn from_contents<R: std::io::Read>(contents: R) -> Self {
Self(
fuchsia_merkle::MerkleTree::from_reader(contents)
.expect("compute fuchsia merkle tree")
.root(),
)
}
}
impl From<FuchsiaMerkleHash> for Hash {
fn from(fuchsia_merkle_hash: FuchsiaMerkleHash) -> Self {
Self(fuchsia_merkle_hash)
}
}
impl Into<FuchsiaMerkleHash> for Hash {
fn into(self) -> FuchsiaMerkleHash {
self.0
}
}
impl fmt::Display for Hash {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl api::AsBytes for Hash {
/// A Fuchsia merkle root hash as bytes is the bytes of the hash digest, as exposed by
/// `fuchsia_merkle::Hash::as_bytes`.
fn as_bytes(&self) -> &[u8] {
self.0.as_bytes()
}
}
#[cfg(test)]
mod tests {
use super::Hash;
#[fuchsia::test]
fn test_hex_merkle_root_fmt() {
let contents = "hello_world";
let hash = Hash::from_contents(contents.as_bytes());
let merkle_root = fuchsia_merkle::from_slice(contents.as_bytes()).root();
assert_eq!(format!("{}", hash), format!("{}", merkle_root));
}
#[fuchsia::test]
fn test_equality() {
let hello1 = Hash::from_contents("hello".as_bytes());
let hello2 = Hash::from_contents("hello".as_bytes());
let goodbye = Hash::from_contents("goodbye".as_bytes());
assert_eq!(hello1, hello2);
assert_ne!(hello1, goodbye)
}
}