class MiniMime::Db::RandomAccessDb

def initialize(path, sort_order)

def initialize(path, sort_order)
  @path = path
  @file = PReadFile.new(@path)
  @row_length = @file.readline("\n").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

def lookup(val)

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

def lookup_uncached(val)

lifted from marcandre/backports
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

def resolve(row)

def resolve(row)
  Info.new(@file.pread(@row_length, row * @row_length).force_encoding(Encoding::UTF_8))
end