Sha256: 758850f9bad06a0076656cf6c05706e0a273695b505ff034b95ad7e4b83c0e03

Contents?: true

Size: 953 Bytes

Versions: 6

Compression:

Stored size: 953 Bytes

Contents

class FormatParser::ReadLimiter
  NO_LIMIT = nil

  class BudgetExceeded < StandardError
  end

  def initialize(io, max_bytes: NO_LIMIT, max_reads: NO_LIMIT, max_seeks: NO_LIMIT)
    @max_bytes = max_bytes
    @max_reads = max_reads
    @max_seeks = max_seeks

    @io = io
    @seeks = 0
    @reads = 0
    @bytes = 0
  end

  def size
    @io.size
  end

  def pos
    @io.pos
  end

  def seek(to_offset)
    @seeks += 1
    if @max_seeks && @seeks > @max_seeks
      raise BudgetExceeded, "Seek budget exceeded (%d seeks performed)" % @max_seeks
    end
    @io.seek(to_offset)
  end

  def size
    @io.size
  end

  def read(n)
    @bytes += n
    @reads += 1

    if @max_bytes && @bytes > @max_bytes
      raise BudgetExceeded, "Read bytes budget (%d) exceeded" % @max_bytes
    end

    if @max_reads && @reads > @max_reads
      raise BudgetExceeded, "Number of read() calls exceeded (%d max)" % @max_reads
    end

    @io.read(n)
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
format_parser-0.2.0 lib/read_limiter.rb
format_parser-0.1.7 lib/read_limiter.rb
format_parser-0.1.6 lib/read_limiter.rb
format_parser-0.1.5 lib/read_limiter.rb
format_parser-0.1.4 lib/read_limiter.rb
format_parser-0.1.3 lib/read_limiter.rb