use std::fmt;
use std::hash::Hasher;
use std::str::FromStr;
use siphasher::sip::SipHasher24;
use crate::{Algorithm, Error, Result};
const VALUES: usize = 128;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum SignatureAlgorithm {
MinHashV1,
MinHashLegacyV1,
}
impl SignatureAlgorithm {
pub const ALL: [Self; 2] = [Self::MinHashV1, Self::MinHashLegacyV1];
#[must_use]
pub const fn id(self) -> &'static str {
match self {
Self::MinHashV1 => "minhash-v1",
Self::MinHashLegacyV1 => "minhash-legacy-v1",
}
}
#[must_use]
pub const fn value_count(self) -> u32 {
match self {
Self::MinHashV1 | Self::MinHashLegacyV1 => 128,
}
}
pub fn from_id(id: &str) -> Result<Self> {
if let Some(algorithm) = Self::ALL.into_iter().find(|algorithm| algorithm.id() == id) {
return Ok(algorithm);
}
match Algorithm::ALL.into_iter().find(|algorithm| algorithm.id() == id) {
Some(algorithm) => Err(Error::NotASignature(algorithm)),
None => Err(Error::UnknownAlgorithm(id.to_owned())),
}
}
}
impl fmt::Display for SignatureAlgorithm {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.id())
}
}
impl FromStr for SignatureAlgorithm {
type Err = Error;
fn from_str(id: &str) -> Result<Self> {
Self::from_id(id)
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for SignatureAlgorithm {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
serializer.serialize_str(self.id())
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for SignatureAlgorithm {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
deserializer.deserialize_str(crate::serde_support::FromStrVisitor::new("a signature algorithm id"))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Signature {
algorithm: SignatureAlgorithm,
values: [u32; VALUES],
}
impl Signature {
pub(crate) const fn from_array(algorithm: SignatureAlgorithm, values: [u32; VALUES]) -> Self {
Self { algorithm, values }
}
#[must_use]
pub const fn algorithm(&self) -> SignatureAlgorithm {
self.algorithm
}
#[must_use]
pub fn values(&self) -> &[u32] {
&self.values
}
pub fn from_values(algorithm: SignatureAlgorithm, values: &[u32]) -> Result<Self> {
let values = <[u32; VALUES]>::try_from(values).map_err(|_| Error::SignatureLength {
algorithm,
expected: VALUES,
actual: values.len(),
})?;
Ok(Self::from_array(algorithm, values))
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.values.iter().all(|&value| value == u32::MAX)
}
#[must_use]
pub fn to_bytes(&self) -> Vec<u8> {
self.values.iter().flat_map(|value| value.to_be_bytes()).collect()
}
pub fn from_bytes(algorithm: SignatureAlgorithm, bytes: &[u8]) -> Result<Self> {
let (words, rest) = bytes.as_chunks::<4>();
if words.len() != VALUES || !rest.is_empty() {
return Err(Error::SignatureLength {
algorithm,
expected: VALUES * 4,
actual: bytes.len(),
});
}
let mut values = [0; VALUES];
for (value, word) in values.iter_mut().zip(words) {
*value = u32::from_be_bytes(*word);
}
Ok(Self::from_array(algorithm, values))
}
#[must_use]
pub fn to_hex(&self) -> String {
const DIGITS: &[u8; 16] = b"0123456789abcdef";
let mut hex = String::with_capacity(VALUES * 8);
for byte in self.to_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: SignatureAlgorithm, hex: &str) -> Result<Self> {
if hex.len() != VALUES * 8 {
return Err(Error::SignatureLength {
algorithm,
expected: VALUES * 8,
actual: hex.len(),
});
}
let digits = hex
.bytes()
.map(|digit| char::from(digit).to_digit(16).ok_or(Error::InvalidHex))
.collect::<Result<Vec<u32>>>()?;
let (groups, _) = digits.as_chunks::<8>();
let mut values = [0; VALUES];
for (value, group) in values.iter_mut().zip(groups) {
*value = group.iter().fold(0, |value, &digit| value << 4 | digit);
}
Ok(Self::from_array(algorithm, values))
}
pub fn matching(&self, other: &Self) -> Result<u32> {
self.check_same(other)?;
Ok(self
.values
.iter()
.zip(&other.values)
.map(|(left, right)| u32::from(left == right))
.sum())
}
pub fn similarity(&self, other: &Self) -> Result<f64> {
let matching = self.matching(other)?;
Ok(f64::from(matching) / f64::from(self.algorithm.value_count()))
}
pub fn union(&self, other: &Self) -> Result<Self> {
self.check_same(other)?;
let mut values = self.values;
for (value, &theirs) in values.iter_mut().zip(&other.values) {
*value = (*value).min(theirs);
}
Ok(Self::from_array(self.algorithm, values))
}
pub fn band_keys(&self, bands: u32) -> Result<Vec<u64>> {
let count = self.algorithm.value_count();
if !count.is_multiple_of(bands) {
return Err(Error::BandCount { bands, values: count });
}
let width = (count / bands) as usize;
let keys = self
.values
.chunks_exact(width)
.zip(0_u32..)
.map(|(band, index)| {
let mut bytes = Vec::with_capacity(4 + 4 * width);
bytes.extend_from_slice(&index.to_be_bytes());
for value in band {
bytes.extend_from_slice(&value.to_be_bytes());
}
let mut hasher = SipHasher24::new_with_keys(0, 0);
hasher.write(&bytes);
hasher.finish()
})
.collect();
Ok(keys)
}
pub fn band_keys_i64(&self, bands: u32) -> Result<Vec<i64>> {
Ok(self
.band_keys(bands)?
.into_iter()
.map(|key| i64::from_be_bytes(key.to_be_bytes()))
.collect())
}
fn check_same(&self, other: &Self) -> Result<()> {
if self.algorithm == other.algorithm {
Ok(())
} else {
Err(Error::SignatureMismatch {
left: self.algorithm,
right: other.algorithm,
})
}
}
}
impl fmt::Display for Signature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.algorithm, self.to_hex())
}
}
impl FromStr for Signature {
type Err = Error;
fn from_str(text: &str) -> Result<Self> {
let (id, hex) = text.split_once(':').ok_or(Error::MissingSeparator)?;
Self::from_hex(SignatureAlgorithm::from_id(id)?, hex)
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for Signature {
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 Signature {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
deserializer.deserialize_str(crate::serde_support::FromStrVisitor::new(
"a signature written `<algorithm>:<hex>`",
))
}
}