Class: CryptoToolchain::Utilities::MT19937

Inherits:
Object
  • Object
show all
Defined in:
lib/crypto_toolchain/utilities/mt_19937.rb

Constant Summary collapse

PARAMETERS_32 =
{
  w: 32, n: 624, m: 397, r: 31,
  a: 0x9908b0df,
  u: 11, d: 0xFFFFFFFF,
  s: 7,  b: 0x9d2c5680,
  t: 15, c: 0xefc60000,
  l: 18,
  f: 1812433253
}.freeze
PARAMETERS_64 =
{
  w: 64, n: 312, m: 156, r: 31,
  a: 0xB5026F5AA96619E9,
  u: 29, d: 0x5555555555555555,
  s: 17, b: 0x71D67FFFEDA60000,
  t: 37, c: 0xFFF7EEE000000000,
  l: 43,
  f: 6364136223846793005
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(seed, bits: 32) ⇒ MT19937

Returns a new instance of MT19937.



44
45
46
47
48
49
# File 'lib/crypto_toolchain/utilities/mt_19937.rb', line 44

def initialize(seed, bits: 32)
  @seed = seed
  set_vars!(self.class.parameters_for(bits))
  @index = n
  @state = build_state!
end

Class Method Details

.from_array(arr, bits: 32, index: parameters_for(bits).fetch(:n)) ⇒ Object



26
27
28
29
30
31
# File 'lib/crypto_toolchain/utilities/mt_19937.rb', line 26

def self.from_array(arr, bits: 32, index: parameters_for(bits).fetch(:n))
  mt = new(0, bits: bits)
  mt.send(:state=, arr)
  mt.send(:index=, index)
  mt
end

.parameters_for(bits) ⇒ Object



33
34
35
36
37
38
39
40
41
42
# File 'lib/crypto_toolchain/utilities/mt_19937.rb', line 33

def self.parameters_for(bits)
  case bits
  when 32
    PARAMETERS_32
  when 64
    PARAMETERS_64
  else
    raise ArgumentError.new("Bits must be 32 or 64")
  end
end

Instance Method Details

#==(other) ⇒ Object



51
52
53
54
# File 'lib/crypto_toolchain/utilities/mt_19937.rb', line 51

def ==(other)
  return false unless other.is_a?(self.class)
  other.send(:state) == state && other.send(:index) == index
end

#extractObject



56
57
58
59
60
61
# File 'lib/crypto_toolchain/utilities/mt_19937.rb', line 56

def extract
  twist! if index >= n
  temper(state[index])
ensure
  @index += 1
end

#temper(y) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/crypto_toolchain/utilities/mt_19937.rb', line 63

def temper(y)
  y ^= (y >> u) & d
  y ^= (y << s) & b
  y ^= (y << t) & c
  y ^= (y >> l)
  lowest_bits(y)
end

#untemper(y) ⇒ Object



71
72
73
74
75
76
# File 'lib/crypto_toolchain/utilities/mt_19937.rb', line 71

def untemper(y)
  y = untemper_rshift(y, shift: l)
  y = untemper_lshift(y, shift: t, mask: c)
  y = untemper_lshift(y, shift: s, mask: b)
  untemper_rshift(y, shift: u, mask: d)
end