Sha256: aca83ebfd8d76162d79c12796b9606fb19046401961e189aeaa2bda3ca78ce51

Contents?: true

Size: 1.12 KB

Versions: 3

Compression:

Stored size: 1.12 KB

Contents

require 'ddtrace/utils/sequence'

module Datadog
  module Utils
    # Acts as a unique dictionary of objects
    class ObjectSet
      # You can provide a block that defines how the key
      # for this message type is resolved.
      def initialize(seed = 0, &block)
        @sequence = Utils::Sequence.new(seed)
        @items = {}
        @key_block = block
      end

      # Submit an array of arguments that define the message.
      # If they match an existing message, it will return the
      # matching object. If it doesn't match, it will yield to
      # the block with the next ID & args given.
      def fetch(*args, &block)
        key = @key_block ? @key_block.call(*args) : args.hash
        # TODO: Ruby 2.0 doesn't like yielding here... switch when 2.0 is dropped.
        # rubocop:disable Performance/RedundantBlockCall
        @items[key] ||= block.call(@sequence.next, *args)
        # rubocop:enable Performance/RedundantBlockCall
      end

      def length
        @items.length
      end

      def objects
        @items.values
      end

      def freeze
        super
        @items.freeze
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
ddtrace-0.49.0 lib/ddtrace/utils/object_set.rb
ddtrace-0.48.0 lib/ddtrace/utils/object_set.rb
ddtrace-0.47.0 lib/ddtrace/utils/object_set.rb