1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00

* lib/securerandom.rb: use OpenSSL::BN for performance improvement.

* benchmark/bm_securerandom.rb: benchmark script.

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@47104 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
glass 2014-08-08 11:00:47 +00:00
parent d6f0bd2b84
commit 0a22f4c168
3 changed files with 32 additions and 13 deletions

View file

@ -1,3 +1,9 @@
Fri Aug 8 01:53:37 2014 Masaki Matsushita <glass.saga@gmail.com>
* lib/securerandom.rb: use OpenSSL::BN for performance improvement.
* benchmark/bm_securerandom.rb: benchmark script.
Fri Aug 8 17:19:57 2014 SHIBATA Hiroshi <shibata.hiroshi@gmail.com>
* lib/open-uri.rb: remove needless condition for old ruby version.

View file

@ -0,0 +1,5 @@
require "securerandom"
20_0000.times do
SecureRandom.random_number(100)
end

View file

@ -214,6 +214,9 @@ module SecureRandom
#
def self.random_number(n=0)
if 0 < n
if defined? OpenSSL::BN
OpenSSL::BN.rand_range(n).to_i
else
hex = n.to_s(16)
hex = '0' + hex if (hex.length & 1) == 1
bin = [hex].pack("H*")
@ -226,9 +229,14 @@ module SecureRandom
rnd[0] = (rnd[0].ord & mask).chr
end until rnd < bin
rnd.unpack("H*")[0].hex
end
else
# assumption: Float::MANT_DIG <= 64
if defined? OpenSSL::BN
i64 = OpenSSL::BN.rand(64, -1).to_i
else
i64 = SecureRandom.random_bytes(8).unpack("Q")[0]
end
Math.ldexp(i64 >> (64-Float::MANT_DIG), -Float::MANT_DIG)
end
end