Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
@@ -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.
8 changes: 6 additions & 2 deletions src/wireguard/device.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down