legit-hamming 0.1.1

Exact Hamming radius search over 64-bit and 256-bit hashes in memory: a scan or multi-index hashing, chosen per query, checked against one reference, and a search service over snapshots
Documentation
//! The crate's error type.

use std::fmt;
use std::io;
use std::path::PathBuf;

/// 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.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    /// A record whose id isn't above the id before it: records are kept in rising id order.
    IdOrder {
        /// The id before.
        previous: u64,
        /// The id given.
        id: u64,
    },
    /// A record with an id pushed to a values-only set, or a bare value to a set of records.
    IdPresence {
        /// Whether the set holds ids.
        set_has_ids: bool,
    },
    /// Columns for a set that aren't one per word of the value, or that differ in length from
    /// each other or from the ids.
    Columns {
        /// The number of columns the value width needs.
        words: usize,
    },
    /// A set grown past the 2³² − 1 records a position can address.
    TooManyRecords,
    /// A chunk count for multi-index hashing that doesn't split the value into equal chunks of 1,
    /// 2, 4, 8 or 16 bits.
    ChunkCount {
        /// The count asked for.
        chunks: u32,
        /// The width of the values in bits.
        bits: u32,
    },
    /// An instruction set this CPU or build doesn't have.
    IsaUnavailable(&'static str),
    /// A hex value of the wrong length or with a character that isn't a hex digit.
    InvalidHex {
        /// The number of hex digits the width needs.
        expected: usize,
    },
    /// A multi-index plan forced on a [`Planned`](crate::Planned) set that has no tables.
    NoTables,
    /// A snapshot whose manifest, files or contents don't agree with each other or with the value
    /// width asked for.
    Snapshot {
        /// The file at fault.
        path: PathBuf,
        /// What's wrong with it.
        reason: String,
    },
    /// A snapshot part whose SHA-256 isn't the one its manifest records.
    Checksum {
        /// The part.
        path: PathBuf,
        /// The checksum the manifest records.
        expected: String,
        /// The checksum of the file.
        actual: String,
    },
    /// Memory the allocator wouldn't give: room for a snapshot's records, or for multi-index
    /// tables.
    OutOfMemory {
        /// What the memory was for.
        what: &'static str,
    },
    /// A file that couldn't be read or written.
    Io {
        /// The file.
        path: PathBuf,
        /// The error from the operating system.
        source: io::Error,
    },
}

impl Error {
    pub(crate) fn io(path: impl Into<PathBuf>, source: io::Error) -> Self {
        Self::Io {
            path: path.into(),
            source,
        }
    }

    pub(crate) fn snapshot(path: impl Into<PathBuf>, reason: impl Into<String>) -> Self {
        Self::Snapshot {
            path: path.into(),
            reason: reason.into(),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::IdOrder { previous, id } => {
                write!(
                    f,
                    "record id `{id}` isn't above the id before it, `{previous}`; records go in rising id order"
                )
            }
            Self::IdPresence { set_has_ids: true } => f.write_str("this set holds records with ids; give each an id"),
            Self::IdPresence { set_has_ids: false } => f.write_str("this set holds values only; give no ids"),
            Self::Columns { words } => {
                write!(
                    f,
                    "a set needs {words} value columns of one length, and ids of that length if any"
                )
            }
            Self::TooManyRecords => f.write_str("a set holds at most 4,294,967,295 records"),
            Self::ChunkCount { chunks, bits } => write!(
                f,
                "`{chunks}` chunks don't split {bits} bits into equal chunks of 1, 2, 4, 8 or 16 bits"
            ),
            Self::IsaUnavailable(name) => write!(f, "the `{name}` instructions aren't available on this CPU or build"),
            Self::InvalidHex { expected } => write!(f, "a value needs exactly {expected} hex digits"),
            Self::NoTables => f.write_str("there are no multi-index tables to probe; give them a larger memory budget"),
            Self::Snapshot { path, reason } => write!(f, "snapshot file `{}`: {reason}", path.display()),
            Self::Checksum { path, expected, actual } => write!(
                f,
                "snapshot part `{}` has SHA-256 `{actual}`, but the manifest records `{expected}`",
                path.display()
            ),
            Self::OutOfMemory { what } => write!(f, "couldn't set aside the memory for {what}"),
            Self::Io { path, source } => write!(f, "couldn't access `{}`: {source}", path.display()),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io { source, .. } => Some(source),
            _ => None,
        }
    }
}