Class: PBIO::Delimited

Inherits:
Object
  • Object
show all
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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io) ⇒ Delimited

Returns a new instance of Delimited.

Parameters:

  • io (IO)

    object



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

#ioObject (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.

Parameters:

  • num (Integer)

    number

Returns:

  • (Array<Byte>)

    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.

Parameters:

  • io (IO)

    stream

Returns:

  • (Integer)

    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.

Returns:

  • (Boolean)

    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.

Parameters:

  • msg (Protobuf::Message)

    the message



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