Expand description
§simd-popcnt
Count the number of 1 bits (bit population count, a.k.a. Hamming weight) in
an array as quickly as possible using specialized CPU instructions: POPCNT,
AVX2 and AVX512 on x86/x86-64, and NEON and SVE on AArch64. The fastest
instruction set the CPU supports is detected once at runtime and cached; on
every other architecture the count falls back to u64::count_ones, which
the compiler lowers to a hardware popcount instruction wherever one exists.
The crate is portable by default and thread-safe. It has no external crate
dependencies and needs the Rust standard library only for runtime SIMD
dispatch (CPU feature detection); it is otherwise no_std.
This is an AI-assisted Rust port of the libpopcnt C/C++ library.
§Usage
popcnt counts the 1 bits in a byte slice; the PopcntExt trait adds a
.popcnt() method to slices, arrays and Vecs of every built-in integer
type.
use simd_popcnt::{popcnt, PopcntExt};
assert_eq!(popcnt(&[0xFF, 0x0F]), 12);
assert_eq!([u64::MAX, 0x0F0F_0F0F_0F0F_0F0F].popcnt(), 96);§Performance
For the fastest possible code, compile with RUSTFLAGS="-C target-cpu=native".
This selects the best SIMD path at compile time and removes the runtime
dispatch entirely.
Traits§
- Popcnt
Ext - Adds a
popcntmethod to slices of the built-in integer types, counting their bits without a manual byte cast. Implemented for slices, arrays andVecs ofu8/u16/u32/u64/u128/usizeand their signed counterparts; bring it into scope withuse simd_popcnt::PopcntExt;.
Functions§
- popcnt
- Counts the number of one bits (population count) in
bytes.