malachite_base/num/logic/hamming_distance.rs
1// Copyright © 2025 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::num::basic::signeds::PrimitiveSigned;
10use crate::num::basic::unsigneds::PrimitiveUnsigned;
11use crate::num::logic::traits::{CheckedHammingDistance, CountOnes, HammingDistance};
12
13fn hamming_distance_unsigned<T: PrimitiveUnsigned>(x: T, y: T) -> u64 {
14 CountOnes::count_ones(x ^ y)
15}
16
17macro_rules! impl_hamming_distance_unsigned {
18 ($t:ident) => {
19 impl HammingDistance<$t> for $t {
20 /// Returns the Hamming distance between two numbers, or the number of bit flips needed
21 /// to turn one into the other.
22 ///
23 /// # Worst-case complexity
24 /// Constant time and additional memory.
25 ///
26 /// # Examples
27 /// See [here](super::hamming_distance#hamming_distance).
28 #[inline]
29 fn hamming_distance(self, other: $t) -> u64 {
30 hamming_distance_unsigned(self, other)
31 }
32 }
33 };
34}
35apply_to_unsigneds!(impl_hamming_distance_unsigned);
36
37fn checked_hamming_distance_signed<T: PrimitiveSigned>(x: T, y: T) -> Option<u64> {
38 if (x >= T::ZERO) == (y >= T::ZERO) {
39 Some(CountOnes::count_ones(x ^ y))
40 } else {
41 None
42 }
43}
44
45macro_rules! impl_checked_hamming_distance_signed {
46 ($t:ident) => {
47 impl CheckedHammingDistance<$t> for $t {
48 /// Returns the Hamming distance between two numbers, or the number of bit flips needed
49 /// to turn one into the other.
50 ///
51 /// If the two numbers have opposite signs, then the number of flips would be infinite,
52 /// so the result is `None`.
53 ///
54 /// # Worst-case complexity
55 /// Constant time and additional memory.
56 ///
57 /// # Examples
58 /// See [here](super::hamming_distance#checked_hamming_distance).
59 #[inline]
60 fn checked_hamming_distance(self, other: $t) -> Option<u64> {
61 checked_hamming_distance_signed(self, other)
62 }
63 }
64 };
65}
66apply_to_signeds!(impl_checked_hamming_distance_signed);