Class: BinData::IO::Write
Overview
Create a new IO Write wrapper around io
. io
must provide #write. 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.
See IO::Read for more information.
Instance Method Summary collapse
-
#flushbits ⇒ Object
(also: #flush)
To be called after all
writebits
have been applied. -
#initialize(io) ⇒ Write
constructor
A new instance of Write.
-
#offset ⇒ Object
Returns the current offset of the io stream.
-
#seekbytes(n) ⇒ Object
Seek
n
bytes from the current position in the io stream. -
#with_buffer(n, &block) ⇒ Object
Sets a buffer of
n
bytes on the io stream. -
#writebits(val, nbits, endian) ⇒ Object
Writes
nbits
bits fromval
to the stream. -
#writebytes(str) ⇒ Object
Writes the given string of bytes to the io stream.
Constructor Details
#initialize(io) ⇒ Write
Returns a new instance of Write.
375 376 377 378 379 380 381 |
# File 'lib/bindata/io.rb', line 375 def initialize(io) super(io) @wnbits = 0 @wval = 0 @wendian = nil end |
Instance Method Details
#flushbits ⇒ Object Also known as: flush
To be called after all writebits
have been applied.
431 432 433 434 435 436 437 |
# File 'lib/bindata/io.rb', line 431 def flushbits raise "Internal state error nbits = #{@wnbits}" if @wnbits >= 8 if @wnbits > 0 writebits(0, 8 - @wnbits, @wendian) end end |
#offset ⇒ Object
Returns the current offset of the io stream. Offset will be rounded up when writing bitfields.
396 397 398 |
# File 'lib/bindata/io.rb', line 396 def offset offset_raw + (@wnbits > 0 ? 1 : 0) end |
#seekbytes(n) ⇒ Object
Seek n
bytes from the current position in the io stream.
401 402 403 404 |
# File 'lib/bindata/io.rb', line 401 def seekbytes(n) flushbits seek(n) end |
#with_buffer(n, &block) ⇒ Object
Sets a buffer of n
bytes on the io stream. Any writes inside the block
will be contained within this buffer. If less than n
bytes are written inside the block, the remainder will be padded with ‘0’ bytes.
387 388 389 390 391 392 |
# File 'lib/bindata/io.rb', line 387 def with_buffer(n, &block) with_buffer_common(n) do |buf_start, buf_end| block.call write("\0" * (buf_end - offset)) end end |
#writebits(val, nbits, endian) ⇒ Object
Writes nbits
bits from val
to the stream. endian
specifies whether the bits are to be stored in :big
or :little
endian format.
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 |
# File 'lib/bindata/io.rb', line 414 def writebits(val, nbits, endian) if @wendian != endian # don't mix bits of differing endian flushbits @wendian = endian end clamped_val = val & mask(nbits) if endian == :big write_big_endian_bits(clamped_val, nbits) else write_little_endian_bits(clamped_val, nbits) end end |
#writebytes(str) ⇒ Object
Writes the given string of bytes to the io stream.
407 408 409 410 |
# File 'lib/bindata/io.rb', line 407 def writebytes(str) flushbits write(str) end |