1 Commits

Author SHA1 Message Date
4f16b0b2fd Fix typo in comment and add Evaluate function for hash comparison
Corrected a typo in a comment within `nilsimsa.go`. Introduced a new `Evaluate` function in `evaluate.go` to compute the bitwise difference between two Nilsimsa hash values, ensuring input validation and proper bit counting logic.
2025-06-16 14:13:17 +01:00
2 changed files with 36 additions and 1 deletions

35
evaluate.go Normal file
View File

@@ -0,0 +1,35 @@
package nilsimsa
import (
"fmt"
)
func Evaluate(a, b []byte) (int, error) {
// Check if the lengths of the strings are the same
if len(a) != len(b) {
return 0, fmt.Errorf("byte strings are of different lengths %d and %d", len(a), len(b))
}
if len(a) != 32 || len(b) != 32 {
return 0, fmt.Errorf("input nilsimsa hashes must be 32 bytes each, got %d and %d",
len(a), len(b))
}
// Count the differing bits
bitDiffCount := 0
for i := 0; i < len(a); i++ {
// XOR the bytes and count the number of `1` bits
xor := a[i] ^ b[i]
bitDiffCount += countBits(xor)
}
return bitDiffCount, nil
}
// Count the number of `1` bits in a byte
func countBits(x byte) int {
count := 0
for x > 0 {
count += int(x & 1) // Add the last bit
x >>= 1 // Right shift the bits
}
return count
}

View File

@@ -127,7 +127,7 @@ type Digest struct {
// New create a new Nilsimsa hash diget
func New() hash.Hash {
d := new(Digest)
// Note that no memory is allocate other than the struct itself. It is better to embedd
// Note that no memory is allocate other than the struct itself. It is better to embed
// last4Array into the struct itself since it's maximum size is know already
// d.last4 = d.last4Array[:0] //creating the slice by re-slicing last4Array
return d