diff --git a/.jules/bolt.md b/.jules/bolt.md new file mode 100644 index 0000000..2a82f77 --- /dev/null +++ b/.jules/bolt.md @@ -0,0 +1,9 @@ +# Bolt Journal + +## 2024-05-24 - Initial setup +**Learning:** Initializing Bolt journal. +**Action:** Always document critical learnings here. + +## 2024-05-24 - Zig jump tables for packet classification +**Learning:** In Zig, standard `switch` statements on sequential integers compile to jump tables. On hot paths (like packet classification), if there is a dominant case (e.g. data-plane packets, which make up 99.9% of traffic), extracting it into an explicit `if` branch *before* the `switch` prevents jump table overhead and improves branch prediction. +**Action:** Always extract dominant cases from switches when on critical hot paths like packet forwarding. diff --git a/src/wireguard/device.zig b/src/wireguard/device.zig index bfbf740..23b0ab1 100644 --- a/src/wireguard/device.zig +++ b/src/wireguard/device.zig @@ -29,11 +29,15 @@ pub const PacketType = enum { // WireGuard messages: first byte is type, next 3 are zeros const msg_type = std.mem.readInt(u32, data[0..4], .little); + + // Optimization: Extract dominant case (data-plane packets) to improve + // branch prediction and avoid jump table overhead on the hot path. + if (msg_type == 4) return .wg_transport; + return switch (msg_type) { 1 => .wg_handshake_init, 2 => .wg_handshake_resp, 3 => .wg_cookie, - 4 => .wg_transport, else => blk: { // STUN: check for magic cookie at bytes 4-7 if (data.len >= 8) {