Sha256: 97f665fd788e131420faa5e42452e7ad074595c4f601f69ea9f0b82453b08791

Contents?: true

Size: 995 Bytes

Versions: 176

Compression:

Stored size: 995 Bytes

Contents

module Tins
  class Bijection < Hash
    def self.[](*pairs)
      pairs.size % 2 == 0 or
        raise ArgumentError, "odd number of arguments for #{self}"
      new.fill do |obj|
        (pairs.size / 2).times do |i|
          j = 2 * i
          key = pairs[j]
          value = pairs[j + 1]
          obj.key?(key) and raise ArgumentError, "duplicate key #{key.inspect} for #{self}"
          obj.inverted.key?(value) and raise ArgumentError, "duplicate value #{value.inspect} for #{self}"
          obj[pairs[j]] = pairs[j + 1]
        end
      end
    end

    def initialize(inverted = Bijection.new(self))
      @inverted = inverted
    end

    def fill
      if empty?
        yield self
        freeze
      end
      self
    end

    def freeze
      r = super
      unless @inverted.frozen?
        @inverted.freeze
      end
      r
    end

    def []=(key, value)
      key?(key) and return
      super
      @inverted[value] = key
    end

    attr_reader :inverted
  end
end

Version data entries

176 entries across 158 versions & 9 rubygems

Version Path
tins-0.4.0 lib/tins/bijection.rb
tins-0.3.14 lib/tins/bijection.rb
tins-0.3.13 lib/tins/bijection.rb
tins-0.3.12 lib/tins/bijection.rb
tins-0.3.11 lib/tins/bijection.rb
tins-0.3.10 lib/tins/bijection.rb
tins-0.3.9 lib/tins/bijection.rb
tins-0.3.8 lib/tins/bijection.rb
tins-0.3.7 lib/tins/bijection.rb
tins-0.3.6 lib/tins/bijection.rb
tins-0.3.5 lib/tins/bijection.rb
tins-0.3.4 lib/tins/bijection.rb
tins-0.3.3 lib/tins/bijection.rb
tins-0.3.2 lib/tins/bijection.rb
tins-0.3.1 lib/tins/bijection.rb
tins-0.3.0 lib/tins/bijection.rb