fixed-hashmap 0.1.0

A fixed-capacity, allocation-free hashmap for fixed-size byte keys and values
Documentation
pub(super) const LANES: usize = 16;

#[cfg(target_arch = "x86_64")]
#[inline]
pub(super) fn tag_masks(tags: &[u8], sought: u8) -> (u32, u32) {
    use core::arch::x86_64::{_mm_cmpeq_epi8, _mm_loadu_si128, _mm_movemask_epi8, _mm_set1_epi8};

    // x86-64 guarantees SSE2, and callers pass at least 16 valid tag bytes.
    unsafe {
        let values = _mm_loadu_si128(tags.as_ptr().cast());
        let wanted = _mm_set1_epi8(sought as i8);
        let empty = _mm_set1_epi8(0);
        let matches = _mm_cmpeq_epi8(values, wanted);
        let vacancies = _mm_cmpeq_epi8(values, empty);
        (
            _mm_movemask_epi8(matches) as u32,
            _mm_movemask_epi8(vacancies) as u32,
        )
    }
}

#[cfg(target_arch = "aarch64")]
#[inline]
pub(super) fn tag_masks(tags: &[u8], sought: u8) -> (u32, u32) {
    use core::arch::aarch64::{vceqq_u8, vdupq_n_u8, vld1q_u8, vst1q_u8};

    // AArch64 guarantees Advanced SIMD, and callers pass at least 16 valid tags.
    unsafe {
        let values = vld1q_u8(tags.as_ptr());
        let matches = vceqq_u8(values, vdupq_n_u8(sought));
        let vacancies = vceqq_u8(values, vdupq_n_u8(0));
        let mut match_lanes = [0; LANES];
        let mut vacancy_lanes = [0; LANES];
        vst1q_u8(match_lanes.as_mut_ptr(), matches);
        vst1q_u8(vacancy_lanes.as_mut_ptr(), vacancies);

        let mut match_mask = 0;
        let mut vacancy_mask = 0;
        for lane in 0..LANES {
            match_mask |= u32::from(match_lanes[lane] != 0) << lane;
            vacancy_mask |= u32::from(vacancy_lanes[lane] != 0) << lane;
        }
        (match_mask, vacancy_mask)
    }
}

#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
#[inline]
pub(super) fn tag_masks(tags: &[u8], sought: u8) -> (u32, u32) {
    let mut match_mask = 0;
    let mut vacancy_mask = 0;
    for (lane, tag) in tags.iter().take(LANES).enumerate() {
        match_mask |= u32::from(*tag == sought) << lane;
        vacancy_mask |= u32::from(*tag == 0) << lane;
    }
    (match_mask, vacancy_mask)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn finds_matching_and_empty_tags() {
        let tags = [1, 2, 0, 3, 0, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
        let (matches, vacancies) = tag_masks(&tags, 2);
        assert_eq!(matches, (1 << 1) | (1 << 5));
        assert_eq!(vacancies, (1 << 2) | (1 << 4));
    }
}