Module: Mmh3

Defined in:
lib/mmh3.rb,
lib/mmh3/version.rb

Overview

This module consists module functions that implement MurmurHash3. MurmurHash3 was written by Austin Appleby, and is placed in the public domain. The author hereby disclaims copyright to this source code.

Constant Summary collapse

VERSION =

Version number of Mmh3 you are using.

'1.2.0'

Class Method Summary collapse

Class Method Details

.hash128(key, seed: 0, x64arch: true) ⇒ Integer

Generate a 128-bit hash value.

Examples:

require 'mmh3'

puts Mmh3.hash128('Hello, world') # => 87198040132278428547135563345531192982

Parameters:

  • key (String)

    Key for hash value.

  • seed (Integer) (defaults to: 0)

    Seed for hash value.

  • x64arch (Boolean) (defaults to: true)

    Flag indicating whether to generate hash value for x64 architecture.

Returns:

  • (Integer)

    Returns hash value.



70
71
72
73
74
# File 'lib/mmh3.rb', line 70

def hash128(key, seed: 0, x64arch: true)
  return hash128_x86(key, seed) if x64arch == false

  hash128_x64(key, seed)
end

.hash32(key, seed: 0) ⇒ Integer

Generate a 32-bit hash value.

Examples:

require 'mmh3'

puts Mmh3.hash32('Hello, world') # => 1785891924

Parameters:

  • key (String)

    Key for hash value.

  • seed (Integer) (defaults to: 0)

    Seed for hash value.

Returns:

  • (Integer)

    Returns hash value.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/mmh3.rb', line 24

def hash32(key, seed: 0)
  keyb = key.to_s.bytes
  key_len = keyb.size
  n_blocks = key_len / 4

  h = seed
  (0...n_blocks * 4).step(4) do |bstart|
    k = block32(keyb, bstart, 0)
    h ^= scramble32(k)
    h = rotl32(h, 13)
    h = ((h * 5) + 0xe6546b64) & 0xFFFFFFFF
  end

  tail_id = n_blocks * 4
  tail_sz = key_len & 3

  k = 0
  # rubocop:disable Layout/ExtraSpacing, Layout/SpaceAroundOperators
  k ^= keyb[tail_id + 2] << 16 if tail_sz >= 3
  k ^= keyb[tail_id + 1] <<  8 if tail_sz >= 2
  k ^= keyb[tail_id + 0]       if tail_sz >= 1
  # rubocop:enable Layout/ExtraSpacing, Layout/SpaceAroundOperators

  h ^= scramble32(k) if tail_sz.positive?

  h = fmix32(h ^ key_len)

  if (h & 0x80000000).zero?
    h
  else
    -((h ^ 0xFFFFFFFF) + 1)
  end
end