diff --git a/.gemspec b/.gemspec deleted file mode 100644 index ea0db60..0000000 --- a/.gemspec +++ /dev/null @@ -1,307 +0,0 @@ -# encoding: utf-8 - -require 'yaml' -require 'pathname' - -module Indexer - - # Convert index data into a gemspec. - # - # Notes: - # * Assumes all executables are in bin/. - # * Does not yet handle default_executable setting. - # * Does not yet handle platform setting. - # * Does not yet handle required_ruby_version. - # * Support for rdoc entries is weak. - # - class GemspecExporter - - # File globs to include in package --unless a manifest file exists. - FILES = ".index .yardopts alt bin data demo ext features lib man spec test try* [A-Z]*.*" unless defined?(FILES) - - # File globs to omit from FILES. - OMIT = "Config.rb" unless defined?(OMIT) - - # Standard file patterns. - PATTERNS = { - :root => '{.index,Gemfile}', - :bin => 'bin/*', - :lib => 'lib/{**/}*', #.rb', - :ext => 'ext/{**/}extconf.rb', - :doc => '*.{txt,rdoc,md,markdown,tt,textile}', - :test => '{test,spec}/{**/}*.rb' - } unless defined?(PATTERNS) - - # For which revision of indexer spec is this converter intended? - REVISION = 2013 unless defined?(REVISION) - - # - def self.gemspec - new.to_gemspec - end - - # - attr :metadata - - # - def initialize(metadata=nil) - @root_check = false - - if metadata - root_dir = metadata.delete(:root) - if root_dir - @root = root_dir - @root_check = true - end - metadata = nil if metadata.empty? - end - - @metadata = metadata || YAML.load_file(root + '.index') - - if @metadata['revision'].to_i != REVISION - warn "This gemspec exporter was not designed for this revision of index metadata." - end - end - - # - def has_root? - root ? true : false - end - - # - def root - return @root if @root || @root_check - @root_check = true - @root = find_root - end - - # - def manifest - return nil unless root - @manifest ||= Dir.glob(root + 'manifest{,.txt}', File::FNM_CASEFOLD).first - end - - # - def scm - return nil unless root - @scm ||= %w{git hg}.find{ |m| (root + ".#{m}").directory? }.to_sym - end - - # - def files - return [] unless root - @files ||= \ - if manifest - File.readlines(manifest). - map{ |line| line.strip }. - reject{ |line| line.empty? || line[0,1] == '#' } - else - list = [] - Dir.chdir(root) do - FILES.split(/\s+/).each do |pattern| - list.concat(glob(pattern)) - end - OMIT.split(/\s+/).each do |pattern| - list = list - glob(pattern) - end - end - list - end.select{ |path| File.file?(path) }.uniq - end - - # - def glob_files(pattern) - return [] unless root - Dir.chdir(root) do - Dir.glob(pattern).select do |path| - File.file?(path) && files.include?(path) - end - end - end - - def patterns - PATTERNS - end - - def executables - @executables ||= \ - glob_files(patterns[:bin]).map do |path| - File.basename(path) - end - end - - def extensions - @extensions ||= \ - glob_files(patterns[:ext]).map do |path| - File.basename(path) - end - end - - def name - metadata['name'] || metadata['title'].downcase.gsub(/\W+/,'_') - end - - def homepage - page = ( - metadata['resources'].find{ |r| r['type'] =~ /^home/i } || - metadata['resources'].find{ |r| r['name'] =~ /^home/i } || - metadata['resources'].find{ |r| r['name'] =~ /^web/i } - ) - page ? page['uri'] : false - end - - def licenses - metadata['copyrights'].map{ |c| c['license'] }.compact - end - - def require_paths - paths = metadata['paths'] || {} - paths['load'] || ['lib'] - end - - # - # Convert to gemnspec. - # - def to_gemspec - if has_root? - Gem::Specification.new do |gemspec| - to_gemspec_data(gemspec) - to_gemspec_paths(gemspec) - end - else - Gem::Specification.new do |gemspec| - to_gemspec_data(gemspec) - to_gemspec_paths(gemspec) - end - end - end - - # - # Convert pure data settings. - # - def to_gemspec_data(gemspec) - gemspec.name = name - gemspec.version = metadata['version'] - gemspec.summary = metadata['summary'] - gemspec.description = metadata['description'] - - metadata['authors'].each do |author| - gemspec.authors << author['name'] - - if author.has_key?('email') - if gemspec.email - gemspec.email << author['email'] - else - gemspec.email = [author['email']] - end - end - end - - gemspec.licenses = licenses - - requirements = metadata['requirements'] || [] - requirements.each do |req| - next if req['optional'] - next if req['external'] - - name = req['name'] - groups = req['groups'] || [] - - version = gemify_version(req['version']) - - if groups.empty? or groups.include?('runtime') - # populate runtime dependencies - if gemspec.respond_to?(:add_runtime_dependency) - gemspec.add_runtime_dependency(name,*version) - else - gemspec.add_dependency(name,*version) - end - else - # populate development dependencies - if gemspec.respond_to?(:add_development_dependency) - gemspec.add_development_dependency(name,*version) - else - gemspec.add_dependency(name,*version) - end - end - end - - # convert external dependencies into gemspec requirements - requirements.each do |req| - next unless req['external'] - gemspec.requirements << ("%s-%s" % req.values_at('name', 'version')) - end - - gemspec.homepage = homepage - gemspec.require_paths = require_paths - gemspec.post_install_message = metadata['install_message'] - end - - # - # Set gemspec settings that require a root directory path. - # - def to_gemspec_paths(gemspec) - gemspec.files = files - gemspec.extensions = extensions - gemspec.executables = executables - - if Gem::VERSION < '1.7.' - gemspec.default_executable = gemspec.executables.first - end - - gemspec.test_files = glob_files(patterns[:test]) - - unless gemspec.files.include?('.document') - gemspec.extra_rdoc_files = glob_files(patterns[:doc]) - end - end - - # - # Return a copy of this file. This is used to generate a local - # .gemspec file that can automatically read the index file. - # - def self.source_code - File.read(__FILE__) - end - - private - - def find_root - root_files = patterns[:root] - if Dir.glob(root_files).first - Pathname.new(Dir.pwd) - elsif Dir.glob("../#{root_files}").first - Pathname.new(Dir.pwd).parent - else - #raise "Can't find root of project containing `#{root_files}'." - warn "Can't find root of project containing `#{root_files}'." - nil - end - end - - def glob(pattern) - if File.directory?(pattern) - Dir.glob(File.join(pattern, '**', '*')) - else - Dir.glob(pattern) - end - end - - def gemify_version(version) - case version - when /^(.*?)\+$/ - ">= #{$1}" - when /^(.*?)\-$/ - "< #{$1}" - when /^(.*?)\~$/ - "~> #{$1}" - else - version - end - end - - end - -end - -Indexer::GemspecExporter.gemspec \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..1c68406 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,32 @@ +name: CI + +on: + push: + pull_request: + +permissions: + contents: read + +jobs: + test: + name: Ruby ${{ matrix.ruby }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + ruby: ['2.7', '3.0', '3.1', '3.2', '3.3', '3.4', '4.0'] + steps: + - uses: actions/checkout@v4 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + - name: Unit tests + run: bundle exec rubytest -Ilib -Itest test/ + - name: Demos + run: bundle exec qed -Ilib demo/ + - name: Demos with frozen string literals + if: matrix.ruby == '4.0' + run: bundle exec qed -Ilib demo/ + env: + RUBYOPT: --enable=frozen-string-literal diff --git a/.gitignore b/.gitignore index 5c1cd7b..dff1a8c 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,7 @@ tmp/ web/ DEMO.rdoc DEMO.md + +pkg/ +.bundle/ +vendor/ diff --git a/.index b/.index deleted file mode 100644 index ead4e7a..0000000 --- a/.index +++ /dev/null @@ -1,78 +0,0 @@ ---- -revision: 2013 -type: ruby -sources: -- Index.yml -- Gemfile -authors: -- name: Trans - email: transfire@gmail.com -- name: Kirk Haines -- name: Robert Klemme -- name: Jan Molic -- name: George Moschovitis -- name: Jeena Paradies -- name: Erik Veenstra -organizations: -- name: RubyWorks (http://rubyworks.github.com/) -requirements: -- groups: - - development - - test - version: ">= 0" - name: qed -- groups: - - development - - test - version: ">= 0" - name: lemon -- groups: - - development - - test - version: ">= 0" - name: rubytest-cli -conflicts: [] -alternatives: [] -resources: -- type: home - uri: http://rubyworks.github.com/hashery - label: Homepage -- type: code - uri: http://github.com/rubyworks/hashery - label: Source Code -- type: mail - uri: http://groups.google.com/group/rubyworks-mailinglist - label: Mailing List -- type: docs - uri: http://rubydoc.info/github/rubyworks/hashery/master/frames - label: Documentation -- type: wiki - uri: http://wiki.github.com/rubyworks/hashery - label: User Guide -- type: gems - uri: http://rubygems.org/gems/hashery -repositories: -- name: upstream - scm: git - uri: git://github.com/rubyworks/hashery.git -categories: [] -copyrights: -- holder: Rubyworks - year: '2010' - license: BSD-2-Clause -customs: [] -paths: - lib: - - lib - - alt -name: hashery -title: Hashery -version: 2.1.2 -summary: Facets-bread collection of Hash-like classes. -description: The Hashery is a tight collection of Hash-like classes. Included among - its many offerings are the auto-sorting Dictionary class, the efficient LRUHash, - the flexible OpenHash and the convenient KeyHash. Nearly every class is a subclass - of the CRUDHash which defines a CRUD model on top of Ruby's standard Hash making - it a snap to subclass and augment to fit any specific use case. -created: '2010-04-21' -date: '2016-05-01' diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 566d07b..0000000 --- a/.travis.yml +++ /dev/null @@ -1,17 +0,0 @@ ---- -language: ruby -script: "bundle exec $TESTCOMMAND" -rvm: - - 1.9.3 - - 2.1.1 - - rbx-2 - - rbx - - jruby -env: - - TESTCOMMAND="qed" - - TESTCOMMAND="rubytest -Ilib -Itest test/" -matrix: - allow_failures: - - rvm: rbx - - rvm: rbx-2 -cache: bundler diff --git a/Assembly b/Assembly deleted file mode 100644 index 4b9f899..0000000 --- a/Assembly +++ /dev/null @@ -1,38 +0,0 @@ ---- -email: - mailto: - - ruby-talk@ruby-lang.org - - rubyworks-mailinglist@googlegroups.com - -github: - gh_pages: web - -gem: - gemspec: pkg/hashery.gemspec - -yard: - yardopts: true - priority: 2 - -qedoc: - title: Hashery Demonstrandum - output: - - DEMO.rdoc - - web/demo.html - -#lemon: -# service: Custom -# test: | -# abort unless system "lemon -Ilib test/" - -dnote: - labels: ~ - output: work/NOTES.rdoc - -vclog: - output: - - log/History.rdoc - - log/Changes.rdoc - active: false - - diff --git a/Gemfile b/Gemfile index 6289a8f..bf1bc0c 100644 --- a/Gemfile +++ b/Gemfile @@ -1,11 +1,11 @@ -# encoding: UTF-8 +source "https://rubygems.org" -source "http://rubygems.org" +gemspec -group "development", "test" do - #gem "detroit", :group => "build" +group :development, :test do + gem "rake" gem "qed" + gem "ae" gem "lemon" gem "rubytest-cli" end - diff --git a/HISTORY.md b/HISTORY.md index d91c900..9481fc1 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,5 +1,33 @@ # RELEASE HISTORY +## 2.2.0 / unreleased + +This release concentrates on LRUHash, by far the most used part of the +Hashery. Its public API is unchanged, but it has been reimplemented on top +of Ruby's ordered Hash instead of a linked list of nodes, which makes it +about twice as fast, and a number of bugs have been fixed. It also +modernizes the project: Ruby 2.7 or newer is now required, the gem is +built from a plain gemspec, and CI runs on GitHub Actions. + +Changes: + +* LRUHash is about 2x faster, using Ruby's ordered Hash internally. +* Fix LRUHash#dup and #clone, which shared state with the original. +* Fix LRUHash#inspect and #to_s, which showed keys and values with #to_s + and failed under frozen string literals. +* LRUHash#keys and #values now list most recently used first, like #each. +* LRUHash#fetch accepts a default argument and its KeyError names the key. +* LRUHash#delete accepts a block for missing keys, like Hash#delete. +* LRUHash#delete_if returns an Enumerator when called without a block. +* Add LRUHash#length. +* Fix IniHash.new with a Hash, and so IniHash.text and .write_to_file. +* Fix IniHash.write_to_file with a comment (used String#each). +* Fix `require 'hashery/static_hash'` on its own. +* Prepare for frozen string literals and fix warnings under `ruby -w`. +* Require Ruby 2.7 or newer. +* Replace Indexer metadata (.index, Index.yml) with hashery.gemspec. +* Replace Travis CI with GitHub Actions. + ## 2.1.2 / 2016-05-02 Minor release fixes a test for KeyHash. And that's it. diff --git a/Index.yml b/Index.yml deleted file mode 100644 index 5d88285..0000000 --- a/Index.yml +++ /dev/null @@ -1,52 +0,0 @@ ---- -name: - hashery - -version: - 2.1.2 - -title: - Hashery - -summary: - Facets-bread collection of Hash-like classes. - -description: - The Hashery is a tight collection of Hash-like classes. Included among its many - offerings are the auto-sorting Dictionary class, the efficient LRUHash, the - flexible OpenHash and the convenient KeyHash. Nearly every class is a subclass - of the CRUDHash which defines a CRUD model on top of Ruby's standard Hash - making it a snap to subclass and augment to fit any specific use case. - -authors: - - Trans - - Kirk Haines - - Robert Klemme - - Jan Molic - - George Moschovitis - - Jeena Paradies - - Erik Veenstra - -resources: - home: http://rubyworks.github.com/hashery - code: http://github.com/rubyworks/hashery - mail: http://groups.google.com/group/rubyworks-mailinglist - docs: http://rubydoc.info/github/rubyworks/hashery/master/frames - wiki: http://wiki.github.com/rubyworks/hashery - gems: http://rubygems.org/gems/hashery - -repositories: - upstream: "git://github.com/rubyworks/hashery.git" - -organizations: - - RubyWorks (http://rubyworks.github.com/) - -copyrights: - - 2010 Rubyworks (BSD-2-Clause) - -load_path: - - lib - - alt - -created: '2010-04-21' - diff --git a/MANIFEST b/MANIFEST deleted file mode 100644 index e31cec8..0000000 --- a/MANIFEST +++ /dev/null @@ -1,54 +0,0 @@ -#!mast -x etc .index .yardopts bin demo lib man spec test *.md *.txt *.rdoc -.index -.yardopts -demo/00_introduction.rdoc -demo/01_open_hash.rdoc -demo/02_query_hash.rdoc -demo/03_casting_hash.rdoc -demo/04_static_hash.rdoc -demo/05_key_hash.rdoc -demo/06_open_cascade.rdoc -demo/07_fuzzy_hash.rdoc -demo/08_propery_hash.rdoc -demo/10_association.rdoc -demo/applique/ae.rb -demo/applique/hashery.rb -lib/hashery/association.rb -lib/hashery/casting_hash.rb -lib/hashery/core_ext.rb -lib/hashery/crud_hash.rb -lib/hashery/dictionary.rb -lib/hashery/fuzzy_hash.rb -lib/hashery/ini_hash.rb -lib/hashery/key_hash.rb -lib/hashery/linked_list.rb -lib/hashery/lru_hash.rb -lib/hashery/open_cascade.rb -lib/hashery/open_hash.rb -lib/hashery/ordered_hash.rb -lib/hashery/path_hash.rb -lib/hashery/property_hash.rb -lib/hashery/query_hash.rb -lib/hashery/stash.rb -lib/hashery/static_hash.rb -lib/hashery.rb -lib/hashery.yml -test/case_association.rb -test/case_casting_hash.rb -test/case_core_ext.rb -test/case_crud_hash.rb -test/case_dictionary.rb -test/case_ini_hash.rb -test/case_key_hash.rb -test/case_linked_list.rb -test/case_lru_hash.rb -test/case_open_cascade.rb -test/case_open_hash.rb -test/case_property_hash.rb -test/case_query_hash.rb -test/fixture/example.ini -test/helper.rb -README.md -HISTORY.md -NOTICE.txt -LICENSE.txt diff --git a/README.md b/README.md index ba11c16..714c023 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,12 @@ # Hashery -[![Gem Version](http://img.shields.io/gem/v/hashery.svg?style=flat)](http://rubygems.org/gem/hashery) -[![Build Status](http://img.shields.io/travis/rubyworks/hashery.svg?style=flat)](http://travis-ci.org/rubyworks/hashery) -[![Fork Me](http://img.shields.io/badge/scm-github-blue.svg?style=flat)](http://github.com/rubyworks/hashery) -[![Report Issue](http://img.shields.io/github/issues/rubyworks/hashery.svg?style=flat)](http://github.com/rubyworks/hashery/issues) -[![Gittip](http://img.shields.io/badge/gittip-$1/wk-green.svg?style=flat)](https://www.gittip.com/rubyworksorg/) +[![Gem Version](https://img.shields.io/gem/v/hashery.svg?style=flat)](https://rubygems.org/gems/hashery) +[![CI](https://github.com/rubyworks/hashery/actions/workflows/ci.yml/badge.svg)](https://github.com/rubyworks/hashery/actions/workflows/ci.yml) +[![Report Issue](https://img.shields.io/github/issues/rubyworks/hashery.svg?style=flat)](https://github.com/rubyworks/hashery/issues) -[Homepage](http://rubyworks.github.com/hashery) · -[Development](http://github.com/rubyworks/hashery) · -[Report Issue](http://github.com/rubyworks/hashery/issues) · -[Chat](https://kiwiirc.com/client/irc.freenode.net/?nick=user1|?#rubyworks) +[Homepage](https://rubyworks.github.io/hashery) · +[Development](https://github.com/rubyworks/hashery) · +[Report Issue](https://github.com/rubyworks/hashery/issues) ## Description @@ -19,11 +16,10 @@ of Hash-like classes. To better support this collection of libraries it was deemed prudent to create a new project specifically for them. Hence the *Facets Hashery*. -Included in this collection are the widely used OrderedHash, -the related but more featured Dictionary class, a number -of _open_ classes similar to the standard OpenStruct, -some variations of the standard Hash class and a few -other yummy morsels. +Included in this collection are the widely used LRUHash, +the auto-sorting Dictionary class, a number of _open_ classes +similar to the standard OpenStruct, some variations of the +standard Hash class and a few other yummy morsels. ## Usage @@ -33,6 +29,36 @@ included in this collection and read the demo documents which give examples of almost all features. +### LRUHash + +`Hashery::LRUHash` is a size-limited Hash that evicts the least recently +used entry when full. It can be required on its own: + +```ruby +require 'hashery/lru_hash' + +cache = Hashery::LRUHash.new(2) +cache[:a] = 1 +cache[:b] = 2 +cache[:a] # reading :a makes it the most recently used +cache[:c] = 3 # full, so :b, the least recently used, is evicted + +cache.keys # => [:c, :a] (most recently used first) +cache.fetch(:b, 0) # => 0 +``` + +Reading with `#[]`, `#fetch`, `#assoc`, `#rassoc`, `#key` or `#values_at` +marks an entry as most recently used; `#has_key?`, `#has_value?` and iteration +do not. Like `Hash.new`, it takes an optional default value or block. Set +`#release_proc` to be told about every entry that leaves the cache: + +```ruby +cache.release_proc = ->(key, value) { value.close } +``` + +An LRUHash is not thread-safe; guard it with a `Mutex` if threads share it. + + ### Core Extensions Hashery adds four core extensions of Ruby's Hash class: `#retrieve`, @@ -45,17 +71,15 @@ sorely missing for Ruby itself, which is why they are provided here. ## Installation -To install with RubyGems simply open a console and type: +Hashery requires Ruby 2.7 or newer. To install with RubyGems simply +open a console and type: - $ sudo gem install hashery + $ gem install hashery Or add it as a dependency to your project's Gemfile: gem "hashery" -Tarball packages are available for manual site installations -via [Ruby Setup](http://rubyworks.github.com/setup). - ## Authors @@ -77,41 +101,34 @@ Well *git* in there! ### Communicating -The project is hosted on Github so the easiest means of communication -is via the [Issues](http://github.com/rubyworks/hashery/issues) page. -For more direct communication you can try the **#rubyworks** IRC channel -on **irc.freenode.net**. - -    [![IRC](https://kiwiirc.com/buttons/irc.freenode.net/rubyworks.png)](https://kiwiirc.com/client/irc.freenode.net/?nick=user1|?#rubyworks) +The project is hosted on GitHub so the easiest means of communication +is via the [Issues](https://github.com/rubyworks/hashery/issues) page. ### Testing -Hashery uses [QED](http://rubyworks.github.com/qed) and -[Lemon](http://rubyworks.github.com/lemon) test frameworks. +Hashery uses [QED](https://rubyworks.github.io/qed) and +[Lemon](https://rubyworks.github.io/lemon) test frameworks. The QED framework to create well tested high-level documentation. -Run the QED specs via: +Lemon is used to create low-level unit tests. Install the development +dependencies and run both via: + + $ bundle install + $ bundle exec rake - $ qed -Ilib demo/ +Or run the QED specs on their own via: -Lemon is used to create low-level unit tests. Run these via the Rubytest: + $ bundle exec qed -Ilib demo/ - $ rubytest -Ilib -Itest test/ +And the Lemon unit tests via Rubytest: + + $ bundle exec rubytest -Ilib -Itest test/ ### Patches -Hashery's repository is hosted on [GitHub](http://github.com/rubyworks/hashery). +Hashery's repository is hosted on [GitHub](https://github.com/rubyworks/hashery). If you'd like to offer up a fix or feature, fork the repo and submit a pull request (preferably in a topic branch). I assume you have heard -all the talk about proper [practices](https://github.com/rubyworks/rubyworks.github.com/wiki/GitHub-Best-Pactices), -so I won't bug you with it yet again. - -### Donations - -Yes, we FOSS programmers need to eat too! ;-) No seriously, any help you can -offer goes a long way toward continued development of Rubyworks projects, -including Hashery. Hop over to our [Gittips](https://www.gittip.com/rubyworksorg/) -page, or see the upper right-hand corner on the [Rubyworks](http://rubyworks.github.com) homepage. -Thanks! +all the talk about proper practices, so I won't bug you with it yet again. ## Copyrights diff --git a/Rakefile b/Rakefile index 686c329..8286c9d 100644 --- a/Rakefile +++ b/Rakefile @@ -1,20 +1,19 @@ -#!/usr/bin/env ruby +require 'bundler/gem_tasks' -#ignore 'web', 'log', 'doc', 'tmp', 'work' - -desc 'run tests' +desc 'run unit tests' task 'test' do - sh 'rubytest test/' + sh 'rubytest -Ilib -Itest test/' end desc 'run demos' task 'demo' do - sh 'qed demo/' + sh 'qed -Ilib demo/' end desc 'coverage report' task 'coverage' do - system({'p'=>'coverage'}, 'qed demo/') - system({'p'=>'coverage'}, 'rubytest test/') + system({'p'=>'coverage'}, 'qed -Ilib demo/') + system({'p'=>'coverage'}, 'rubytest -Ilib -Itest test/') end +task 'default' => ['test', 'demo'] diff --git a/hashery.gemspec b/hashery.gemspec new file mode 100644 index 0000000..6d1af19 --- /dev/null +++ b/hashery.gemspec @@ -0,0 +1,36 @@ +require_relative 'lib/hashery/version' + +Gem::Specification.new do |s| + s.name = 'hashery' + s.version = Hashery::VERSION + s.summary = 'Facets-bread collection of Hash-like classes.' + s.description = 'The Hashery is a tight collection of Hash-like classes. ' \ + 'Included among its many offerings are the auto-sorting Dictionary class, ' \ + 'the efficient LRUHash, the flexible OpenHash and the convenient KeyHash. ' \ + 'Nearly every class is a subclass of the CRUDHash which defines a CRUD model ' \ + "on top of Ruby's standard Hash making it a snap to subclass and augment to " \ + 'fit any specific use case.' + + s.authors = ['Trans', 'Kirk Haines', 'Robert Klemme', 'Jan Molic', + 'George Moschovitis', 'Jeena Paradies', 'Erik Veenstra'] + s.email = ['transfire@gmail.com'] + s.homepage = 'https://rubyworks.github.io/hashery' + s.license = 'BSD-2-Clause' + + s.metadata = { + 'homepage_uri' => s.homepage, + 'source_code_uri' => 'https://github.com/rubyworks/hashery', + 'bug_tracker_uri' => 'https://github.com/rubyworks/hashery/issues', + 'changelog_uri' => 'https://github.com/rubyworks/hashery/blob/master/HISTORY.md', + 'documentation_uri' => 'https://rubydoc.info/gems/hashery' + } + + s.required_ruby_version = '>= 2.7' + + s.files = Dir[ + 'lib/**/*.rb', 'alt/**/*.rb', 'demo/**/*', 'test/**/*', + '.yardopts', 'README.md', 'HISTORY.md', 'LICENSE.txt', 'NOTICE.txt' + ] + s.require_paths = ['lib'] + s.extra_rdoc_files = ['LICENSE.txt', 'NOTICE.txt', 'HISTORY.md', 'README.md'] +end diff --git a/lib/hashery.rb b/lib/hashery.rb index 1255296..84907e4 100644 --- a/lib/hashery.rb +++ b/lib/hashery.rb @@ -1,6 +1,4 @@ -module Hashery - VERSION = "2.1.0" -end +require 'hashery/version' require 'hashery/core_ext' diff --git a/lib/hashery.yml b/lib/hashery.yml deleted file mode 100644 index ead4e7a..0000000 --- a/lib/hashery.yml +++ /dev/null @@ -1,78 +0,0 @@ ---- -revision: 2013 -type: ruby -sources: -- Index.yml -- Gemfile -authors: -- name: Trans - email: transfire@gmail.com -- name: Kirk Haines -- name: Robert Klemme -- name: Jan Molic -- name: George Moschovitis -- name: Jeena Paradies -- name: Erik Veenstra -organizations: -- name: RubyWorks (http://rubyworks.github.com/) -requirements: -- groups: - - development - - test - version: ">= 0" - name: qed -- groups: - - development - - test - version: ">= 0" - name: lemon -- groups: - - development - - test - version: ">= 0" - name: rubytest-cli -conflicts: [] -alternatives: [] -resources: -- type: home - uri: http://rubyworks.github.com/hashery - label: Homepage -- type: code - uri: http://github.com/rubyworks/hashery - label: Source Code -- type: mail - uri: http://groups.google.com/group/rubyworks-mailinglist - label: Mailing List -- type: docs - uri: http://rubydoc.info/github/rubyworks/hashery/master/frames - label: Documentation -- type: wiki - uri: http://wiki.github.com/rubyworks/hashery - label: User Guide -- type: gems - uri: http://rubygems.org/gems/hashery -repositories: -- name: upstream - scm: git - uri: git://github.com/rubyworks/hashery.git -categories: [] -copyrights: -- holder: Rubyworks - year: '2010' - license: BSD-2-Clause -customs: [] -paths: - lib: - - lib - - alt -name: hashery -title: Hashery -version: 2.1.2 -summary: Facets-bread collection of Hash-like classes. -description: The Hashery is a tight collection of Hash-like classes. Included among - its many offerings are the auto-sorting Dictionary class, the efficient LRUHash, - the flexible OpenHash and the convenient KeyHash. Nearly every class is a subclass - of the CRUDHash which defines a CRUD model on top of Ruby's standard Hash making - it a snap to subclass and augment to fit any specific use case. -created: '2010-04-21' -date: '2016-05-01' diff --git a/lib/hashery/core_ext.rb b/lib/hashery/core_ext.rb index bdd4f5c..1968c01 100644 --- a/lib/hashery/core_ext.rb +++ b/lib/hashery/core_ext.rb @@ -9,7 +9,7 @@ class Hash # Returns a `Hash`. # def self.create(initial_hash={}, &block) - o = new &block + o = new(&block) o.update(initial_hash) o end diff --git a/lib/hashery/crud_hash.rb b/lib/hashery/crud_hash.rb index 906fb24..36f869f 100644 --- a/lib/hashery/crud_hash.rb +++ b/lib/hashery/crud_hash.rb @@ -324,7 +324,7 @@ def each #:yield: # def replace(other) super cast(other) - end + end # # Get the values at. @@ -334,7 +334,7 @@ def replace(other) # Returns `Array` of values. # def values_at(*keys) - super *keys.map{ |key| cast_key(key) } + super(*keys.map{ |key| cast_key(key) }) end # Convert CRUDHash to regular Hash. diff --git a/lib/hashery/fuzzy_hash.rb b/lib/hashery/fuzzy_hash.rb index 63a6544..4453344 100644 --- a/lib/hashery/fuzzy_hash.rb +++ b/lib/hashery/fuzzy_hash.rb @@ -177,7 +177,7 @@ def fuzz_test unless @fuzz_test @fuzz_test = Object.new @fuzz_test.instance_variable_set(:'@fuzzies', fuzzies) - method = " + method = +" def match(str) case str\n " diff --git a/lib/hashery/ini_hash.rb b/lib/hashery/ini_hash.rb index ee84f5a..121c116 100644 --- a/lib/hashery/ini_hash.rb +++ b/lib/hashery/ini_hash.rb @@ -115,7 +115,7 @@ def initialize(path, load=nil) @path = path if String === path @inihash = (Hash === path ? path.dup : {}) - if load or ( load.nil? and FileTest.readable_real? @path ) + if load or ( load.nil? and @path and FileTest.readable_real? @path ) restore() end end @@ -185,7 +185,7 @@ def to_h # Returns a string in the ini file format. # def to_s - str = "" + str = +"" inihash.each do |key, value| if value.is_a? Hash str << "[#{key.to_s}]\n" @@ -259,7 +259,7 @@ def self.read_from_file(path) # Returns a `String` with the comments from the beginning of the INI file. # def self.read_comment_from_file(path) - comment = "" + comment = +"" IO.foreach(path) do |line| line.strip! @@ -289,7 +289,7 @@ def self.write_to_file(path, inihash={}, comment=nil) File.open(path, "w") { |file| unless comment.nil? - comment.each do |line| + comment.each_line do |line| file << "# #{line}" end end diff --git a/lib/hashery/linked_list.rb b/lib/hashery/linked_list.rb index a134da7..3281276 100644 --- a/lib/hashery/linked_list.rb +++ b/lib/hashery/linked_list.rb @@ -216,7 +216,7 @@ def each # def node_delete(n) node_join(n.prev_node,n.next_node) - v = n.value + n.value end # diff --git a/lib/hashery/lru_hash.rb b/lib/hashery/lru_hash.rb index f21387b..35a50b8 100644 --- a/lib/hashery/lru_hash.rb +++ b/lib/hashery/lru_hash.rb @@ -1,11 +1,23 @@ -require 'enumerator' - module Hashery # Hash with LRU expiry policy. There are at most max_size elements in a # LRUHash. When adding more elements old elements are removed according # to LRU policy. # + # Reading an entry with #[], #fetch, #assoc, #rassoc, #key or #values_at + # marks it as the most recently used. Membership checks (#has_key?, + # #has_value?) and iteration do not. + # + # Iteration (#each, #keys, #values, etc.) runs from the most recently used + # entry to the least recently used one. + # + # The optional #release_proc is called with the key and value of every + # entry that leaves the hash, whether evicted, deleted or cleared. + # It is not called when a value is overwritten. + # + # An LRUHash is not thread-safe. Guard it with a Mutex if it is shared + # between threads. + # # Based on Robert Klemme's LRUHash class. # # LRUHash, Copyright (c) 2010 Robert Klemme. @@ -23,31 +35,46 @@ class LRUHash # # Initialize new LRUHash instance. # - # max_size - - # default_value - - # block - + # max_size - Maximum number of entries. Must be a positive integer + # (or something whose #to_i is). + # default_value - Value returned by #[] for missing keys. + # block - Default procedure called with the hash and key for + # missing keys, like Hash.new's block. # def initialize(max_size, default_value=nil, &block) @max_size = normalize_max(max_size) @default = default_value @default_proc = block - @h = {} - @head = Node.new - @tail = front(Node.new) + # Maps each key to a [key, value] pair. Hash keeps insertion order, + # so the first entry is the least recently used and the last entry + # the most recently used. Moving an entry to the end is a delete + # followed by a re-insert of the same pair. + @table = {} end # - # Iterate over each pair. + # Make a dup or clone independent of the original. + # + def initialize_copy(source) + super + @table = {} + source.instance_variable_get(:@table).each_value do |key, value| + @table[key] = [key, value] + end + end + + # + # Iterate over each pair, most recently used first. # def each_pair - if block_given? - each_node do |n| - yield [n.key, n.value] - end - else - enum_for :each_pair + return enum_for(:each_pair) { size } unless block_given? + + @table.values.reverse_each do |key, value| + yield [key, value] end + + self end # @@ -56,86 +83,105 @@ def each_pair alias each each_pair # - # Iterate over each key. + # Iterate over each key, most recently used first. # def each_key - if block_given? - each_node do |n| - yield n.key - end - else - enum_for :each_key + return enum_for(:each_key) { size } unless block_given? + + @table.values.reverse_each do |key, _value| + yield key end + + self end # - # Iterate over each value. + # Iterate over each value, most recently used first. # def each_value - if block_given? - each_node do |n| - yield n.value - end - else - enum_for :each_value + return enum_for(:each_value) { size } unless block_given? + + @table.values.reverse_each do |_key, value| + yield value end + + self end # # Size of the hash. # def size - @h.size + @table.size end + alias length size + # - # + # Is the hash empty? # def empty? - @head.succ.equal? @tail + @table.empty? end # + # Returns the value for the key, marking it most recently used. Like + # Hash#fetch, a missing key yields to the block if given, otherwise + # returns the default argument if given, otherwise raises KeyError. # - # - def fetch(key, &b) - n = @h[key] + def fetch(key, default_value=UNDEFINED) + if (pair = @table.delete(key)) + @table[pair[0]] = pair + return pair[1] + end - if n - front(n).value + if block_given? + unless UNDEFINED.equal?(default_value) + warn 'block supersedes default value argument', uplevel: 1 + end + yield key + elsif !UNDEFINED.equal?(default_value) + default_value else - (b || FETCH)[key] + raise KeyError.new("key not found: #{key.inspect}", receiver: self, key: key) end end # - # + # Returns the value for the key, marking it most recently used, or + # the default if the key is missing. # def [](key) - fetch(key) do |k| - @default_proc ? @default_proc[self, k] : default + if (pair = @table.delete(key)) + @table[pair[0]] = pair + pair[1] + elsif @default_proc + @default_proc[self, key] + else + default end end # - # + # Keys, most recently used first. # def keys - @h.keys + @table.keys.reverse! end # - # + # Values, most recently used first. # def values - @h.map {|k,n| n.value} + list = @table.map { |_key, pair| pair[1] } + list.reverse! end # - # + # Does the hash contain the key? Does not affect LRU order. # def has_key?(key) - @h.has_key? key + @table.key?(key) end alias key? has_key? @@ -143,11 +189,12 @@ def has_key?(key) alias include? has_key? # - # + # Does the hash contain the value (compared with #eql?)? + # Does not affect LRU order. # def has_value?(value) - each_pair do |k, v| - return true if value.eql? v + @table.each_value do |pair| + return true if value.eql?(pair[1]) end false @@ -155,116 +202,129 @@ def has_value?(value) alias value? has_value? + # + # Values for the given keys, as by #[]. + # def values_at(*key_list) key_list.map {|k| self[k]} end # - # + # Returns [key, value] for the key, marking it most recently used, + # or nil if missing. # def assoc(key) - n = @h[key] - - if n - front(n) - [n.key, n.value] + if (pair = @table.delete(key)) + @table[pair[0]] = pair + [pair[0], pair[1]] end end # - # + # Returns [key, value] for the most recently used entry whose value is + # #eql? to the given value, marking it most recently used, or nil. # def rassoc(value) - each_node do |n| - if value.eql? n.value - front(n) - return [n.key, n.value] + @table.values.reverse_each do |pair| + if value.eql?(pair[1]) + @table.delete(pair[0]) + @table[pair[0]] = pair + return [pair[0], pair[1]] end end + nil end # - # + # Returns the key for the given value, as by #rassoc. # def key(value) pair = rassoc(value) and pair.first end # - # + # Store a value, marking it most recently used. If the hash is full + # and the key is new, the least recently used entry is evicted first. # def store(key, value) - # same optimization as in Hash - key = key.dup.freeze if String === key && !key.frozen? - - n = @h[key] - - unless n - if size == max_size - # reuse node to optimize memory usage - n = delete_oldest - n.key = key - n.value = value - else - n = Node.new key, value - end + if (pair = @table.delete(key)) + pair[1] = value + @table[pair[0]] = pair + else + # same optimization as in Hash + key = key.dup.freeze if String === key && !key.frozen? + + evict_oldest if @table.size >= max_size - @h[key] = n + @table[key] = [key, value] end - front(n).value = value + value end alias []= store # - # + # Delete the entry, calling the release_proc. Returns the value, or, + # if the key is missing, the result of the block if given, else nil. # def delete(key) - n = @h[key] and remove_node(n).value + if (pair = @table.delete(key)) + release(pair) + pair[1] + elsif block_given? + yield key + end end # - # + # Delete every entry for which the block returns true, calling + # the release_proc for each. # def delete_if - each_node do |n| - remove_node n if yield n.key, n.value + return enum_for(:delete_if) { size } unless block_given? + + @table.values.reverse_each do |key, value| + next unless yield(key, value) + pair = @table.delete(key) + release(pair) if pair end + + self end # - # + # Change the maximum size, evicting least recently used entries + # as needed. # def max_size=(limit) limit = normalize_max(limit) while size > limit - delete_oldest + evict_oldest end @max_size = limit end # - # + # Remove all entries, least recently used first, calling the + # release_proc for each. # def clear until empty? - delete_oldest + evict_oldest end self end # - # + # String representation, like Hash#inspect, most recently used first. # def to_s - s = nil - each_pair {|k, v| (s ? (s << ', ') : s = '{') << k.to_s << '=>' << v.to_s} - s ? (s << '}') : '{}' + to_h.inspect end alias inspect to_s @@ -272,49 +332,20 @@ def to_s private # - # Iterate nodes. - # - def each_node - n = @head.succ - - until n.equal? @tail - succ = n.succ - yield n - n = succ - end - - self - end - - # - # Move node to front. - # - # node - [Node] - # - def front(node) - node.insert_after(@head) - end - - # - # Remove the node and invoke release_proc - # if set - # - # node - [Node] + # Remove the least recently used entry, returning its [key, value] pair. # - def remove_node(node) - n = @h.delete(node.key) - n.unlink - release_proc and release_proc[n.key, n.value] - n + def evict_oldest + _key, pair = @table.shift + raise "Cannot delete from empty hash" unless pair + release(pair) + pair end # - # Remove the oldest node returning the node + # Call the release_proc, if any, for a removed [key, value] pair. # - def delete_oldest - n = @tail.pred - raise "Cannot delete from empty hash" if @head.equal? n - remove_node n + def release(pair) + release_proc and release_proc[pair[0], pair[1]] end # @@ -325,38 +356,14 @@ def delete_oldest # n - [#to_i] max size # def normalize_max(n) - n = n.to_i - raise ArgumentError, 'Invalid max_size: %p' % n unless Integer === n && n > 0 - n + i = n.to_i + raise ArgumentError, 'Invalid max_size: %p' % [n] unless Integer === i && i > 0 + i end - # - FETCH = Proc.new {|k| raise KeyError, 'key not found'} - - # A single node in the doubly linked LRU list of nodes. - Node = Struct.new :key, :value, :pred, :succ do - def unlink - pred.succ = succ if pred - succ.pred = pred if succ - self.succ = self.pred = nil - self - end - - def insert_after(node) - raise 'Cannot insert after self' if equal? node - return self if node.succ.equal? self - - unlink - - self.succ = node.succ - self.pred = node - - node.succ.pred = self if node.succ - node.succ = self - - self - end - end + # Marker for an omitted argument. + UNDEFINED = Object.new.freeze + private_constant :UNDEFINED end diff --git a/lib/hashery/open_hash.rb b/lib/hashery/open_hash.rb index 3a26cac..32532b0 100644 --- a/lib/hashery/open_hash.rb +++ b/lib/hashery/open_hash.rb @@ -82,7 +82,7 @@ def open!(*methods) if @safe raise ArgumentError, "cannot set public method" unless methods.empty? else - (class << self; self; end).class_eval{ protected *methods } + (class << self; self; end).class_eval{ protected(*methods) } end methods end @@ -110,7 +110,7 @@ def open?(method) # Returns +methods+. # def close!(*methods) - (class << self; self; end).class_eval{ public *methods } + (class << self; self; end).class_eval{ public(*methods) } methods end diff --git a/lib/hashery/static_hash.rb b/lib/hashery/static_hash.rb index 55b8467..a3c8ee1 100644 --- a/lib/hashery/static_hash.rb +++ b/lib/hashery/static_hash.rb @@ -1,3 +1,5 @@ +require 'hashery/crud_hash' + module Hashery # StaticHash ia a Hash object which raises an error if any diff --git a/lib/hashery/version.rb b/lib/hashery/version.rb new file mode 100644 index 0000000..484672c --- /dev/null +++ b/lib/hashery/version.rb @@ -0,0 +1,3 @@ +module Hashery + VERSION = "2.2.0" +end diff --git a/test/case_ini_hash.rb b/test/case_ini_hash.rb index f0d2593..a3e4994 100644 --- a/test/case_ini_hash.rb +++ b/test/case_ini_hash.rb @@ -6,6 +6,30 @@ test do h = IniHash.new('foo.ini', false) end + + test "from a hash" do + h = IniHash.new('a' => '1') + h['a'].assert == '1' + end + end + + class_method :text do + test do + IniHash.text('a' => '1', 'b' => {'c' => '3'}).assert == "a=1\n[b]\nc=3\n" + end + end + + class_method :write_to_file do + test "with a comment" do + require 'tmpdir' + Dir.mktmpdir do |dir| + path = File.join(dir, 'out.ini') + IniHash.write_to_file(path, {'a' => '1'}, "one\ntwo\n") + File.read(path).assert == "# one\n# two\na=1\n" + IniHash.read_comment_from_file(path).assert == "one\ntwo\n" + IniHash.read_from_file(path).assert == {'a' => '1'} + end + end end method :[]= do diff --git a/test/case_lru_hash.rb b/test/case_lru_hash.rb index 8912a83..f60f65a 100644 --- a/test/case_lru_hash.rb +++ b/test/case_lru_hash.rb @@ -2,15 +2,51 @@ test_case LRUHash do + # Build a full hash of :a => 1, :b => 2, :c => 3, used least recently + # in that order, i.e. :a is next to be evicted. + def abc(max_size=3) + h = LRUHash.new(max_size) + h[:a] = 1 + h[:b] = 2 + h[:c] = 3 + h + end + class_method :new do - h = LRUHash.new(10) - LRUHash.assert === h + test do + h = LRUHash.new(10) + LRUHash.assert === h + end + + test "max_size is converted with #to_i" do + LRUHash.new("5").max_size.assert == 5 + LRUHash.new(2.9).max_size.assert == 2 + end + + test "max_size must be positive" do + ArgumentError.assert.raised? { LRUHash.new(0) } + ArgumentError.assert.raised? { LRUHash.new(-1) } + ArgumentError.assert.raised? { LRUHash.new(nil) } + end + + test "default value" do + h = LRUHash.new(10, :none) + h[:x].assert == :none + end end method :max_size= do test do h = LRUHash.new(10) h.max_size = 100 + h.max_size.assert == 100 + end + + test "shrinking evicts least recently used entries" do + h = abc + h[:a] + h.max_size = 1 + h.keys.assert == [:a] end end @@ -18,7 +54,35 @@ test do h = LRUHash.new(10) h.store(:a, 1) - h[:a].assert == 1 + h[:a].assert == 1 + end + + test "returns the value" do + h = LRUHash.new(10) + h.store(:a, 1).assert == 1 + end + + test "evicts the least recently used entry when full" do + h = abc + h.store(:d, 4) + h.keys.assert == [:d, :c, :b] + end + + test "overwriting a key does not evict" do + h = abc + h.store(:a, 10) + h.size.assert == 3 + h.keys.assert == [:a, :c, :b] + h[:a].assert == 10 + end + + test "unfrozen String keys are copied and frozen" do + h = LRUHash.new(10) + k = String.new("k") + h.store(k, 1) + k << "x" + h.keys.assert == ["k"] + h.keys.first.assert.frozen? end end @@ -33,6 +97,64 @@ h = LRUHash.new(10){ |h,k| h[k] = 0 } h[:a].assert == 0 end + + test "marks the entry most recently used" do + h = abc + h[:a] + h[:d] = 4 + h.keys.assert == [:d, :a, :c] + end + + test "nil values are found" do + h = LRUHash.new(10, :default) + h[:a] = nil + h[:a].assert == nil + end + end + + method :fetch do + test do + h = LRUHash.new(10) + h[:a] = 1 + h.fetch(:a).assert == 1 + end + + test "missing key raises KeyError" do + h = LRUHash.new(10) + KeyError.assert.raised? { h.fetch(:x) } + end + + test "KeyError names the key and receiver" do + h = LRUHash.new(10) + e = (h.fetch(:x) rescue $!) + KeyError.assert === e + e.message.assert == "key not found: :x" + e.key.assert == :x + e.receiver.assert.equal?(h) + end + + test "missing key with block" do + h = LRUHash.new(10) + h.fetch(:x){ |k| "no #{k}" }.assert == "no x" + end + + test "missing key with default argument" do + h = LRUHash.new(10) + h.fetch(:x, 0).assert == 0 + h.fetch(:x, nil).assert == nil + end + + test "ignores the hash default" do + h = LRUHash.new(10, :default) + KeyError.assert.raised? { h.fetch(:x) } + end + + test "marks the entry most recently used" do + h = abc + h.fetch(:a) + h[:d] = 4 + h.keys.assert == [:d, :a, :c] + end end method :empty? do @@ -42,6 +164,13 @@ end end + method :size do + test do + abc.size.assert == 3 + abc.length.assert == 3 + end + end + method :key do test do h = LRUHash.new(10) @@ -56,6 +185,12 @@ h[:a] = 1 h.keys.assert == [:a] end + + test "most recently used first" do + h = abc + h[:a] + h.keys.assert == [:a, :c, :b] + end end method :values do @@ -64,6 +199,12 @@ h[:a] = 1 h.values.assert == [1] end + + test "most recently used first" do + h = abc + h[:a] + h.values.assert == [1, 3, 2] + end end method :values_at do @@ -73,6 +214,12 @@ h[:b] = 2 h.values_at(:a).assert == [1] end + + test "missing keys give the default" do + h = LRUHash.new(10, :none) + h[:a] = 1 + h.values_at(:a, :x).assert == [1, :none] + end end method :has_key? do @@ -80,6 +227,17 @@ h = LRUHash.new(10) h[:a] = 1 h.assert.has_key?(:a) + h.assert.key?(:a) + h.assert.member?(:a) + h.assert.include?(:a) + h.refute.has_key?(:b) + end + + test "does not affect LRU order" do + h = abc + h.has_key?(:a) + h[:d] = 4 + h.refute.has_key?(:a) end end @@ -88,6 +246,7 @@ h = LRUHash.new(10) h[:a] = 1 h.assert.has_value?(1) + h.refute.has_value?(2) end end @@ -97,6 +256,7 @@ h[:a] = 1 h[:b] = 2 h.assoc(:a).assert == [:a,1] + h.assoc(:x).assert == nil end end @@ -106,6 +266,26 @@ h[:a] = 1 h[:b] = 2 h.rassoc(1).assert == [:a,1] + h.rassoc(9).assert == nil + end + end + + method :each do + test "most recently used first" do + h = abc + h[:a] + h.to_a.assert == [[:a, 1], [:c, 3], [:b, 2]] + end + + test "returns an enumerator without a block" do + Enumerator.assert === abc.each + abc.each.size.assert == 3 + end + + test "allows modification while iterating" do + h = abc + h.each { |k, v| h[k] = v * 10 } + h.values.sort.assert == [10, 20, 30] end end @@ -145,8 +325,18 @@ test do h = LRUHash.new(10) h[:a] = 1 - h.delete(:a) - h.assert.empty? + h.delete(:a).assert == 1 + h.assert.empty? + end + + test "missing key returns nil" do + h = LRUHash.new(10) + h.delete(:a).assert == nil + end + + test "missing key with block" do + h = LRUHash.new(10) + h.delete(:a){ |k| "no #{k}" }.assert == "no a" end end @@ -155,7 +345,87 @@ h = LRUHash.new(10) h[:a] = 1 h.delete_if{ |k,v| k == :a } - h.assert.empty? + h.assert.empty? + end + + test "returns self" do + h = abc + h.delete_if{ |k,v| v.odd? }.assert.equal?(h) + h.keys.assert == [:b] + end + + test "returns an enumerator without a block" do + Enumerator.assert === abc.delete_if + end + end + + method :release_proc= do + test "called for evicted, deleted and cleared entries" do + log = [] + h = LRUHash.new(2) + h.release_proc = lambda { |k, v| log << [k, v] } + h[:a] = 1 + h[:b] = 2 + h[:c] = 3 # evicts :a + h.delete(:b) + h[:d] = 4 + h.clear # least recently used first + log.assert == [[:a, 1], [:b, 2], [:c, 3], [:d, 4]] + end + + test "called when shrinking and in delete_if" do + log = [] + h = abc + h.release_proc = lambda { |k, v| log << k } + h.max_size = 2 + h.delete_if { |k, v| k == :c } + log.assert == [:a, :c] + end + + test "not called when a value is overwritten" do + log = [] + h = LRUHash.new(2) + h.release_proc = lambda { |k, v| log << k } + h[:a] = 1 + h[:a] = 2 + log.assert == [] + end + end + + method :dup do + test "copy is independent of the original" do + a = abc + b = a.dup + b[:d] = 4 + b.delete(:b) + a.to_a.assert == [[:c, 3], [:b, 2], [:a, 1]] + b.to_a.assert == [[:d, 4], [:c, 3]] + end + + test "copy keeps LRU order" do + a = abc + a[:a] + a.dup.keys.assert == [:a, :c, :b] + end + end + + method :inspect do + test "looks like a Hash, most recently used first" do + h = LRUHash.new(10) + h[:a] = "x" + h[nil] = 1 + h.inspect.assert == {nil => 1, :a => "x"}.inspect + h.to_s.assert == h.inspect + end + + test "empty" do + LRUHash.new(10).inspect.assert == "{}" + end + end + + method :to_h do + test do + abc.to_h.assert == {:a => 1, :b => 2, :c => 3} end end