Class: Kafka::Protocol::Decoder

Inherits:
Object
  • Object
show all
Defined in:
lib/kafka/protocol/decoder.rb

Overview

A decoder wraps an IO object, making it easy to read specific data types from it. The Kafka protocol is not self-describing, so a client must call these methods in just the right order for things to work.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io) ⇒ Decoder

Initializes a new decoder.

Parameters:

  • io (IO)

    an object that acts as an IO.



15
16
17
# File 'lib/kafka/protocol/decoder.rb', line 15

def initialize(io)
  @io = io
end

Class Method Details

.from_string(str) ⇒ Object



8
9
10
# File 'lib/kafka/protocol/decoder.rb', line 8

def self.from_string(str)
  new(StringIO.new(str))
end

Instance Method Details

#array(&block) ⇒ Array

Decodes an array from the IO object.

The provided block will be called once for each item in the array. It is the responsibility of the block to decode the proper type in the block, since there's no information that allows the type to be inferred automatically.

Returns:

  • (Array)


59
60
61
62
# File 'lib/kafka/protocol/decoder.rb', line 59

def array(&block)
  size = int32
  size.times.map(&block)
end

#bytesString

Decodes a list of bytes from the IO object.

Returns:

  • (String)


80
81
82
83
84
85
86
87
88
# File 'lib/kafka/protocol/decoder.rb', line 80

def bytes
  size = int32

  if size == -1
    nil
  else
    read(size)
  end
end

#eof?Boolean

Returns:

  • (Boolean)


19
20
21
# File 'lib/kafka/protocol/decoder.rb', line 19

def eof?
  @io.eof?
end

#int16Integer

Decodes a 16-bit integer from the IO object.

Returns:

  • (Integer)


33
34
35
# File 'lib/kafka/protocol/decoder.rb', line 33

def int16
  read(2).unpack("s>").first
end

#int32Integer

Decodes a 32-bit integer from the IO object.

Returns:

  • (Integer)


40
41
42
# File 'lib/kafka/protocol/decoder.rb', line 40

def int32
  read(4).unpack("l>").first
end

#int64Integer

Decodes a 64-bit integer from the IO object.

Returns:

  • (Integer)


47
48
49
# File 'lib/kafka/protocol/decoder.rb', line 47

def int64
  read(8).unpack("q>").first
end

#int8Integer

Decodes an 8-bit integer from the IO object.

Returns:

  • (Integer)


26
27
28
# File 'lib/kafka/protocol/decoder.rb', line 26

def int8
  read(1).unpack("C").first
end

#read(number_of_bytes) ⇒ String

Reads the specified number of bytes from the IO object, returning them as a String.

Returns:

  • (String)


94
95
96
# File 'lib/kafka/protocol/decoder.rb', line 94

def read(number_of_bytes)
  @io.read(number_of_bytes) or raise EOFError
end

#stringString

Decodes a string from the IO object.

Returns:

  • (String)


67
68
69
70
71
72
73
74
75
# File 'lib/kafka/protocol/decoder.rb', line 67

def string
  size = int16

  if size == -1
    nil
  else
    read(size)
  end
end