module BinData::IO::Common

Common operations for both Read and Write.

Public Class Methods

new(io) click to toggle source
# File lib/bindata/io.rb, line 10
def initialize(io)
  if self.class === io
    raise ArgumentError, "io must not be a #{self.class}"
  end

  # wrap strings in a StringIO
  if io.respond_to?(:to_str)
    io = BinData::IO.create_string_io(io.to_str)
  end

  @raw_io = io
  @buffer_end_pos = nil

  extend seekable? ? SeekableStream : UnSeekableStream
  stream_init
end

Private Instance Methods

buffer_limited_n(n) click to toggle source
# File lib/bindata/io.rb, line 40
def buffer_limited_n(n)
  if @buffer_end_pos
    if n.nil? or n > 0
      max = @buffer_end_pos[1] - offset
      n = max if n.nil? or n > max
    else
      min = @buffer_end_pos[0] - offset
      n = min if n < min
    end
  end

  n
end
seek(n) click to toggle source
# File lib/bindata/io.rb, line 36
def seek(n)
  seek_raw(buffer_limited_n(n))
end
seekable?() click to toggle source
# File lib/bindata/io.rb, line 30
def seekable?
  @raw_io.pos
rescue NoMethodError, Errno::ESPIPE, Errno::EPIPE
  nil
end
with_buffer_common(n, &block) click to toggle source
# File lib/bindata/io.rb, line 54
def with_buffer_common(n, &block)
  prev = @buffer_end_pos
  if prev
    avail = prev[1] - offset
    n = avail if n > avail
  end
  @buffer_end_pos = [offset, offset + n]
  begin
    block.call(*@buffer_end_pos)
  ensure
    @buffer_end_pos = prev
  end
end