Sha256: 55ccca8645fe042e829a4e7f90f96ac299373a8af339752ff5f91720c2899447

Contents?: true

Size: 1.21 KB

Versions: 4

Compression:

Stored size: 1.21 KB

Contents

# Copyright (c) 2020 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
# frozen_string_literal: true

module Contrast
  module Utils
    # Implementation taken from http://stackoverflow.com/questions/1933866/efficient-ruby-lru-cache
    class Cache
      def initialize max_size = 1000
        @max_size = max_size
        @data = {}
      end

      def [] key
        found = true
        value = @data.delete(key) { found = false }
        @data[key] = value if found
      end

      def []= key, value
        @data.delete(key)
        @data[key] = value
        @data.delete(@data.first[0]) if @data.length > @max_size

        value # rubocop:disable Lint/Void
      end

      def each
        @data.reverse_each do |pair|
          yield pair
        end
      end

      # used further up the chain, non thread safe each
      alias_method :each_unsafe, :each

      def to_a
        @data.to_a.reverse
      end

      def delete key
        @data.delete(key)
      end

      def clear
        @data.clear
      end

      def count
        @data.count
      end

      # for cache validation only, ensures all is sound
      def valid?
        true
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
contrast-agent-3.12.2 lib/contrast/utils/cache.rb
contrast-agent-3.12.1 lib/contrast/utils/cache.rb
contrast-agent-3.12.0 lib/contrast/utils/cache.rb
contrast-agent-3.11.0 lib/contrast/utils/cache.rb