legit-hashes 0.2.1

Versioned similarity hashes of images and text, and MinHash set signatures, with index keys for finding near matches
Documentation
//! The crate's error type.

use std::fmt;

use crate::{Algorithm, SignatureAlgorithm};

/// The result of a fallible operation in this crate.
pub type Result<T, E = Error> = std::result::Result<T, E>;

/// What went wrong. Every failure in this crate, bad input included, is one of these; nothing
/// panics.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
    /// An image or resize target with a width or height of 0.
    ZeroDimension {
        /// The width given.
        width: u32,
        /// The height given.
        height: u32,
    },
    /// An image or resize target wider or taller than [`MAX_DIMENSION`](crate::MAX_DIMENSION), or
    /// on a 32-bit target, one with more pixels than a buffer can hold.
    DimensionTooLarge {
        /// The width given.
        width: u32,
        /// The height given.
        height: u32,
    },
    /// A pixel buffer whose length doesn't match its width and height.
    BufferLength {
        /// The length the width, height and channel count call for.
        expected: usize,
        /// The length given.
        actual: usize,
    },
    /// Image hashing asked of an algorithm that hashes text.
    NotAnImageAlgorithm(Algorithm),
    /// Two hashes compared across algorithms or versions.
    AlgorithmMismatch {
        /// The algorithm of the hash compared from.
        left: Algorithm,
        /// The algorithm of the hash compared to.
        right: Algorithm,
    },
    /// An algorithm id that this version of the crate doesn't know.
    UnknownAlgorithm(String),
    /// A hash string without the `:` between the algorithm id and the hex.
    MissingSeparator,
    /// Hex or bytes of the wrong length for the algorithm.
    WrongLength {
        /// The algorithm the value was read for.
        algorithm: Algorithm,
        /// The length the algorithm needs, in hex digits or bytes as the input is.
        expected: usize,
        /// The length given.
        actual: usize,
    },
    /// A hex string with a character that isn't a hex digit.
    InvalidHex,
    /// An integer form asked of an algorithm whose hashes aren't 64 bits wide.
    NoIntegerForm {
        /// The algorithm of the hash.
        algorithm: Algorithm,
    },
    /// A chunk count outside `1..=bits`, or one that leaves a chunk wider than 64 bits.
    ChunkCount {
        /// The count asked for.
        count: u32,
        /// The width of the hash in bits.
        bits: u32,
    },
    /// A shingle size of 0.
    ShingleSize,
    /// The id of a signature algorithm, such as `minhash-v1`, read as a bit-hash algorithm.
    NotABitHash(SignatureAlgorithm),
    /// The id of a bit-hash algorithm, such as `simhash-v1`, read as a signature algorithm.
    NotASignature(Algorithm),
    /// Two signatures compared or combined across algorithms or versions.
    SignatureMismatch {
        /// The algorithm of the signature compared from.
        left: SignatureAlgorithm,
        /// The algorithm of the signature compared to.
        right: SignatureAlgorithm,
    },
    /// Hex, bytes or values of the wrong length for the signature algorithm.
    SignatureLength {
        /// The algorithm the signature was read for.
        algorithm: SignatureAlgorithm,
        /// The length the algorithm needs, in hex digits, bytes or values as the input is.
        expected: usize,
        /// The length given.
        actual: usize,
    },
    /// A band count that doesn't divide the signature's values into equal bands.
    BandCount {
        /// The count asked for.
        bands: u32,
        /// The number of values in the signature.
        values: u32,
    },
    /// An encoded image that couldn't be decoded, or that is over the decoder limits.
    #[cfg(feature = "image")]
    Decode(String),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ZeroDimension { width, height } => {
                write!(
                    f,
                    "`{width}x{height}` has a side of 0; width and height must be at least 1"
                )
            }
            Self::DimensionTooLarge { width, height } => write!(
                f,
                "`{width}x{height}` is too large; width and height must be at most `{}`",
                crate::MAX_DIMENSION
            ),
            Self::BufferLength { expected, actual } => {
                write!(
                    f,
                    "the pixel buffer holds `{actual}` bytes; its size calls for `{expected}`"
                )
            }
            Self::NotAnImageAlgorithm(algorithm) => write!(f, "`{algorithm}` hashes text, not images"),
            Self::AlgorithmMismatch { left, right } => {
                write!(
                    f,
                    "can't compare hashes of different algorithms, `{left}` and `{right}`"
                )
            }
            Self::UnknownAlgorithm(id) => write!(f, "`{id}` isn't a known hash algorithm"),
            Self::MissingSeparator => f.write_str("a hash is written `<algorithm>:<hex>`; the `:` is missing"),
            Self::WrongLength { algorithm, actual, .. } => write!(
                f,
                "`{algorithm}` hashes are `{}` hex digits or `{}` bytes long, not `{actual}`",
                algorithm.bits() / 4,
                algorithm.bits() / 8
            ),
            Self::InvalidHex => f.write_str("the hash holds a character that isn't a hex digit"),
            Self::NoIntegerForm { algorithm } => {
                write!(
                    f,
                    "`{algorithm}` hashes aren't 64 bits wide, so they have no integer form"
                )
            }
            Self::ChunkCount { count, bits } => write!(
                f,
                "can't split `{bits}` bits into `{count}` chunks; use {} to `{bits}`",
                bits.div_ceil(64)
            ),
            Self::ShingleSize => f.write_str("a shingle must be at least 1 character long"),
            Self::NotABitHash(algorithm) => {
                write!(
                    f,
                    "`{algorithm}` makes signatures, not bit hashes; read it as a `Signature`"
                )
            }
            Self::NotASignature(algorithm) => {
                write!(f, "`{algorithm}` makes bit hashes, not signatures; read it as a `Hash`")
            }
            Self::SignatureMismatch { left, right } => write!(
                f,
                "can't compare signatures of different algorithms, `{left}` and `{right}`"
            ),
            Self::SignatureLength { algorithm, actual, .. } => {
                let values = algorithm.value_count();
                write!(
                    f,
                    "`{algorithm}` signatures are `{}` hex digits, `{}` bytes or `{values}` values long, not `{actual}`",
                    values * 8,
                    values * 4
                )
            }
            Self::BandCount { bands, values } => write!(
                f,
                "can't split `{values}` values into `{bands}` equal bands; use a divisor of `{values}`"
            ),
            #[cfg(feature = "image")]
            Self::Decode(message) => write!(f, "couldn't decode the image: {message}"),
        }
    }
}

impl std::error::Error for Error {}