Module: MessagePack::Unpacker

Defined in:
ext/unpack.c

Overview

Deserializer class that includes Buffered API and Unbuffered API.

Buffered API uses the internal buffer of the Unpacker. Following code uses Buffered API with an input stream:

# create an unpacker with input stream.
pac = MessagePack::Unpacker.new(STDIN)

# deserialize object one after another.
pac.each {|obj|
  # ...
}

Following code doesn’t use the input stream and feeds buffer manually. This is useful to use special stream or with event-driven I/O library.

# create an unpacker without input stream.
pac = MessagePack::Unpacker.new()

# feed buffer to the internal buffer.
pac.feed(input_bytes)

# deserialize object one after another.
pac.each {|obj|
  # ...
}

You can manage the buffer manually with the combination of execute, finished?, data and reset method.

# create an unpacker.
pac = MessagePack::Unpacker.new()

# manage buffer and offset manually.
offset = 0
buffer = ''

# read some data into the buffer.
buffer << [1,2,3].to_msgpack
buffer << [4,5,6].to_msgpack

while true
  offset = pac.execute(buffer, offset)

  if pac.finished?
    obj = pac.data

    buffer.slice!(0, offset)
    offset = 0
    pac.reset

    # do something with the object
    # ...

    # repeat execution if there are more data.
    next unless buffer.empty?
  end

  break
end