Class: Dcha::Chunk

Inherits:
Array
  • Object
show all
Includes:
Comparable
Defined in:
lib/dcha/chunk.rb

Overview

:nodoc:

Constant Summary collapse

SIZE =
128
TAG_SIZE =

SHA1

40

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bytes) ⇒ Chunk

Returns a new instance of Chunk.



27
28
29
30
31
32
33
# File 'lib/dcha/chunk.rb', line 27

def initialize(bytes)
  super
  @tag = bytes.shift(TAG_SIZE).pack('C*')
  @index = bytes.shift
  @total = bytes.shift
  @buffer = bytes.pack('C*')
end

Instance Attribute Details

#indexObject (readonly)

Returns the value of attribute index.



25
26
27
# File 'lib/dcha/chunk.rb', line 25

def index
  @index
end

#tagObject (readonly)

Returns the value of attribute tag.



25
26
27
# File 'lib/dcha/chunk.rb', line 25

def tag
  @tag
end

#totalObject (readonly)

Returns the value of attribute total.



25
26
27
# File 'lib/dcha/chunk.rb', line 25

def total
  @total
end

Class Method Details

.create(data) ⇒ Object



8
9
10
# File 'lib/dcha/chunk.rb', line 8

def create(data)
  split(data).map { |bytes| new bytes }
end

.split(data) ⇒ Object



12
13
14
15
16
17
18
19
20
# File 'lib/dcha/chunk.rb', line 12

def split(data)
  buffer = Oj.dump(data)
  tag = Digest::SHA1.hexdigest(buffer).unpack('C*')
  slices = buffer.unpack('C*').each_slice(SIZE)
  size = slices.size
  slices.map.with_index do |bytes, index|
    [tag, index, size, bytes].flatten
  end
end

Instance Method Details

#<=>(other) ⇒ Object



35
36
37
# File 'lib/dcha/chunk.rb', line 35

def <=>(other)
  index <=> other.index
end

#to_sObject



39
40
41
# File 'lib/dcha/chunk.rb', line 39

def to_s
  @buffer
end