Skip to content

Commit 0a22f4c

Browse files
author
glass
committed
* 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
1 parent d6f0bd2 commit 0a22f4c

File tree

3 files changed

+32
-13
lines changed

3 files changed

+32
-13
lines changed

ChangeLog

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
Fri Aug 8 01:53:37 2014 Masaki Matsushita <[email protected]>
2+
3+
* lib/securerandom.rb: use OpenSSL::BN for performance improvement.
4+
5+
* benchmark/bm_securerandom.rb: benchmark script.
6+
17
Fri Aug 8 17:19:57 2014 SHIBATA Hiroshi <[email protected]>
28

39
* lib/open-uri.rb: remove needless condition for old ruby version.

benchmark/bm_securerandom.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
require "securerandom"
2+
3+
20_0000.times do
4+
SecureRandom.random_number(100)
5+
end

lib/securerandom.rb

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -214,21 +214,29 @@ def self.urlsafe_base64(n=nil, padding=false)
214214
#
215215
def self.random_number(n=0)
216216
if 0 < n
217-
hex = n.to_s(16)
218-
hex = '0' + hex if (hex.length & 1) == 1
219-
bin = [hex].pack("H*")
220-
mask = bin[0].ord
221-
mask |= mask >> 1
222-
mask |= mask >> 2
223-
mask |= mask >> 4
224-
begin
225-
rnd = SecureRandom.random_bytes(bin.length)
226-
rnd[0] = (rnd[0].ord & mask).chr
227-
end until rnd < bin
228-
rnd.unpack("H*")[0].hex
217+
if defined? OpenSSL::BN
218+
OpenSSL::BN.rand_range(n).to_i
219+
else
220+
hex = n.to_s(16)
221+
hex = '0' + hex if (hex.length & 1) == 1
222+
bin = [hex].pack("H*")
223+
mask = bin[0].ord
224+
mask |= mask >> 1
225+
mask |= mask >> 2
226+
mask |= mask >> 4
227+
begin
228+
rnd = SecureRandom.random_bytes(bin.length)
229+
rnd[0] = (rnd[0].ord & mask).chr
230+
end until rnd < bin
231+
rnd.unpack("H*")[0].hex
232+
end
229233
else
230234
# assumption: Float::MANT_DIG <= 64
231-
i64 = SecureRandom.random_bytes(8).unpack("Q")[0]
235+
if defined? OpenSSL::BN
236+
i64 = OpenSSL::BN.rand(64, -1).to_i
237+
else
238+
i64 = SecureRandom.random_bytes(8).unpack("Q")[0]
239+
end
232240
Math.ldexp(i64 >> (64-Float::MANT_DIG), -Float::MANT_DIG)
233241
end
234242
end

0 commit comments

Comments
 (0)