Skip to content

Commit 0579a72

Browse files
authored
Small aesthetic improvement to the FNV implementation (#18)
An improvement to the FNV implementation that calculates a bitmask using a power of two minus one instead of hardcoding them. 2^32-1 == 0xffffffff
1 parent 91f966a commit 0579a72

File tree

2 files changed

+2
-16
lines changed

2 files changed

+2
-16
lines changed

lib/fnv.rb

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,24 +8,18 @@ module River
88
module FNV
99
def self.fnv1_hash(str, size:)
1010
hash = OFFSET_BASIS.fetch(size)
11-
mask = MASK.fetch(size)
11+
mask = (2**size - 1).to_int # creates a mask of 1s of `size` bits long like 0xffffffff
1212
prime = PRIME.fetch(size)
1313

1414
str.each_byte do |byte|
1515
hash *= prime
16-
hash &= mask # take lower N bits of multiplication product
16+
hash &= mask
1717
hash ^= byte
1818
end
1919

2020
hash
2121
end
2222

23-
MASK = {
24-
32 => 0xffffffff, # mask 32 bits long
25-
64 => 0xffffffffffffffff # mask 64 bits long
26-
}.freeze
27-
private_constant :MASK
28-
2923
OFFSET_BASIS = {
3024
32 => 0x811c9dc5,
3125
64 => 0xcbf29ce484222325

spec/fnv_spec.rb

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,6 @@
1414
end
1515
end
1616
end
17-
18-
# Just a sanity check to make sure the number of 0xffs is right.
19-
describe "MASK" do
20-
it "contains masks equal to integer limits" do
21-
expect(River::FNV.const_get(:MASK)[32]).to eq(4_294_967_295)
22-
expect(River::FNV.const_get(:MASK)[64]).to eq(18_446_744_073_709_551_615)
23-
end
24-
end
2517
end
2618

2719
#

0 commit comments

Comments
 (0)