Class: Bitindex::Writer

Inherits:
Object
  • Object
show all
Includes:
Common
Defined in:
lib/bitindex/writer.rb

Constant Summary

Constants included from Common

Common::SIGNED_16BIT, Common::SIGNED_32BIT, Common::UNSIGNED_16BIT, Common::UNSIGNED_32BIT

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Common

#bit_set?, #build_mask, #byte_pos, #set_bit, #unset_bit

Constructor Details

#initialize(filepath, size, opts = {}) ⇒ Writer

Returns a new instance of Writer.



9
10
11
12
13
14
15
16
17
18
# File 'lib/bitindex/writer.rb', line 9

def initialize filepath, size, opts = {}
  raise "#{ size } is invalid size" unless size and size.to_i > 0
  @size = size

  raise "#{ filepath } is invalid file" unless filepath
  @filepath = filepath

  @ltor = !(opts[:ltor] == false)
  @block_size = (opts[:block_size] and opts[:block_size].to_i > 0) ? opts[:block_size].to_i : 1024
end

Instance Attribute Details

#block_sizeObject (readonly)

Returns the value of attribute block_size.



7
8
9
# File 'lib/bitindex/writer.rb', line 7

def block_size
  @block_size
end

#filepathObject (readonly)

Returns the value of attribute filepath.



5
6
7
# File 'lib/bitindex/writer.rb', line 5

def filepath
  @filepath
end

#ltorObject (readonly)

Returns the value of attribute ltor.



6
7
8
# File 'lib/bitindex/writer.rb', line 6

def ltor
  @ltor
end

#sizeObject (readonly)

Returns the value of attribute size.



5
6
7
# File 'lib/bitindex/writer.rb', line 5

def size
  @size
end

Instance Method Details

#write(sorted) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/bitindex/writer.rb', line 20

def write sorted
  File.open(self.filepath, 'wb') do |io|
    last_num = nil
    cur_byte = 0
    cur_idx = 0
    sorted.each do |n|
      raise "values must be sorted" unless last_num.nil? or n >= last_num
      
      idx = byte_pos n
      if idx < self.size
        if idx > cur_idx
          io.putc cur_byte
          pad_to_pos io, cur_idx, idx - 1
          cur_idx = idx
          cur_byte = 0
        end

        cur_byte = set_bit cur_byte, n, self.ltor
      end          
    end

    io.putc cur_byte
    pad_to_pos io, cur_idx, self.size - 1 if cur_idx < self.size - 1
  end
end