4 ms·
Rust's output[0] is basically the same as Zig in this case. The unsafe is needed here because it's calling extern functions. However, in this specific instance
by Measter 6y ago
Rust's output[0] is basically the same as Zig in this case. The unsafe is needed here because it's calling extern functions.
However, in this specific instance at least, this isn't as optimal as it could be. What this is basically doing is creating a jump table to find out which branch it should go down. But, because all the functions have the same signature, and each branch does the same thing, what it could have done instead is create a jump table for the function to call. At that point, all it would need to do is use the Inst's discriminant to index into the jump table.
I'm not sure what it would look like in Zig, but it's not that hard to get that from Rust[1]. The drawback of doing it this way is that it now comes with the maintenance overhead of ensuring the order and length of the jump table exactly matches the enum, otherwise you get the wrong function being called, or an out-of-bounds panic. You also need to explicitly handle the End variant anyway because the called function can't return for its parent.
I don't know Zig, but from what I understand it has some pretty nice code generation, so maybe that could help with keeping the array and enum in step here?
[0] https://godbolt.org/z/sa6fGq https://godbolt.org/z/sa6fGq
[1] https://godbolt.org/z/P3cj31 https://godbolt.org/z/P3cj31