Class: QuartzTorrent::RegionMap

Inherits:
Object
  • Object
show all
Defined in:
lib/quartz_torrent/regionmap.rb

Overview

This class is used to map consecutive integer regions to objects. The lowest end of the lowest region is assumed to be 0.

Instance Method Summary collapse

Constructor Details

#initializeRegionMap

Returns a new instance of RegionMap.



46
47
48
49
# File 'lib/quartz_torrent/regionmap.rb', line 46

def initialize
  @map = []
  @sorted = false
end

Instance Method Details

#[](i) ⇒ Object



107
108
109
# File 'lib/quartz_torrent/regionmap.rb', line 107

def [](i)
  at(i)
end

#add(regionEnd, obj) ⇒ Object

Add a region that ends at the specified ‘regionEnd’ with the associated ‘obj’



52
53
54
55
# File 'lib/quartz_torrent/regionmap.rb', line 52

def add(regionEnd, obj)
  @map.push [regionEnd, obj]
  @sorted = false
end

#at(i) ⇒ Object

For the region with index i, return an array of the form [value, left, right]



96
97
98
99
100
101
102
103
104
105
# File 'lib/quartz_torrent/regionmap.rb', line 96

def at(i)
  return nil if @map.length == 0
  if i == 0
    left = 0
  else
    left = @map[i-1][0]+1
  end

  [@map[i][1],left,@map[i][0]]
end

#find(value) ⇒ Object

Given a value, return a list of the form [index, value, left, right, offset] where index is the zero-based index in this map of the region, value is the associated object, left is the lowest value in the region, right is the highest, and offset is the offset within the region of the value.



80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/quartz_torrent/regionmap.rb', line 80

def find(value)
  
  index = findIndex(value)
  return nil if ! index
  result = at(index)

  if index == 0
    offset = value
  else
    offset = value - result[1]
  end
  
  [index, result[0], result[1], result[2], offset]
end

#findIndex(value) ⇒ Object



67
68
69
70
71
72
73
74
# File 'lib/quartz_torrent/regionmap.rb', line 67

def findIndex(value)
  if ! @sorted
    @map.sort{ |a,b| a[0] <=> b[0] }
    @sorted = true
  end
  
  @map.binsearch_index{|x| x[0] >= value}
end

#findValue(value) ⇒ Object

Given an integer value, find which region it falls in and return the object associated with that region.



58
59
60
61
62
63
64
65
# File 'lib/quartz_torrent/regionmap.rb', line 58

def findValue(value)
  if ! @sorted
    @map.sort{ |a,b| a[0] <=> b[0] }
    @sorted = true
  end
  
  @map.binsearch{|x| x[0] >= value}[1]
end

#lastObject

For the final region, return an array of the form [index, value, left, right]



117
118
119
120
121
122
123
124
125
# File 'lib/quartz_torrent/regionmap.rb', line 117

def last
  return nil if ! @map.last
  if @map.length == 1
    left = 0
  else
    left = @map[@map.length-2][0]+1
  end
  [@map.length-1,@map.last[1],left,@map.last[0]]
end

#maxIndexObject

Return the rightmost index of the final region, or -1 if no regions have been added.



112
113
114
# File 'lib/quartz_torrent/regionmap.rb', line 112

def maxIndex
  @map.size-1
end