Created
November 14, 2023 13:04
-
-
Save Validark/a45d57c18f290031cd41126ef142fe3e to your computer and use it in GitHub Desktop.
Pext zig
This file contains 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
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