Inline switch prong

I have this function

/// Return true if character is a separator (not a word character).
pub fn isSeparator(c: u8) bool {
    return switch (c) {
        ' ', '\t' => true,
        '0'...'9', 'a'...'z', 'A'...'Z', '_' => false,
        else => true,
    };
}

I want to prioritize whitespace. Does this make any sense?

/// Return true if character is a separator (not a word character).
pub fn isSeparator(c: u8) bool {
    return switch (c) {
        inline ' ', '\t' => true,
        '0'...'9', 'a'...'z', 'A'...'Z', '_' => false,
        else => true,
    };
}

or is this better?

/// Return true if character is a separator (not a word character).
pub fn isSeparator(c: u8) bool {
    if (c == ' ' or c == '\t') return true;
    return switch (c) {
        '0'...'9', 'a'...'z', 'A'...'Z', '_' => false,
        else => true,
    };
}

What’s a possible application of inline in switch prongs? That is, in which case are they useful/make sense?

In your case, it probably doesn’t have much if any effect on the generated machine code.

Inline prongs are most used to turn a runtime value into a comptime one, either for when you need to do some meta-programming on it, or you want to guarantee you get branches optimised for the given values.

But is form 1 enough for the compiler to understand that I want to prioritize whitespace? Or I must use form 3? Are prongs evaluated in the same order I write them?

The order doesn’t matter because you can’t have more than one prong for a value, even when inside of ranges.

Its just preference

Thanks, then I think I’ll go with 3.

Well now I have to point out my preference is :stuck_out_tongue:

/// Return true if character is a separator (not a word character).
pub fn isSeparator(c: u8) bool {
    return switch (c) {
        '0'...'9', 'a'...'z', 'A'...'Z', '_' => false,
        else => true,
    };
}

Regardless, they will probably result in the exact same machine code.

3 Likes