Parent

Files

Class/Module Index [+]

Quicksearch

BinData::IO::Read

Create a new IO Read wrapper around io. io must provide read, pos if reading the current stream position and seek if setting the current stream position. If io is a string it will be automatically wrapped in an StringIO object.

The IO can handle bitstreams in either big or little endian format.

M  byte1   L      M  byte2   L
S 76543210 S      S fedcba98 S
B          B      B          B

In big endian format:

readbits(6), readbits(5) #=> [765432, 10fed]

In little endian format:

readbits(6), readbits(5) #=> [543210, a9876]

Public Class Methods

new(io) click to toggle source
# File lib/bindata/io.rb, line 30
def initialize(io)
  raise ArgumentError, "io must not be a BinData::IO::Read" if BinData::IO::Read === io

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

  @raw_io = io

  # bits when reading
  @rnbits  = 0
  @rval    = 0
  @rendian = nil

  @buffer_end_pos = nil

  extend seekable? ? SeekableStream : UnSeekableStream
end

Public Instance Methods

read_all_bytes() click to toggle source

Reads all remaining bytes from the stream.

# File lib/bindata/io.rb, line 88
def read_all_bytes
  reset_read_bits
  read
end
readbits(nbits, endian) click to toggle source

Reads exactly nbits bits from the stream. endian specifies whether the bits are stored in :big or :little endian format.

# File lib/bindata/io.rb, line 95
def readbits(nbits, endian)
  if @rendian != endian
    # don't mix bits of differing endian
    reset_read_bits
    @rendian = endian
  end

  if endian == :big
    read_big_endian_bits(nbits)
  else
    read_little_endian_bits(nbits)
  end
end
readbytes(n) click to toggle source

Reads exactly n bytes from io.

If the data read is nil an EOFError is raised.

If the data read is too short an IOError is raised.

# File lib/bindata/io.rb, line 78
def readbytes(n)
  reset_read_bits

  str = read(n)
  raise EOFError, "End of file reached" if str.nil?
  raise IOError, "data truncated" if str.size < n
  str
end
reset_read_bits() click to toggle source

Discards any read bits so the stream becomes aligned at the next byte boundary.

# File lib/bindata/io.rb, line 111
def reset_read_bits
  @rnbits = 0
  @rval   = 0
end
seekbytes(n) click to toggle source

Seek n bytes from the current position in the io stream.

# File lib/bindata/io.rb, line 68
def seekbytes(n)
  reset_read_bits
  seek(n)
end
with_buffer(n, &block) click to toggle source

Sets a buffer of n bytes on the io stream. Any reading or seeking calls inside the block will be contained within this buffer.

# File lib/bindata/io.rb, line 52
def with_buffer(n, &block)
  prev = @buffer_end_pos
  if prev
    avail = prev - offset
    n = avail if n > avail
  end
  @buffer_end_pos = offset + n
  begin
    block.call
    read
  ensure
    @buffer_end_pos = prev
  end
end

[Validate]

Generated with the Darkfish Rdoc Generator 2.