Sha256: 4130a3687ac045a599bdb99d70a17ac43c7cddd7b78d19cf1fece70ab075e247

Contents?: true

Size: 843 Bytes

Versions: 5

Compression:

Stored size: 843 Bytes

Contents

module Dcha
  # :nodoc:
  class Chunk < Array
    SIZE = 128
    TAG_SIZE = 40 # SHA1

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

      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
    end

    include Comparable

    attr_reader :tag, :index, :total

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

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

    def to_s
      @buffer
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
dcha-0.1.4 lib/dcha/chunk.rb
dcha-0.1.3 lib/dcha/chunk.rb
dcha-0.1.2 lib/dcha/chunk.rb
dcha-0.1.1 lib/dcha/chunk.rb
dcha-0.1.0 lib/dcha/chunk.rb