merkle-dag/src/hash.rs

38 lines
1.4 KiB
Rust
Raw Normal View History

2022-08-01 20:48:59 -04:00
// Copyright 2022 Jeremy Wall (Jeremy@marzhilsltudios.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2022-08-06 20:16:08 -04:00
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
/// Utility Trait to specify the hashing algorithm and provide a common
/// interface for that algorithm to provide. This interface is expected to
/// be stateful.
2022-08-24 10:00:08 -04:00
pub trait HashWriter: Default {
/// Record bytes from an iterator into our hash algorithm.
2022-08-01 20:48:59 -04:00
fn record<I: Iterator<Item = u8>>(&mut self, bs: I);
/// Provide the current hash value based on the bytes that have so far been recorded.
2022-08-24 10:00:08 -04:00
fn hash(&self) -> Vec<u8>;
}
2022-08-24 10:00:08 -04:00
impl HashWriter for DefaultHasher {
fn record<I: Iterator<Item = u8>>(&mut self, iter: I) {
let bytes = iter.collect::<Vec<u8>>();
self.write(bytes.as_slice());
}
2022-08-24 10:00:08 -04:00
fn hash(&self) -> Vec<u8> {
self.finish().to_le_bytes().to_vec()
}
2022-08-01 20:48:59 -04:00
}