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
//! Which instruction sets the CPU has, and which code path a scan uses.

use std::fmt;

use crate::error::{Error, Result};
use crate::value::Value;

/// A code path for the distance kernels, named after the instructions it needs.
///
/// Every path returns exactly what [`Isa::Scalar`] returns; the test suite checks each path the CPU
/// running it has against the plain reference. [`Isa::best_for`] picks one for a width.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Isa {
    /// Portable Rust with no instruction set assumed beyond the build target's. Always available.
    Scalar,
    /// The x86-64 `popcnt` instruction, one 64-bit word at a time.
    Popcnt,
    /// x86-64 AVX2: four 64-bit words a step, counting bits with a nibble lookup table.
    Avx2,
    /// x86-64 AVX-512 F and BW without `VPOPCNTDQ`, as on Skylake-X and Cascade Lake servers: the
    /// AVX2 nibble lookup on 512-bit vectors, eight 64-bit words a step.
    Avx512Bw,
    /// x86-64 AVX-512 with `VPOPCNTDQ`: eight 64-bit words a step, counted by one instruction.
    Avx512,
    /// Arm NEON: two 64-bit words a vector, each counted on its own.
    Neon,
    /// Arm NEON, eight 64-bit values a step in four vectors, their counts narrowed into one vector
    /// and compared with the radius there, so only a step with a survivor leaves the vector unit.
    /// At 256 bits it runs the [`Isa::Neon`] kernel.
    NeonWide,
}

impl Isa {
    /// Every path, in order from the plainest to the widest, x86-64 first.
    pub const ALL: [Self; 7] = [
        Self::Scalar,
        Self::Popcnt,
        Self::Avx2,
        Self::Avx512Bw,
        Self::Avx512,
        Self::Neon,
        Self::NeonWide,
    ];

    /// The path's name, such as `avx512`.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Scalar => "scalar",
            Self::Popcnt => "popcnt",
            Self::Avx2 => "avx2",
            Self::Avx512Bw => "avx512bw",
            Self::Avx512 => "avx512",
            Self::Neon => "neon",
            Self::NeonWide => "neon-wide",
        }
    }

    /// The path named `name`, as [`name`](Self::name) gives it, whether or not this CPU has it.
    #[must_use]
    pub fn from_name(name: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|isa| isa.name() == name)
    }

    /// How the path counts bits, so a benchmark result can be traced to the code behind it.
    #[must_use]
    pub const fn technique(self) -> &'static str {
        match self {
            Self::Scalar => "count_ones per word as the build target compiles it, four records unrolled",
            Self::Popcnt => "hardware popcnt per word, four records unrolled",
            Self::Avx2 => {
                "nibble lookup with vpshufb and vpsadbw per 64-bit lane (Mula, Kurz and Lemire 2018), \
                 four records a vector"
            }
            Self::Avx512Bw => {
                "nibble lookup with 512-bit vpshufb and vpsadbw per 64-bit lane, a compare to a mask, \
                 eight records a vector"
            }
            Self::Avx512 => "vpopcntq per 64-bit lane and a compare to a mask, eight records a vector",
            Self::Neon => "vcntq_u8 and pairwise widening adds per 64-bit lane, two records a vector",
            Self::NeonWide => {
                "vcntq_u8 on four vectors, pairwise adds narrowing eight records' counts into one \
                 vector, compared with the radius there; the neon kernel at 256 bits"
            }
        }
    }

    /// Whether this CPU, and this build, can run the path. Checked at run time.
    #[must_use]
    pub fn is_available(self) -> bool {
        match self {
            Self::Scalar => true,
            #[cfg(target_arch = "x86_64")]
            Self::Popcnt => std::arch::is_x86_feature_detected!("popcnt"),
            #[cfg(target_arch = "x86_64")]
            Self::Avx2 => std::arch::is_x86_feature_detected!("avx2") && std::arch::is_x86_feature_detected!("popcnt"),
            #[cfg(target_arch = "x86_64")]
            Self::Avx512Bw => {
                std::arch::is_x86_feature_detected!("avx512f")
                    && std::arch::is_x86_feature_detected!("avx512bw")
                    && std::arch::is_x86_feature_detected!("popcnt")
            }
            #[cfg(target_arch = "x86_64")]
            Self::Avx512 => {
                std::arch::is_x86_feature_detected!("avx512f")
                    && std::arch::is_x86_feature_detected!("avx512vpopcntdq")
                    && std::arch::is_x86_feature_detected!("popcnt")
            }
            #[cfg(target_arch = "aarch64")]
            Self::Neon | Self::NeonWide => std::arch::is_aarch64_feature_detected!("neon"),
            #[allow(unreachable_patterns, reason = "which arms remain depends on the target")]
            _ => false,
        }
    }

    /// The paths this CPU can run, plainest first.
    #[must_use]
    pub fn available() -> Vec<Self> {
        Self::ALL.into_iter().filter(|isa| isa.is_available()).collect()
    }

    /// The fastest path this CPU can run for values of type `V`, by what was measured on each kind
    /// of CPU (the crate's README has the numbers).
    ///
    /// On x86-64, at either width: AVX-512 with `VPOPCNTDQ`, then AVX-512 BW, then AVX2, then
    /// `popcnt`, then [`Isa::Scalar`]. On `aarch64`, where NEON is detected, the answer depends on
    /// the width: at 256 bits [`Isa::Neon`], which ran 1.6 times the scalar code on an Apple M2 Pro;
    /// at 64 bits [`Isa::NeonWide`], which ran 1.4 to 1.6 times the scalar code on the same CPU on
    /// every workload measured. The [`Isa::Neon`] kernel at 64 bits ran 0.68 times the scalar
    /// code there, and stays selectable by name for comparison.
    #[must_use]
    pub fn best_for<V: Value>() -> Self {
        let order: &[Self] = if cfg!(target_arch = "aarch64") {
            if V::BITS == 64 {
                &[Self::NeonWide]
            } else {
                &[Self::Neon]
            }
        } else {
            &[Self::Avx512, Self::Avx512Bw, Self::Avx2, Self::Popcnt]
        };
        order
            .iter()
            .copied()
            .find(|isa| isa.is_available())
            .unwrap_or(Self::Scalar)
    }

    /// Return the path if this CPU can run it.
    ///
    /// # Errors
    ///
    /// [`Error::IsaUnavailable`] if it can't.
    pub fn require(self) -> Result<Self> {
        if self.is_available() {
            Ok(self)
        } else {
            Err(Error::IsaUnavailable(self.name()))
        }
    }
}

