class PBIO::Delimited
Delimited
contains write and read methods to consume and generate delimited protobuf IO streams.
Attributes
io[R]
Public Class Methods
encode_uvarint(num)
click to toggle source
@param [Integer] num number @return [Array<Byte>] uvarint byte array
# File lib/pbio/delimited.rb, line 7 def self.encode_uvarint(num) bytes = [] while num >= 0x80 b = num & 0xFF | 0x80 bytes << b num >>= 7 end bytes << num bytes.pack('c*') end
new(io)
click to toggle source
@param [IO] io object
# File lib/pbio/delimited.rb, line 37 def initialize(io) @io = io if @io.respond_to?(:binmode) @io.binmode elsif @io.respond_to?(:set_encoding) @io.set_encoding(Encoding::BINARY) end end
read_uvarint(io)
click to toggle source
@param [IO] io stream @return [Integer] decoded number
# File lib/pbio/delimited.rb, line 20 def self.read_uvarint(io) num = shift = 0 io.each_byte do |b| if b < 0x80 num |= b << shift break end num |= (b & 0x7f) << shift shift += 7 end num end
Public Instance Methods
eof?()
click to toggle source
@return [Boolean] EOF status
# File lib/pbio/delimited.rb, line 61 def eof? io.respond_to?(:eof?) && io.eof? end
read(klass)
click to toggle source
Reads the next message
# File lib/pbio/delimited.rb, line 55 def read(klass) size = Delimited.read_uvarint(io) klass.decode io.read(size) unless size.zero? end
write(msg)
click to toggle source
Writes a message to the IO stream. @param [Protobuf::Message] msg the message
# File lib/pbio/delimited.rb, line 48 def write(msg) payload = msg.to_proto size = Delimited.encode_uvarint(payload.bytesize) io.write(size) + io.write(payload) end