Project

General

Profile

Misc #13870 ยป remove-securerandom-random_number.patch

aycabta (aycabta .), 09/05/2017 04:36 PM

View differences:

lib/securerandom.rb
206 206
    s
207 207
  end
208 208

  
209
=begin
210
  # SecureRandom.random_number generates a random number.
211
  #
212
  # If a positive integer is given as _n_,
213
  # +SecureRandom.random_number+ returns an integer, such that:
214
  # +0 <= SecureRandom.random_number(n) < n+.
215
  #
216
  #   p SecureRandom.random_number(100) #=> 15
217
  #   p SecureRandom.random_number(100) #=> 88
218
  #
219
  # If 0 is given or an argument is not given,
220
  # +SecureRandom.random_number+ returns a float, such that:
221
  # +0.0 <= SecureRandom.random_number() < 1.0+.
222
  #
223
  #   p SecureRandom.random_number #=> 0.596506046187744
224
  #   p SecureRandom.random_number #=> 0.350621695741409
225
  #
226
  def random_number(n=0)
227
    if 0 < n
228
      if defined? OpenSSL::BN
229
        OpenSSL::BN.rand_range(n).to_i
230
      else
231
        hex = n.to_s(16)
232
        hex = '0' + hex if (hex.length & 1) == 1
233
        bin = [hex].pack("H*")
234
        mask = bin[0].ord
235
        mask |= mask >> 1
236
        mask |= mask >> 2
237
        mask |= mask >> 4
238
        begin
239
          rnd = random_bytes(bin.length)
240
          rnd[0] = (rnd[0].ord & mask).chr
241
        end until rnd < bin
242
        rnd.unpack("H*")[0].hex
243
      end
244
    else
245
      # assumption: Float::MANT_DIG <= 64
246
      if defined? OpenSSL::BN
247
        i64 = OpenSSL::BN.rand(64, -1).to_i
248
      else
249
        i64 = random_bytes(8).unpack("Q")[0]
250
      end
251
      Math.ldexp(i64 >> (64-Float::MANT_DIG), -Float::MANT_DIG)
252
    end
253
  end
254
=end
255

  
256 209
  # SecureRandom.uuid generates a random v4 UUID (Universally Unique IDentifier).
257 210
  #
258 211
  #   p SecureRandom.uuid #=> "2d931510-d99f-494a-8c67-87feb05e1594"