Sha256: 4c654ed1d7078ea40198c3fbc4bf186a0f611adaf95d6eb6ff213eb0ab990ddf

Contents?: true

Size: 1.44 KB

Versions: 7

Compression:

Stored size: 1.44 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 max_size= size
        return if size < 1

        @max_size = size
        return if @max_size >= @data.length

        @data.keys[0..(@max_size - @data.length)].each do |k|
          @data.delete(k)
        end
      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

7 entries across 7 versions & 1 rubygems

Version Path
contrast-agent-3.10.2 lib/contrast/utils/cache.rb
contrast-agent-3.10.1 lib/contrast/utils/cache.rb
contrast-agent-3.10.0 lib/contrast/utils/cache.rb
contrast-agent-3.9.1 lib/contrast/utils/cache.rb
contrast-agent-3.9.0 lib/contrast/utils/cache.rb
contrast-agent-3.8.5 lib/contrast/utils/cache.rb
contrast-agent-3.8.4 lib/contrast/utils/cache.rb