Danylo's website

Zig patch VTable

Word count: ~132

Zig does not have language level interfaces, so dynamic dispatch is written the C way. Usually, you will see Vtable struct.

pub const VTable = struct {
    move: *const fn (reader: *Reader, advance: usize, len: usize) MoveError!void,
    checkEncoding: *const fn (reader: *Reader, encoding: []const u8) bool,
};

Since Vtable is just a set of pointers, you can replace pointers without creating a wrapper interface first.

fn foo() !void {
    const sr = &streaming.interface;
    const myVtable = &xml.Reader.VTable{
        .move = sr.vtable.move,
        .checkEncoding = &checkEncodingAlwaysTrue,
    };
    sr.vtable = myVtable;
}

fn checkEncodingAlwaysTrue(reader: *xml.Reader, encoding: []const u8) bool {
    _ = reader;
    _ = encoding;
    return true;
}
wc -l optimizations