Skip to content

Enumerable methods

Jacob edited this page Aug 24, 2016 · 1 revision

Methods that are implemented by including Enumerable will enumerate from a byte buffer's current position up to its limit, incrementing the position on each iteration.

bb = ByteBuffer.new(10)
bb.write 0_u8..9_u8
bb.position = 3
bb.limit = 6
bb.each { |byte| puts byte }
# 3
# 4
# 5
bb.remaining # => 0

Calling each without a block will return a BufferIterator(UInt8). Iterating it will increment the position of the byte buffer it was created from, and calling rewind on it will set it to the position it had when the iterator was created.

bb = ByteBuffer.new(16)
bb.write UInt8[1, 2, 3, 4, 5]
bb.flip
bb.position = 2
iter = bb.each
iter.next # => 3
iter.next # => 4
iter.rewind
iter.next # => 3
iter.rewind
iter.cycle.first(10).to_a # => [3, 4, 5, 3, 4, 5, 3, 4, 5, 3]

BufferIterator has three methods to get the next value:

  • next() returns the next value or returns Iterator::Stop. It's better suited to be used by other iterator methods.
  • next?() returns the next value or returns nil.
  • next!() returns the next value or raises IO::EOFError.

Like methods to read numbers, each (with or without a block) accepts Number types as an argument. This allows to iterate in terms of that type instead of bytes.

bb = ByteBuffer.new(16)
4.times { |i| bb.write((i + 1) * 10) }
bb.flip
iter = bb.each(Int32) # => ByteBuffer::BufferIterator(Int32)
iter.to_a # => [10, 20, 30, 40]
Clone this wiki locally