From f51c56e6c4d7c7ff4a294a909c27526167155a81 Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Sun, 8 Mar 2026 10:58:12 +0000 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=20Bolt:=20Optimize=20packet=20classif?= =?UTF-8?q?ication=20with=20explicit=20fast-path?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: igorls <4753812+igorls@users.noreply.github.com> --- .jules/bolt.md | 3 +++ src/wireguard/device.zig | 10 ++++++++-- 2 files changed, 11 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..9d4ed48 --- /dev/null +++ b/.jules/bolt.md @@ -0,0 +1,3 @@ +## 2024-03-08 - Fast Path Packet Classification +**Learning:** In Zig, standard `switch` statements on integers compile to jump tables. For network packet classification where one type (data plane packets) vastly outnumbers others, the jump table overhead and potential branch mispredictions can be a bottleneck. Furthermore, small utility functions on the hot path may incur call overhead across module boundaries if not explicitly inlined. +**Action:** Extract the dominant case (`msg_type == 4` for `.wg_transport`) into an explicit `if` branch before the `switch` statement to improve branch prediction and avoid jump table overhead for the most common packets. Also mark the function with the `inline` keyword. diff --git a/src/wireguard/device.zig b/src/wireguard/device.zig index bfbf740..ee68e4b 100644 --- a/src/wireguard/device.zig +++ b/src/wireguard/device.zig @@ -24,16 +24,22 @@ pub const PacketType = enum { stun, // STUN binding response unknown, - pub fn classify(data: []const u8) PacketType { + /// Optimization: Inlining small packet classification function and extracting + /// the dominant data-plane path (.wg_transport) outside the switch. + /// This avoids jump table overhead and improves branch prediction for 99%+ of packets. + 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); + + // Fast path: Type 4 (Transport Data) is overwhelmingly the most common + 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) {