Class: PBIO::Delimited
- Inherits:
-
Object
- Object
- PBIO::Delimited
- Defined in:
- lib/pbio/delimited.rb
Overview
Delimited contains write and read methods to consume and generate delimited protobuf IO streams.
Instance Attribute Summary collapse
-
#io ⇒ Object
readonly
Returns the value of attribute io.
Class Method Summary collapse
-
.encode_uvarint(num) ⇒ Array<Byte>
Uvarint byte array.
-
.read_uvarint(io) ⇒ Integer
Decoded number.
Instance Method Summary collapse
-
#eof? ⇒ Boolean
EOF status.
-
#initialize(io) ⇒ Delimited
constructor
A new instance of Delimited.
-
#read(klass) ⇒ Object
Reads the next message.
-
#write(msg) ⇒ Object
Writes a message to the IO stream.
Constructor Details
#initialize(io) ⇒ Delimited
Returns a new instance of Delimited.
37 38 39 40 41 42 43 44 |
# 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 |
Instance Attribute Details
#io ⇒ Object (readonly)
Returns the value of attribute io.
34 35 36 |
# File 'lib/pbio/delimited.rb', line 34 def io @io end |
Class Method Details
.encode_uvarint(num) ⇒ Array<Byte>
Returns uvarint byte array.
7 8 9 10 11 12 13 14 15 16 |
# 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 |
.read_uvarint(io) ⇒ Integer
Returns decoded number.
20 21 22 23 24 25 26 27 28 29 30 31 32 |
# 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 |
Instance Method Details
#eof? ⇒ Boolean
Returns EOF status.
61 62 63 |
# File 'lib/pbio/delimited.rb', line 61 def eof? io.respond_to?(:eof?) && io.eof? end |
#read(klass) ⇒ Object
Reads the next message
55 56 57 58 |
# 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) ⇒ Object
Writes a message to the IO stream.
48 49 50 51 52 |
# 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 |