Purpose
The streaming unpacker allows incremental parsing of MessagePack data as it becomes available.
References
-
IO streaming guide - Working with streams
-
API reference - Unpacker class documentation
Concepts
Feeding data incrementally
unpacker = Messagepack::Unpacker.new
unpacker.feed("\x81") # Feed partial data
unpacker.feed("\xA3") # Feed more
unpacker.feed("foo") # Feed final part
obj = unpacker.read # => {"foo"=>nil}Where,
-
Unpacker.newcreates a new unpacker instance -
feed(data)appends data to the buffer -
readreturns one complete object ornilif more data is needed
Examples
Example 1. Streaming unpacking from network
require 'socket'
# Simulate receiving data in chunks
unpacker = Messagepack::Unpacker.new
chunks = ["\x81\xA3", "foo", "\xA5", "world"]
chunks.each do |chunk|
unpacker.feed(chunk)
obj = unpacker.read
if obj
puts "Received: #{obj.inspect}"
else
puts "Waiting for more data..."
end
end
# Output:
# Waiting for more data...
# Waiting for more data...
# Waiting for more data...
# Received: {"foo"=>"world"}