Class: Torrenter::TorrentReader::PieceConstructor

Inherits:
Object
  • Object
show all
Defined in:
lib/torrenter/torrent_reader/piece_constructor.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(files, folder, sha_hashes, piece_length) ⇒ PieceConstructor

Returns a new instance of PieceConstructor.



6
7
8
9
10
11
12
# File 'lib/torrenter/torrent_reader/piece_constructor.rb', line 6

def initialize(files, folder, sha_hashes, piece_length)
  @files        = files
  @folder       = folder
  @sha_hashes   = sha_hashes
  @piece_length = piece_length
  @index        = PieceIndex.new(piece_length)
end

Instance Attribute Details

#indexObject (readonly)

Returns the value of attribute index.



5
6
7
# File 'lib/torrenter/torrent_reader/piece_constructor.rb', line 5

def index
  @index
end

Instance Method Details

#final_piece?Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/torrenter/torrent_reader/piece_constructor.rb', line 18

def final_piece?
  index_length == @index.size + 1
end

#index_lengthObject



14
15
16
# File 'lib/torrenter/torrent_reader/piece_constructor.rb', line 14

def index_length
  @sha_hashes.size / 20
end

#make_indexObject



22
23
24
25
26
27
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
56
# File 'lib/torrenter/torrent_reader/piece_constructor.rb', line 22

def make_index
  @piece = Piece.new(@piece_length)
  @files.each do |file|
    path = "#{@folder}/#{file['path'].join('/')}"
    offset = 0
    if @piece.tally != 0
      if @piece.left > file['length']
        @piece.add(0...file['length'], path)
      else
        offset = @piece.left
        @piece.add(0...@piece.left, path)
      end

      @index << @piece if @piece.full?
    else
      offset = 0
    end

    while offset < ((file['length']) - @piece_length)
      @piece = Piece.new(@piece_length)
      @piece.add(offset...(offset += @piece_length), path)
      @index << @piece if @piece.full?
    end

    if @piece.full? && offset > 0
      @piece = Piece.new(@piece_length)
      @piece.add(offset...file['length'], path)
    end

    if final_piece?
      @index << @piece
    end
  end
  set_hash
end

#piece_hash(n) ⇒ Object



67
68
69
# File 'lib/torrenter/torrent_reader/piece_constructor.rb', line 67

def piece_hash(n)
  @sha_hashes[(n * 20)...(n * 20) + 20]
end

#set_hashObject



58
59
60
61
62
63
64
65
# File 'lib/torrenter/torrent_reader/piece_constructor.rb', line 58

def set_hash
  0.upto(@index.size - 1) do |i|
    @index[i].hash = piece_hash(i)
    @index[i].index = i
  end

  return @index
end