summaryrefslogtreecommitdiff
path: root/lib/racc/iset.rb
blob: 339221d21bc5f009f14febf0eda850b4062a9957 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#--
#
#
#
# Copyright (c) 1999-2006 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
# see the file "COPYING".
#
#++

module Racc

  # An "indexed" set.  All items must respond to :ident.
  class ISet

    def initialize(a = [])
      @set = a
    end

    attr_reader :set

    def add(i)
      @set[i.ident] = i
    end

    def [](key)
      @set[key.ident]
    end

    def []=(key, val)
      @set[key.ident] = val
    end

    alias include? []
    alias key? []

    def update(other)
      s = @set
      o = other.set
      o.each_index do |idx|
        if t = o[idx]
          s[idx] = t
        end
      end
    end

    def update_a(a)
      s = @set
      a.each {|i| s[i.ident] = i }
    end

    def delete(key)
      i = @set[key.ident]
      @set[key.ident] = nil
      i
    end

    def each(&block)
      @set.compact.each(&block)
    end

    def to_a
      @set.compact
    end

    def to_s
      "[#{@set.compact.join(' ')}]"
    end

    alias inspect to_s

    def size
      @set.nitems
    end

    def empty?
      @set.nitems == 0
    end

    def clear
      @set.clear
    end

    def dup
      ISet.new(@set.dup)
    end

  end   # class ISet

end   # module Racc