Class: BinData::IO::Write

Inherits:
Object
  • Object
show all
Defined in:
lib/bindata/io.rb

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

Constructor Details

#initialize(io) ⇒ Write

Returns a new instance of Write.



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/bindata/io.rb', line 271

def initialize(io)
  if BinData::IO::Write === io
    raise ArgumentError, "io must not be a BinData::IO::Write"
  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

  @wnbits  = 0
  @wval    = 0
  @wendian = nil

  @write_count = 0

  @bytes_remaining = nil
end

Instance Method Details

#flushbitsObject Also known as: flush

To be called after all writebits have been applied.



343
344
345
346
347
348
349
# File 'lib/bindata/io.rb', line 343

def flushbits
  raise "Internal state error nbits = #{@wnbits}" if @wnbits >= 8

  if @wnbits > 0
    writebits(0, 8 - @wnbits, @wendian)
  end
end

#offsetObject

Returns the current offset of the io stream. Offset will be rounded up when writing bitfields.



314
315
316
# File 'lib/bindata/io.rb', line 314

def offset
  @write_count + (@wnbits > 0 ? 1 : 0)
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.



296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/bindata/io.rb', line 296

def with_buffer(n, &block)
  prev = @bytes_remaining
  if prev
    n = prev if n > prev
    prev -= n
  end

  @bytes_remaining = n
  begin
    block.call
    write_raw("\0" * @bytes_remaining)
  ensure
    @bytes_remaining = prev
  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.



326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/bindata/io.rb', line 326

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.



319
320
321
322
# File 'lib/bindata/io.rb', line 319

def writebytes(str)
  flushbits
  write_raw(str)
end