Class: Spandx::Core::IndexFile

Inherits:
Object
  • Object
show all
Defined in:
lib/spandx/core/index_file.rb

Constant Summary collapse

UINT_32_DIRECTIVE =
'V'
UINT_32_SIZE =
4

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data_file) ⇒ IndexFile

Returns a new instance of IndexFile.



11
12
13
14
15
# File 'lib/spandx/core/index_file.rb', line 11

def initialize(data_file)
  @data_file = data_file
  @path = Pathname.new("#{data_file.absolute_path}.idx")
  @entries = size.positive? ? Array.new(size) : []
end

Instance Attribute Details

#data_fileObject (readonly)

Returns the value of attribute data_file.



9
10
11
# File 'lib/spandx/core/index_file.rb', line 9

def data_file
  @data_file
end

#pathObject (readonly)

Returns the value of attribute path.



9
10
11
# File 'lib/spandx/core/index_file.rb', line 9

def path
  @path
end

Instance Method Details

#eachObject



17
18
19
20
21
22
# File 'lib/spandx/core/index_file.rb', line 17

def each
  total = path.size / UINT_32_SIZE
  total.times do |n|
    yield position_for(n)
  end
end

#position_for(row_number) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/spandx/core/index_file.rb', line 43

def position_for(row_number)
  return if row_number > size

  entry = entries[row_number]
  return entry if entry

  bytes = IO.binread(path, UINT_32_SIZE, offset_for(row_number))
  entry = bytes.unpack1(UINT_32_DIRECTIVE)
  entries[row_number] = entry
  entry
end

#search(min: 0, max: size) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/spandx/core/index_file.rb', line 24

def search(min: 0, max: size)
  scan do |reader|
    until min >= max
      mid = mid_for(min, max)
      row = reader.row(mid)
      return unless row

      comparison = yield row
      return row if comparison.zero?

      comparison.positive? ? (min = mid + 1) : (max = mid)
    end
  end
end

#sizeObject



39
40
41
# File 'lib/spandx/core/index_file.rb', line 39

def size
  path.exist? ? path.size / UINT_32_SIZE : 0
end

#update!Object



55
56
57
58
59
60
# File 'lib/spandx/core/index_file.rb', line 55

def update!
  return unless data_file.exist?

  sort(data_file)
  rebuild_index!
end