From b58d923acd6029a095cb995d6169e179014727a7 Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Thu, 5 Mar 2026 10:57:03 +0000 Subject: [PATCH] Optimize packet classification fast path Extracts the dominant case (WireGuard transport data packets) into an explicit `if` check before the `switch` statement in `PacketType.classify` to improve branch prediction and avoid jump table overhead on the hottest path. Also inlines the function. Co-authored-by: igorls <4753812+igorls@users.noreply.github.com> --- .jules/bolt.md | 3 +++ src/wireguard/device.zig | 8 ++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) create mode 100644 .jules/bolt.md diff --git a/.jules/bolt.md b/.jules/bolt.md new file mode 100644 index 0000000..aa07784 --- /dev/null +++ b/.jules/bolt.md @@ -0,0 +1,3 @@ +## 2024-05-14 - Packet Classification Fast Path +**Learning:** Optimizing the packet classification function `PacketType.classify` is beneficial because it's called on every single incoming UDP packet (the hottest path in the system). Standard `switch` statements compile to jump tables. Extracting the dominant case (`msg_type == 4` for `.wg_transport` data-plane packets) into an explicit `if` branch before the `switch` statement improves branch prediction and avoids jump table overhead. +**Action:** Always consider the dominant branch in high-throughput hot paths and hoist it outside of standard switch/jump table constructs when possible. Documented the fast path optimization. diff --git a/src/wireguard/device.zig b/src/wireguard/device.zig index bfbf740..aa47b6b 100644 --- a/src/wireguard/device.zig +++ b/src/wireguard/device.zig @@ -24,16 +24,20 @@ pub const PacketType = enum { stun, // STUN binding response unknown, - pub fn classify(data: []const u8) PacketType { + pub inline fn classify(data: []const u8) PacketType { if (data.len < 4) return .unknown; // WireGuard messages: first byte is type, next 3 are zeros const msg_type = std.mem.readInt(u32, data[0..4], .little); + + // Optimization: fast path for the dominant case (data-plane packets). + // Explicit `if` branch avoids jump table overhead and improves branch prediction. + 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) {