Sha256: 4002abba5a4b2654208e96a5dc0eb040edf29cbe266e9bf081546e40ba2eaae7

Contents?: true

Size: 851 Bytes

Versions: 5

Compression:

Stored size: 851 Bytes

Contents

module FormatParser::IOUtils
  class InvalidRead < ArgumentError
  end

  class MalformedFile < ArgumentError
  end

  def safe_read(io, n)
    raise ArgumentError, 'Unbounded reads are not supported' if n.nil?
    buf = io.read(n)

    unless buf
      raise InvalidRead, "We wanted to read #{n} bytes from the IO, but the IO is at EOF"
    end
    if buf.bytesize != n
      raise InvalidRead, "We wanted to read #{n} bytes from the IO, but we got #{buf.bytesize} instead"
    end

    buf
  end

  def safe_skip(io, n)
    raise ArgumentError, 'Unbounded skips are not supported' if n.nil?

    return if n == 0

    raise InvalidRead, 'Negative skips are not supported' if n < 0

    if io.respond_to?(:pos)
      io.seek(io.pos + n)
    else
      safe_read(io, n)
    end
    nil
  end

  ### TODO: Some kind of built-in offset for the read
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
format_parser-0.7.0 lib/io_utils.rb
format_parser-0.6.0 lib/io_utils.rb
format_parser-0.5.2 lib/io_utils.rb
format_parser-0.5.1 lib/io_utils.rb
format_parser-0.5.0 lib/io_utils.rb