Skip to content

Commit

Permalink
hex_util: simplify common_hex_len() a bit to compare input bytes once
Browse files Browse the repository at this point in the history
I think it's slightly easier to follow if we calculate a diff of input bits
first. I don't know which one is faster, but I assume compiler can optimize to
similar instructions.
  • Loading branch information
yuja committed Sep 16, 2024
1 parent ac605d2 commit a684076
Showing 1 changed file with 4 additions and 10 deletions.
14 changes: 4 additions & 10 deletions lib/src/hex_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,10 @@ pub fn to_reverse_hex(forward_hex: &str) -> Option<String> {
pub fn common_hex_len(bytes_a: &[u8], bytes_b: &[u8]) -> usize {
std::iter::zip(bytes_a, bytes_b)
.enumerate()
.find_map(|(i, (a, b))| {
if a != b {
if a >> 4 != b >> 4 {
Some(i * 2)
} else {
Some(i * 2 + 1)
}
} else {
None
}
.find_map(|(i, (a, b))| match a ^ b {
0 => None,
d if d & 0xf0 == 0 => Some(i * 2 + 1),
_ => Some(i * 2),
})
.unwrap_or_else(|| bytes_a.len().min(bytes_b.len()) * 2)
}
Expand Down

0 comments on commit a684076

Please sign in to comment.