Class: RecordSearch::Search

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

Constant Summary collapse

INDEX_SIZE =

TODO is there a sizeof(long) ?

4

Instance Method Summary collapse

Constructor Details

#initialize(db, db_idx = nil) ⇒ Search

Returns a new Search object. db is the file having the data used for your searches. db_idx is the index created with RecordSearch#index if it’s nil, it will construct a filename appending ‘.idx’ to the value db has.



11
12
13
14
15
16
17
# File 'lib/recordsearch/search.rb', line 11

def initialize(db, db_idx=nil)
  @db = File.open(db, 'r')
  db_idx = db + '.idx' if db_idx.nil?
  @db_idx = File.open(db_idx, 'r')
  @db_size = File.stat(db_idx).size / INDEX_SIZE
  @db_pos = 0
end

Instance Method Details

#closeObject

Close the files.



20
21
22
23
24
# File 'lib/recordsearch/search.rb', line 20

def close
  @db.close
  @db_idx.close
  @db = @db_idx = nil
end

#search(key) ⇒ Object

Searches object key in the file using binary search. If found returns what your implementation of parse returned, nil otherwise.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/recordsearch/search.rb', line 28

def search(key)
  from = 0
  to = @db_size - 1

  pivot = nil
  while from < to
    middle = ((from + to) / 2).to_i

    pivot = read(middle)

    if lt(key, pivot)
      to = middle
      next
    elsif gt(key, pivot)
      from = middle + 1
      next
    end

    result = nil
    result = pivot if eq(key, pivot)
    return result
  end

  if from == to
    pivot = read(from)
    return pivot if eq(pivot, pivot)
  end
end