Last active
August 12, 2025 07:31
-
-
Save lalinsky/26e449023f936f538402b2ed3b7217d1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const V = @Vector(16, u8); | |
// Safe version that handles bounds checking properly | |
export fn shuffle_safe(x: V, m: V) V { | |
var r: V = undefined; | |
inline for (0..16) |i| { | |
if (m[i] >= 16) { | |
r[i] = 0; | |
} else { | |
r[i] = x[m[i]]; | |
} | |
} | |
return r; | |
} | |
// Unsafe version that relies on compiler optimization to vpshufb | |
// Only safe when compiled with -OReleaseFast and appropriate target | |
export fn shuffle_unsafe(x: V, m: V) V { | |
var r: V = undefined; | |
inline for (0..16) |i| { | |
r[i] = x[m[i]]; | |
} | |
return r; | |
} | |
export fn test_safe(data_ptr: *V, mask_ptr: *V, result_ptr: *V) void { | |
const data = data_ptr.*; | |
const mask = mask_ptr.*; | |
const result = shuffle_safe(data, mask); | |
result_ptr.* = result; | |
} | |
export fn test_unsafe(data_ptr: *V, mask_ptr: *V, result_ptr: *V) void { | |
const data = data_ptr.*; | |
const mask = mask_ptr.*; | |
const result = shuffle_unsafe(data, mask); | |
result_ptr.* = result; | |
} | |
const std = @import("std"); | |
pub fn main() void { | |
var data: V = .{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; | |
var mask: V = .{ 15, 14, 13, 12, 0xFF, 0xFF, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; | |
var result_safe: V = undefined; | |
var result_unsafe: V = undefined; | |
test_safe(&data, &mask, &result_safe); | |
test_unsafe(&data, &mask, &result_unsafe); | |
std.debug.print("Data: {any}\n", .{data}); | |
std.debug.print("Mask: {any}\n", .{mask}); | |
std.debug.print("Safe: {any}\n", .{result_safe}); | |
std.debug.print("Unsafe: {any}\n", .{result_unsafe}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment