File: hash_counter.rb

package info (click to toggle)
ruby-webmock 3.25.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,172 kB
  • sloc: ruby: 12,829; makefile: 6
file content (45 lines) | stat: -rw-r--r-- 779 bytes parent folder | download
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
# frozen_string_literal: true

require 'thread'

module WebMock
  module Util
    class HashCounter
      attr_accessor :hash

      def initialize
        self.hash = Hash.new(0)
        @order = {}
        @max = 0
        @lock = ::Mutex.new
      end

      def put(key, num=1)
        @lock.synchronize do
          hash[key] += num
          @order[key] = @max += 1
        end
      end

      def get(key)
        @lock.synchronize do
          hash[key]
        end
      end

      def select(&block)
        return unless block_given?

        @lock.synchronize do
          hash.select(&block)
        end
      end

      def each(&block)
        @order.to_a.sort_by { |a| a[1] }.each do |a|
          yield(a[0], hash[a[0]])
        end
      end
    end
  end
end