use std::fmt;
use std::str::FromStr;
use crate::{Algorithm, Error, Result};
const MAX_BYTES: usize = 32;
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Hash {
algorithm: Algorithm,
bytes: [u8; MAX_BYTES],
}
impl Hash {
pub(crate) const fn from_bits(algorithm: Algorithm, bits: u64) -> Self {
let mut bytes = [0; MAX_BYTES];
let be = bits.to_be_bytes();
let mut index = 0;
while index < be.len() {
bytes[index] = be[index];
index += 1;
}
Self { algorithm, bytes }
}
pub(crate) const fn from_wide(algorithm: Algorithm, bytes: [u8; MAX_BYTES]) -> Self {
Self { algorithm, bytes }
}
#[must_use]
pub const fn algorithm(&self) -> Algorithm {
self.algorithm
}
#[must_use]
pub const fn bits(&self) -> u32 {
self.algorithm.bits()
}
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
&self.bytes[..self.byte_len()]
}
pub fn from_bytes(algorithm: Algorithm, bytes: &[u8]) -> Result<Self> {
let mut hash = Self {
algorithm,
bytes: [0; MAX_BYTES],
};
let expected = hash.byte_len();
if bytes.len() != expected {
return Err(Error::WrongLength {
algorithm,
expected,
actual: bytes.len(),
});
}
hash.bytes[..expected].copy_from_slice(bytes);
Ok(hash)
}
#[must_use]
pub fn to_hex(&self) -> String {
const DIGITS: &[u8; 16] = b"0123456789abcdef";
let mut hex = String::with_capacity(self.byte_len() * 2);
for &byte in self.as_bytes() {
hex.push(char::from(DIGITS[usize::from(byte >> 4)]));
hex.push(char::from(DIGITS[usize::from(byte & 0x0f)]));
}
hex
}
pub fn from_hex(algorithm: Algorithm, hex: &str) -> Result<Self> {
let expected = algorithm.bits() as usize / 4;
if hex.len() != expected {
return Err(Error::WrongLength {
algorithm,
expected,
actual: hex.len(),
});
}
let digits = hex
.bytes()
.map(|digit| char::from(digit).to_digit(16).ok_or(Error::InvalidHex))
.collect::<Result<Vec<u32>>>()?;
let (pairs, _) = digits.as_chunks::<2>();
let bytes: Vec<u8> = pairs.iter().map(|&[high, low]| (high << 4 | low) as u8).collect();
Self::from_bytes(algorithm, &bytes)
}
pub fn to_u64(&self) -> Result<u64> {
if self.bits() != 64 {
return Err(Error::NoIntegerForm {
algorithm: self.algorithm,
});
}
let [b0, b1, b2, b3, b4, b5, b6, b7, ..] = self.bytes;
Ok(u64::from_be_bytes([b0, b1, b2, b3, b4, b5, b6, b7]))
}
pub fn to_i64(&self) -> Result<i64> {
Ok(i64::from_be_bytes(self.to_u64()?.to_be_bytes()))
}
pub fn from_u64(algorithm: Algorithm, value: u64) -> Result<Self> {
if algorithm.bits() != 64 {
return Err(Error::NoIntegerForm { algorithm });
}
Ok(Self::from_bits(algorithm, value))
}
pub fn from_i64(algorithm: Algorithm, value: i64) -> Result<Self> {
Self::from_u64(algorithm, u64::from_be_bytes(value.to_be_bytes()))
}
pub fn distance(&self, other: &Self) -> Result<u32> {
if self.algorithm != other.algorithm {
return Err(Error::AlgorithmMismatch {
left: self.algorithm,
right: other.algorithm,
});
}
Ok(self
.as_bytes()
.iter()
.zip(other.as_bytes())
.map(|(left, right)| (left ^ right).count_ones())
.sum())
}
pub fn similarity(&self, other: &Self) -> Result<f64> {
let distance = self.distance(other)?;
Ok(1.0 - f64::from(distance) / f64::from(self.bits()))
}
pub fn chunks(&self, count: u32) -> Result<Vec<u64>> {
let bits = self.bits();
if count < bits.div_ceil(64) || count > bits {
return Err(Error::ChunkCount { count, bits });
}
let mut keys = Vec::with_capacity(count as usize);
let mut position = 0;
for index in 0..count {
let width = bits / count + u32::from(index < bits % count);
let key = (position..position + width).fold(0_u64, |key, bit| key << 1 | u64::from(self.bit(bit)));
keys.push(key);
position += width;
}
Ok(keys)
}
fn bit(&self, index: u32) -> bool {
let byte = self.bytes[(index / 8) as usize];
byte >> (7 - index % 8) & 1 == 1
}
fn byte_len(&self) -> usize {
self.bits() as usize / 8
}
}
impl fmt::Debug for Hash {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Hash")
.field("algorithm", &self.algorithm)
.field("bytes", &self.as_bytes())
.finish()
}
}
impl fmt::Display for Hash {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.algorithm, self.to_hex())
}
}
impl FromStr for Hash {
type Err = Error;
fn from_str(text: &str) -> Result<Self> {
let (id, hex) = text.split_once(':').ok_or(Error::MissingSeparator)?;
Self::from_hex(Algorithm::from_id(id)?, hex)
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for Hash {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Hash {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
deserializer.deserialize_str(crate::serde_support::FromStrVisitor::new(
"a hash written `<algorithm>:<hex>`",
))
}
}