Sha256: e1645271d3bd4b991bfc1b91c44d40ce2bb4316a5d6eab12407312e8b2dabbfa

Contents?: true

Size: 1.62 KB

Versions: 10

Compression:

Stored size: 1.62 KB

Contents

# frozen_string_literal: true

module OpenAssets
  MARKER = "\x4f\x41"
  VERSION = "\x01\x00"

  # the open assets payload
  class Payload
    attr_accessor :quantities
    attr_accessor :metadata

    def initialize(quantities = [], metadata = '')
      @quantities = quantities
      @metadata = metadata
    end

    # parse open assets payload
    # @return [Payload] a open assets payload object, if payload is invalid, return nil.
    def self.parse_from_payload(payload)
      buf = StringIO.new(payload)
      marker = buf.read(2)
      version = buf.read(2)
      return nil if marker != MARKER || version != VERSION
      count = Tapyrus.unpack_var_int_from_io(buf)
      return nil unless count
      quantities = []
      count.times { quantities << LEB128.decode_unsigned(buf, buf.pos) }
      metadata_length = Tapyrus.unpack_var_int_from_io(buf)
      return nil if metadata_length.nil? || buf.length < metadata_length + buf.pos
      metadata = buf.read(metadata_length).each_byte.map(&:chr).join
      new(quantities, metadata)
    rescue StandardError
      # LEB128#decode_unsigned raise 'undefined method `unpack' for nil:NilClass'
      # for invalid format such as "018f8f" (the most significant bit of the last byte should be 0)
      nil
    end

    # generate binary payload
    def to_payload
      payload = String.new
      payload << MARKER
      payload << VERSION
      payload << Tapyrus.pack_var_int(quantities.size) << quantities.map { |q| LEB128.encode_unsigned(q).read }.join
      payload << Tapyrus.pack_var_int(metadata.length) << metadata.bytes.map { |b| sprintf('%02x', b) }.join.htb
      payload
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
tapyrus-0.3.4 lib/openassets/payload.rb
tapyrus-0.3.3 lib/openassets/payload.rb
tapyrus-0.3.2 lib/openassets/payload.rb
tapyrus-0.3.1 lib/openassets/payload.rb
tapyrus-0.3.0 lib/openassets/payload.rb
tapyrus-0.2.13 lib/openassets/payload.rb
tapyrus-0.2.12 lib/openassets/payload.rb
tapyrus-0.2.10 lib/openassets/payload.rb
tapyrus-0.2.9 lib/openassets/payload.rb
tapyrus-0.2.8 lib/openassets/payload.rb