Sha256: c73318f581efad420a872ea2fcd016854946db9ecd6a5b3d49a312b7e3b976f1

Contents?: true

Size: 994 Bytes

Versions: 8

Compression:

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

  def reset_limits!
    @seeks = 0
    @reads = 0
    @bytes = 0
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
format_parser-0.7.0 lib/read_limiter.rb
format_parser-0.6.0 lib/read_limiter.rb
format_parser-0.5.2 lib/read_limiter.rb
format_parser-0.5.1 lib/read_limiter.rb
format_parser-0.5.0 lib/read_limiter.rb
format_parser-0.4.0 lib/read_limiter.rb
format_parser-0.3.5 lib/read_limiter.rb
format_parser-0.3.4 lib/read_limiter.rb