Sha256: 8cfd351b2e19d70238d7b7ac8ee4fd22242cc0dc54a994810701cc918dc2bbda

Contents?: true

Size: 800 Bytes

Versions: 2

Compression:

Stored size: 800 Bytes

Contents

require "strscan"

class Fossyl::Parser
  attr_reader :scanner

  def initialize(string)
    @scanner = StringScanner.new(string)
  end

  def parse
    return parse_bytes      if scanner.scan(/\d+/)
    return parse_integer    if scanner.scan(/i/)
    return parse_list       if scanner.scan(/l/)
    return parse_dictionary if scanner.scan(/d/)

    raise Fossyl::InvalidBencoding
  end

  private
  def parse_bytes
    length = scanner.matched.to_i
    scanner.get_byte # Skip the ':'
    length.times.map { scanner.get_byte }.join
  end

  def parse_integer
    scanner.scan_until(/e/).chop.to_i
  end

  def parse_list
    list = []
    list << parse until scanner.scan(/e/)
    list
  end

  def parse_dictionary
    hash = {}
    hash[parse] = parse until scanner.scan(/e/)
    hash
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
fossyl-0.6.1 lib/fossyl/parser.rb
fossyl-0.6.0 lib/fossyl/parser.rb