| 1 | #!/bin/ruby -Ku |
|---|
| 2 | # Copyright(c) 2007 URABE, Shyouhei. |
|---|
| 3 | # |
|---|
| 4 | # Permission is hereby granted, free of charge, to any person obtaining a copy |
|---|
| 5 | # of this code, to deal in the code without restriction, including without |
|---|
| 6 | # limitation the rights to use, copy, modify, merge, publish, distribute, |
|---|
| 7 | # sublicense, and/or sell copies of the code, and to permit persons to whom the |
|---|
| 8 | # code is furnished to do so, subject to the following conditions: |
|---|
| 9 | # |
|---|
| 10 | # The above copyright notice and this permission notice shall be |
|---|
| 11 | # included in all copies or substantial portions of the code. |
|---|
| 12 | # |
|---|
| 13 | # THE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
|---|
| 14 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
|---|
| 15 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
|---|
| 16 | # AUTHOR OR COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
|---|
| 17 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
|---|
| 18 | # OUT OF OR IN CONNECTION WITH THE CODE OR THE USE OR OTHER DEALINGS IN THE |
|---|
| 19 | # CODE. |
|---|
| 20 | |
|---|
| 21 | class Memoize |
|---|
| 22 | def initialize |
|---|
| 23 | @forward = Hash.new |
|---|
| 24 | @reverse = Hash.new do |h, k| h.store k, Array.new end |
|---|
| 25 | @key_finalizer = lambda do |i| @forward.delete i end |
|---|
| 26 | @value_finalizer = lambda do |i| |
|---|
| 27 | @reverse.delete(i).each do |j| |
|---|
| 28 | @forward.delete j |
|---|
| 29 | end |
|---|
| 30 | end |
|---|
| 31 | end |
|---|
| 32 | |
|---|
| 33 | def fetch k |
|---|
| 34 | e = GC.disable |
|---|
| 35 | j = @forward.fetch k.object_id do |
|---|
| 36 | return yield k |
|---|
| 37 | end |
|---|
| 38 | return ObjectSpace._id2ref j |
|---|
| 39 | ensure |
|---|
| 40 | GC.enable unless e |
|---|
| 41 | end |
|---|
| 42 | |
|---|
| 43 | def store k, v |
|---|
| 44 | i = k.object_id |
|---|
| 45 | j = v.object_id |
|---|
| 46 | ObjectSpace.define_finalizer k, @key_finalizer |
|---|
| 47 | ObjectSpace.define_finalizer v, @value_finalizer |
|---|
| 48 | @reverse[j].push i |
|---|
| 49 | @forward.store i, j |
|---|
| 50 | end |
|---|
| 51 | end |
|---|
| 52 | |
|---|
| 53 | |
|---|
| 54 | # Local Variables: |
|---|
| 55 | # mode: ruby |
|---|
| 56 | # coding: utf-8 |
|---|
| 57 | # indent-tabs-mode: t |
|---|
| 58 | # tab-width: 3 |
|---|
| 59 | # ruby-indent-level: 3 |
|---|
| 60 | # fill-column: 79 |
|---|
| 61 | # default-justification: full |
|---|
| 62 | # End: |
|---|
| 63 | # vi: ts=3 sw=3 |
|---|