class MiniMime::Db::RandomAccessDb

Constants

MAX_CACHED

Public Class Methods

new(path, sort_order) click to toggle source
# File lib/mini_mime.rb, line 97
def initialize(path, sort_order)
  @path = path
  @file = File.open(@path)

  @row_length = @file.readline.length
  @file_length = File.size(@path)
  @rows = @file_length / @row_length

  @hit_cache = Cache.new(MAX_CACHED)
  @miss_cache = Cache.new(MAX_CACHED)

  @sort_order = sort_order
end

Public Instance Methods

lookup(val) click to toggle source
# File lib/mini_mime.rb, line 111
def lookup(val)
  @hit_cache.fetch(val) do
    @miss_cache.fetch(val) do
      data = lookup_uncached(val)
      if data
        @hit_cache[val] = data
      else
        @miss_cache[val] = nil
      end

      data
    end
  end
end
lookup_uncached(val) click to toggle source

lifted from marcandre/backports

# File lib/mini_mime.rb, line 127
def lookup_uncached(val)
  from = 0
  to = @rows - 1
  result = nil

  while from <= to do
    midpoint = from + (to - from).div(2)
    current = resolve(midpoint)
    data = current[@sort_order]
    if data > val
      to = midpoint - 1
    elsif data < val
      from = midpoint + 1
    else
      result = current
      break
    end
  end
  result
end
resolve(row) click to toggle source
# File lib/mini_mime.rb, line 148
def resolve(row)
  @file.seek(row * @row_length)
  Info.new(@file.readline)
end