#u8 with subscript operator

1 messages · Page 1 of 1 (latest)

sacred shore
#

Hello!
I was writing a parser that needs to validate a set of ascii characters. I originally want the switch route, but I quickly moved to a lookup table.

As a sanity check, I went to compiler explorer to check the generated ASM, and surprise! Bound checks were emitted when indexing an array of size 256 with a u8.

const safe_path_chars: [256]bool = blk: {
    var table: [256]bool = undefined; 
    @memset(&table, false);

    // var table = [_]bool{false} ** 256; doesn't compile, did something change in the trunk ?

    for ("-._~!$&'()*+,;=:@/") |c| table[c] = true;

    break :blk table;
};

export fn isPathSafe(c: u8) bool {
    return safe_path_chars[c];
}

I would expect the optimizer to notice that a u8 can't out-of-bound on an array of size 256, and emit the same ASM if I use raw pointer offset.

Am I missing something ?

dull plover
#

in optimised build modes, I'd expect the compiler to be smart enough to optimise away the bounds check.
also, regarding ** - the operator was removed, use var table: [256]u8 = @splat(false);

sacred shore
#

I can obviously get rid of the bound checks if I use a raw pointer

fn isPathSafe(c: u8) bool {
    const table_ptr: [*]const bool = &safe_path_chars;
    return table_ptr[c];
}

But that should not be needed here.

dull plover