Class: MiniMime::Db::RandomAccessDb

Inherits:
Object
  • Object
show all
Defined in:
lib/mini_mime.rb

Constant Summary collapse

MAX_CACHED =
100

Instance Method Summary collapse

Constructor Details

#initialize(path, sort_order) ⇒ RandomAccessDb

Returns a new instance of RandomAccessDb.



97
98
99
100
101
102
103
104
105
106
107
108
109
# 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

Instance Method Details

#lookup(val) ⇒ Object



111
112
113
114
115
116
117
118
119
120
121
122
123
124
# 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) ⇒ Object

lifted from marcandre/backports



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# 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) ⇒ Object



148
149
150
151
# File 'lib/mini_mime.rb', line 148

def resolve(row)
  @file.seek(row * @row_length)
  Info.new(@file.readline)
end