Class: StringHasher

Inherits:
Object
  • Object
show all
Defined in:
lib/string_hasher.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(length) ⇒ StringHasher

Returns a new instance of StringHasher.



4
5
6
# File 'lib/string_hasher.rb', line 4

def initialize(length)
  @length = length
end

Instance Attribute Details

#lengthObject (readonly)

Returns the value of attribute length.



2
3
4
# File 'lib/string_hasher.rb', line 2

def length
  @length
end

Instance Method Details

#c_hash(string) ⇒ Object



16
17
18
# File 'lib/string_hasher.rb', line 16

def c_hash(string)
  string.hash_vl(length)
end

#hash(string) ⇒ Object



8
9
10
11
12
13
14
# File 'lib/string_hasher.rb', line 8

def hash(string)
  if String.public_instance_methods.include?(:hash_vl)
    c_hash(string)
  else
    ruby_hash(string)
  end
end

#ruby_hash(string) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/string_hasher.rb', line 20

def ruby_hash(string)
  return 0 if string == ""

  x = string.bytes.first << 7
  m = 1000003
  mask = (1<<length) - 1
  string.each_byte{ |char| x = ((x * m) ^ char.to_i) & mask }

  x ^= string.bytes.count
  x = -2 if x == -1
  x.to_s
end