Skip to content

Commit

Permalink
perf(iroh-net): simplify stun::is check (#1580)
Browse files Browse the repository at this point in the history
This is run on every packet, and showed up in some profiling as not
being as cheap as it should be
  • Loading branch information
dignifiedquire authored Oct 5, 2023
1 parent 2e5e464 commit 0b28d15
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions iroh-net/src/stun.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,15 @@ pub fn response(tx: TransactionId, addr: SocketAddr) -> Vec<u8> {
buffer
}

// Copied from stun_rs
// const MAGIC_COOKIE: Cookie = Cookie(0x2112_A442);
const COOKIE: [u8; 4] = 0x2112_A442u32.to_be_bytes();

/// Reports whether b is a STUN message.
pub fn is(b: &[u8]) -> bool {
let cookie: [u8; 4] = b[4..8].try_into().unwrap();

b.len() >= stun_rs::MESSAGE_HEADER_SIZE &&
b[0]&0b11000000 == 0 && // top two bits must be zero
cookie == stun_rs::MAGIC_COOKIE
b[4..8] == COOKIE
}

/// Parses a STUN binding request.
Expand Down Expand Up @@ -508,6 +510,11 @@ mod tests {
assert_eq!(got_tx, tx);
}

#[test]
fn test_stun_cookie() {
assert_eq!(stun_rs::MAGIC_COOKIE, COOKIE);
}

#[test]
fn test_response() {
let txn = |n| TransactionId::from([n; 12]);
Expand Down

0 comments on commit 0b28d15

Please sign in to comment.