Module: FormatParser::IOUtils

Defined Under Namespace

Classes: InvalidRead, MalformedFile

Instance Method Summary collapse

Instance Method Details

#safe_read(io, n) ⇒ Object

Raises:

  • (ArgumentError)


8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/io_utils.rb', line 8

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

#safe_skip(io, n) ⇒ Object

Raises:

  • (ArgumentError)


22
23
24
25
26
27
28
29
30
31
# File 'lib/io_utils.rb', line 22

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

  io.seek(io.pos + n)
  nil
end