Class: QQWry::Database
- Inherits:
-
Object
- Object
- QQWry::Database
- Defined in:
- lib/qqwry/database.rb
Instance Method Summary collapse
- #each ⇒ Object
-
#initialize(file = 'QQWrt.Dat') ⇒ Database
constructor
A new instance of Database.
- #query(ip) ⇒ Object
- #version ⇒ Object
Constructor Details
#initialize(file = 'QQWrt.Dat') ⇒ Database
Returns a new instance of Database.
20 21 22 23 24 25 26 27 28 |
# File 'lib/qqwry/database.rb', line 20 def initialize(file = 'QQWrt.Dat') if file.respond_to?(:to_str) @file = File.new(file.to_str) else @file = file @file.seek(0) end @header = QQWry::Header.read(@file) end |
Instance Method Details
#each ⇒ Object
30 31 32 33 34 35 36 37 38 39 |
# File 'lib/qqwry/database.rb', line 30 def each offset = @header.index_offset_start while offset <= @header.index_offset_end @file.seek(offset) index = QQWry::Index.read(@file) record = QQWry::Record.new(index.ip_start, @file, index.record_offset) yield record offset += QQWry::Index::SIZE end end |
#query(ip) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/qqwry/database.rb', line 49 def query(ip) if ip.respond_to?(:to_str) ip = ip.to_str.split('.').collect{|i| i.to_i}.pack('C4').unpack('N')[0] end raise ArgumentError, "invalid IP" unless (0...(1 << 32)).include?(ip) @file.seek(QQWry::Header::SIZE) low = 0 # the end record is the version info start = @header.index_offset_start high = (@header.index_offset_end - start) / QQWry::Index::SIZE while low <= high middle = (low + high) / 2 @file.seek(start + middle * QQWry::Index::SIZE) index = QQWry::Index.read(@file) if ip > index.ip_start low = middle + 1 elsif ip < index.ip_start high = middle - 1 else return QQWry::Record.new(index.ip_start, @file, index.record_offset) end end @file.seek(start + high * QQWry::Index::SIZE) index = QQWry::Index.read(@file) QQWry::Record.new(index.ip_start, @file, index.record_offset) end |