Permalink
Browse files

Add a singleton method to avoid reading the dict every time

  • Loading branch information...
1 parent 20b913e commit 70c37daeb0c85afe9832ad4231cc5c548efb3184 @blaine blaine committed Apr 2, 2012
Showing with 52 additions and 1 deletion.
  1. +18 −0 lib/passphrase_entropy.rb
  2. +1 −1 lib/passphrase_entropy/version.rb
  3. +33 −0 test/singleton_test.rb
View
@@ -6,12 +6,15 @@
#
class PassphraseEntropy
+ attr_accessor :call_count
+
# Instantiate a new PasswordEntropy calculator.
# dictionary should be a String containing a list of words; this is
# /usr/share/dict/words by default, which should be good for English systems.
#
def initialize(dictionary=default_dictionary)
@dictionary = dictionary
+ self.call_count = 0
end
# Estimate the entropy of s (in bytes)
@@ -24,6 +27,20 @@ def inspect(*args)
to_s
end
+ # A singleton method that avoids reloading the dictionary over and over again.
+ class << self
+ attr_accessor :single
+
+ def of(s)
+ self.single = PassphraseEntropy.new if self.single.nil?
+ self.single.entropy(s)
+ end
+
+ def call_count
+ self.single.call_count
+ end
+ end
+
private
def default_dictionary
File.read("/usr/share/dict/words")
@@ -33,6 +50,7 @@ def zlen(s)
z = Zlib::Deflate.new
out = z.deflate(@dictionary + s, Zlib::FINISH)
z.close
+ self.call_count += 1
out.bytesize
end
@@ -1,3 +1,3 @@
class PassphraseEntropy
- VERSION = "0.1.1"
+ VERSION = "0.1.2"
end
View
@@ -0,0 +1,33 @@
+require "minitest/autorun"
+require "passphrase_entropy"
+
+class SingletonTest < MiniTest::Unit::TestCase
+ def test_using_singleton_api
+ start = PassphraseEntropy.single ? PassphraseEntropy.single.call_count : 0
+ PassphraseEntropy.of("this thing")
+ assert_equal start + 1, PassphraseEntropy.single.call_count
+ PassphraseEntropy.of("that thing")
+ assert_equal start + 2, PassphraseEntropy.single.call_count
+ end
+
+ def test_that_using_singleton_is_faster_than_not
+ test_set = [ "rubbish!", "rubbish" "sdfjhweu", "password" "Password1",
+ "password" "Slightly^better 1", "Password1" "correct horse battery staple",
+ "Tr0ub4dor&3" "~T3n Char$", "antidisestablishmentarianism" ]
+
+ t0 = Time.now
+ test_set.each do |s|
+ pe = PassphraseEntropy.new
+ pe.entropy(s)
+ end
+ without = Time.now - t0
+
+ t1 = Time.now
+ test_set.each do |s|
+ PassphraseEntropy.of(s)
+ end
+ with = Time.now - t1
+
+ assert with < without
+ end
+end

0 comments on commit 70c37da

Please sign in to comment.