#[inline(always)]
fn w8(s: &[u8], at: usize) -> u64 {
u64::from_ne_bytes([
s[at],
s[at + 1],
s[at + 2],
s[at + 3],
s[at + 4],
s[at + 5],
s[at + 6],
s[at + 7],
])
}
#[inline(always)]
fn w4(s: &[u8], at: usize) -> u32 {
u32::from_ne_bytes([s[at], s[at + 1], s[at + 2], s[at + 3]])
}
#[inline]
#[must_use]
pub fn bytes_eq(a: &[u8], b: &[u8]) -> bool {
let n = a.len();
if n != b.len() {
return false;
}
if n >= 8 {
let mut at = 0;
while at + 8 < n {
if w8(a, at) != w8(b, at) {
return false;
}
at += 8;
}
return w8(a, n - 8) == w8(b, n - 8);
}
if n >= 4 {
return w4(a, 0) == w4(b, 0) && w4(a, n - 4) == w4(b, n - 4);
}
let mut at = 0;
while at < n {
if a[at] != b[at] {
return false;
}
at += 1;
}
true
}
#[cfg(test)]
mod tests {
use super::bytes_eq;
#[test]
fn it_agrees_with_the_slice_comparison_at_every_length_and_position() {
for n in 0..40usize {
let a: Vec<u8> = (0..n).map(|i| (i % 251) as u8).collect();
assert!(bytes_eq(&a, &a.clone()), "{n} bytes against itself");
for at in 0..n {
let mut b = a.clone();
b[at] ^= 0x80;
assert!(!bytes_eq(&a, &b), "{n} bytes differing at {at}");
assert_eq!(bytes_eq(&a, &b), a == b);
}
}
}
#[test]
fn a_different_length_is_never_equal() {
for n in 0..40usize {
let a = vec![b'x'; n];
let b = vec![b'x'; n + 1];
assert!(!bytes_eq(&a, &b));
assert!(!bytes_eq(&b, &a));
}
}
#[test]
fn nothing_is_the_same_as_nothing() {
assert!(bytes_eq(b"", b""));
assert!(bytes_eq(&[], &[]));
}
}