Skip to content

Commit 366c242

Browse files
committed
Optimize checksum calculation
Replace slice iteration with indexed access to reduce overhead and improve performance - CPU usage dropped by 8% on Apple M1.
1 parent e2b75e3 commit 366c242

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

src/wire/ip.rs

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -688,26 +688,28 @@ pub mod checksum {
688688
// For each 32-byte chunk...
689689
const CHUNK_SIZE: usize = 32;
690690
while data.len() >= CHUNK_SIZE {
691-
let mut d = &data[..CHUNK_SIZE];
691+
let chunk = &data[..CHUNK_SIZE];
692+
let mut i = 0;
692693
// ... take by 2 bytes and sum them.
693-
while d.len() >= 2 {
694-
accum += NetworkEndian::read_u16(d) as u32;
695-
d = &d[2..];
694+
while i + 1 < CHUNK_SIZE {
695+
accum += u16::from_be_bytes([chunk[i], chunk[i + 1]]) as u32;
696+
i += 2;
696697
}
697698

698699
data = &data[CHUNK_SIZE..];
699700
}
700701

701702
// Sum the rest that does not fit the last 32-byte chunk,
702703
// taking by 2 bytes.
703-
while data.len() >= 2 {
704-
accum += NetworkEndian::read_u16(data) as u32;
705-
data = &data[2..];
704+
let mut i = 0;
705+
while i + 1 < data.len() {
706+
accum += u16::from_be_bytes([data[i], data[i + 1]]) as u32;
707+
i += 2;
706708
}
707709

708710
// Add the last remaining odd byte, if any.
709-
if let Some(&value) = data.first() {
710-
accum += (value as u32) << 8;
711+
if i < data.len() {
712+
accum += (data[i] as u32) << 8;
711713
}
712714

713715
propagate_carries(accum)

0 commit comments

Comments
 (0)