Sha256: 9c90fd77478f4a3f7598ac4190f0b9b16ea910a67ac0ff76f8cb13abd607bf2f

Contents?: true

Size: 922 Bytes

Versions: 4

Compression:

Stored size: 922 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 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

4 entries across 4 versions & 1 rubygems

Version Path
format_parser-0.3.3 lib/read_limiter.rb
format_parser-0.3.2 lib/read_limiter.rb
format_parser-0.3.1 lib/read_limiter.rb
format_parser-0.3.0 lib/read_limiter.rb