Skip to content

Instantly share code, notes, and snippets.

@Validark
Created November 14, 2023 13:04
Show Gist options
  • Save Validark/a45d57c18f290031cd41126ef142fe3e to your computer and use it in GitHub Desktop.
Save Validark/a45d57c18f290031cd41126ef142fe3e to your computer and use it in GitHub Desktop.
Pext zig
inline fn pext(src: anytype, mask: @TypeOf(src)) @TypeOf(src) {
switch (@TypeOf(src)) {
u32, u64 => {},
else => @compileError(std.fmt.comptimePrint("pext called with a bad type: {}\n", .{@TypeOf(src)})),
}
if (@inComptime()) {
@setEvalBranchQuota(std.math.maxInt(u32));
var result: @TypeOf(src) = 0;
var m = mask;
var i: std.math.Log2Int(@TypeOf(src)) = 0;
while (m > 0) : ({
m &= m -% 1;
i += 1;
}) {
result |= ((src >> @ctz(m)) & 1) << i;
}
return result;
}
return asm ("pext %[mask], %[src], %[ret]"
: [ret] "=r" (-> @TypeOf(src)),
: [src] "r" (src),
[mask] "r" (mask),
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment