Class: DatxRuby::District

Inherits:
Object
  • Object
show all
Includes:
Common
Defined in:
lib/datx_ruby/district.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Common

#datx, #datx_path, #index_size

Constructor Details

#initializeDistrict

Returns a new instance of District.



7
8
9
10
# File 'lib/datx_ruby/district.rb', line 7

def initialize
  @data = IO.binread(datx)
  @index_size = Util.bytes2long(@data[0], @data[1], @data[2], @data[3])
end

Class Method Details

.datax_path=(path) ⇒ Object



12
13
14
# File 'lib/datx_ruby/district.rb', line 12

def self.datax_path=(path)
  $datx_path ||= path
end

Instance Method Details

#find(ip) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/datx_ruby/district.rb', line 16

def find(ip)
  raise "Invalid IP address" unless ::IPAddr.new(ip).ipv4?

  low = 0
  high = (index_size - 262148 - 262144) / 13 - 1
  val = Util.ip2long(ip)

  while low <= high do
    mid = (low + high) / 2
    pos = mid * 13 + 262148

    starts = Util.bytes2long(@data[pos], @data[pos + 1], @data[pos + 2], @data[pos + 3])
    ends = Util.bytes2long(@data[pos+4], @data[pos + 5], @data[pos + 6], @data[pos + 7])

    if val > ends
      low = mid + 1
    elsif val < starts
      high = mid - 1
    else
      off = Util.bytes2long(@data[pos + 11], @data[pos + 10], @data[pos + 9], @data[pos + 8])
      l = @data[pos + 12].to_i
      pos = off - 262144 + index_size

      tmp = @data[pos...pos + l].force_encoding('utf-8')
      return tmp.split("\t")
    end
  end

end