impl fmt::Display for Isa {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

/// What the running machine offers, for a report or a benchmark record.
///
/// ```
/// let cpu = legit_hamming::Cpu::detect();
/// assert!(cpu.paths.contains(&cpu.best64) && cpu.paths.contains(&cpu.best256));
/// println!("{} with {:?}: {} at 64 bits, {} at 256", cpu.arch, cpu.features, cpu.best64, cpu.best256);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Cpu {
    /// The architecture the crate was built for, such as `x86_64`.
    pub arch: &'static str,
    /// The instruction-set extensions that matter to this crate and that the CPU reports, by
    /// their `is_x86_feature_detected!` or `is_aarch64_feature_detected!` names, such as
    /// `avx512vpopcntdq`.
    pub features: Vec<&'static str>,
    /// The paths this CPU can run.
    pub paths: Vec<Isa>,
    /// The path [`Isa::best_for`] chooses for 64-bit values.
    pub best64: Isa,
    /// The path [`Isa::best_for`] chooses for 256-bit values.
    pub best256: Isa,
    /// The threads the operating system lets this process run at once, or 1 if it won't say.
    pub threads: usize,
}

impl Cpu {
    /// Detect the running CPU.
    #[must_use]
    pub fn detect() -> Self {
        Self {
            arch: std::env::consts::ARCH,
            features: features(),
            paths: Isa::available(),
            best64: Isa::best_for::<u64>(),
            best256: Isa::best_for::<[u64; 4]>(),
            threads: std::thread::available_parallelism().map_or(1, usize::from),
        }
    }
}

#[cfg(target_arch = "x86_64")]
fn features() -> Vec<&'static str> {
    use std::arch::is_x86_feature_detected as has;

    let mut found = Vec::new();
    for (name, present) in [
        ("popcnt", has!("popcnt")),
        ("bmi2", has!("bmi2")),
        ("avx2", has!("avx2")),
        ("avx512f", has!("avx512f")),
        ("avx512bw", has!("avx512bw")),
        ("avx512vl", has!("avx512vl")),
        ("avx512vpopcntdq", has!("avx512vpopcntdq")),
        ("avx512bitalg", has!("avx512bitalg")),
    ] {
        if present {
            found.push(name);
        }
    }
    found
}

#[cfg(target_arch = "aarch64")]
fn features() -> Vec<&'static str> {
    use std::arch::is_aarch64_feature_detected as has;

    let mut found = Vec::new();
    for (name, present) in [("neon", has!("neon")), ("sve", has!("sve")), ("sve2", has!("sve2"))] {
        if present {
            found.push(name);
        }
    }
    found
}

#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
fn features() -> Vec<&'static str> {
    Vec::new()
}