Class: VinaryTree::Liblevenshtein::Query

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/vinary_tree/liblevenshtein.rb

Constant Summary collapse

BATCH_SIZE =
256

Instance Method Summary collapse

Constructor Details

#initialize(pointer) ⇒ Query

Returns a new instance of Query.



158
159
160
161
162
163
# File 'lib/vinary_tree/liblevenshtein.rb', line 158

def initialize(pointer)
  @box = [pointer]
  @claimed = false
  @mutex = Mutex.new
  ObjectSpace.define_finalizer(self, Finalizer.for(@box, proc { |value| Native.llev_query_cursor_free(value) }))
end

Instance Method Details

#closeObject



191
192
193
194
195
196
197
198
# File 'lib/vinary_tree/liblevenshtein.rb', line 191

def close
  @mutex.synchronize do
    return if @box[0].zero?
    Liblevenshtein.check(Native.llev_query_cursor_free(@box[0]))
    @box[0] = 0
    ObjectSpace.undefine_finalizer(self)
  end
end

#eachObject



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/vinary_tree/liblevenshtein.rb', line 165

def each
  return enum_for(__method__) unless block_given?
  @mutex.synchronize do
    raise IOError, "query is one-shot" if @claimed
    @claimed = true
  end
  begin
    loop do
      batch = Native::Batch.malloc
      status = Native.llev_query_cursor_next_batch(@box[0], BATCH_SIZE, batch)
      break if status == END_STATUS
      Liblevenshtein.check(status)
      begin
        batch.len.times do |index|
          item = Native::Match.new(batch.matches + index * Native::Match.size)
          yield materialize(item)
        end
      ensure
        Liblevenshtein.check(Native.llev_query_cursor_release_batch(@box[0], batch.generation))
      end
    end
  ensure
    close
  end
end