Sha256: 4a5f43f3ff50d24b370246023f7af698f7e5e86b00d4f97675d0a6d380584423

Contents?: true

Size: 845 Bytes

Versions: 9

Compression:

Stored size: 845 Bytes

Contents

module FormatParser::IOUtils
  class InvalidRead < ArgumentError
  end

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

    if !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)
    if n.nil?
      raise ArgumentError, "Unbounded skips are not supported"
    end

    return if n == 0

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

    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

9 entries across 9 versions & 1 rubygems

Version Path
format_parser-0.2.0 lib/io_utils.rb
format_parser-0.1.7 lib/io_utils.rb
format_parser-0.1.6 lib/io_utils.rb
format_parser-0.1.5 lib/io_utils.rb
format_parser-0.1.4 lib/io_utils.rb
format_parser-0.1.3 lib/io_utils.rb
format_parser-0.1.2 lib/io_utils.rb
format_parser-0.1.1 lib/io_utils.rb
format_parser-0.1.0 lib/io_utils.rb