Class: MaxMindDB::LowMemoryReader

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

Constant Summary collapse

METADATA_MAX_SIZE =
128 * 1024

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ LowMemoryReader

Returns a new instance of LowMemoryReader.



8
9
10
11
# File 'lib/maxminddb/reader.rb', line 8

def initialize(path)
  @mutex = Mutex.new
  @file = File.open(path, 'rb')
end

Instance Method Details

#[](pos, length = 1) ⇒ Object



13
14
15
# File 'lib/maxminddb/reader.rb', line 13

def [](pos, length=1)
  atomic_read(length, pos)
end

#atomic_read(length, pos) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/maxminddb/reader.rb', line 25

def atomic_read(length, pos)
  # Prefer `pread` in environments where it is available. `pread` provides
  # atomic file access across processes.
  if @file.respond_to?(:pread)
    @file.pread(length, pos)
  else
    @mutex.synchronize do
      @file.seek(pos)
      @file.read(length)
    end
  end
end

#rindex(search) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/maxminddb/reader.rb', line 17

def rindex(search)
  base = [0, @file.size - METADATA_MAX_SIZE].max
  tail = atomic_read(METADATA_MAX_SIZE, base)
  pos = tail.rindex(search)
  return nil if pos.nil?
  base + pos
end