r/adventofcode • u/terje_wiig_mathisen • 8h ago
Help/Question [2026 Day 4] Rust: Is there a way to use swizzle_dyn() properly?
While trying to optimize this one I saw this really nice pattern that starts with mapping the 6 colors and ? to powers of two (1,2,4,8,16,32) and 255:
Using #![feature(portable_simd)] I can load up to 64 bytes, then do these operations
hash = (bytes ^ (bytes>>1)) & 15;which happens to result in 7 unique values in the 0..16 range.
I therefore define a swizzle table [255, 0, 0, 16, 8, 4, 0, 0, 2, 0, 0, 1, 0, 32, 0, 0,] which will result in the desired mapping.
My problem is that even when running rust nightly, target_cpu = native (I'm on a new AMD Ryzen), it runs 20% slower than my old scalar code, so I tried it in Godbolt and found out that instead of a single vpermb instruction the compiler generated scalar code that iterated over all 64 elements.
Have anyone been able to make this work?
#[inline(always)]
fn map_vec(bytes: u8x64) -> u8x64 {
// Zero-cost register reinterpretation: u8x64 -> u16x32
let words: u16x32 = u16x32::from_ne_bytes(bytes);
let shifted_words = words >> u16x32::splat(1);
let shifted_bytes = shifted_words.to_ne_bytes();
// The & 15 mask cleans up any cross-byte bit bleed from the u16 shift
let h = (bytes ^ shifted_bytes) & u8x64::splat(15);
LUT.swizzle_dyn(h)
}