TL;DR: Can I generate multiple cases of a switch expression at comptime based on a table/array?
I’m writing a simple string escaping function, which will expand particular characters from an input string into longer sequences. I’m currently doing this in two passes: first, I calculate the length of the output string. Then, I copy and expand as necessary.
This approach means I have to hardcode information about the special characters to be expanded in two different switch statements (in this example, it’s XML character entities):
for (source) |c| {
out_chars += switch (c) {
'<', '>' => 4,
'"' => 6,
'&' => 5,
else => 1,
};
}
for (source) |c| {
switch (c) {
'<' => { @memcpy(out[out_i..], "<"); out_i += 4; },
'>' => { @memcpy(out[out_i..], ">"); out_i += 4; },
'"' => { @memcpy(out[out_i..], """); out_i += 6; },
'&' => { @memcpy(out[out_i..], "&"); out_i += 5; },
else => { out[out_i] = c; out_i += 1; },
}
}
Is there any way I could write a single table defining the special characters and their resultant expansions, i.e.. .{ .{ ‘<‘, “<” }, .{ ‘>’, “>” }, … }, and generate both of the appropriate switch cases entirely at compile time? I’ve found a few mentions of ‘inline else’ while searching around for this, but I’m not sure I fully understand how it’s useful for this sort of case.