rybakit/msgpack
A pure PHP implementation of the MessagePack serialization format.
Maintainers
Fund package maintenance!
Requires
- php: ^8.2
Requires (Dev)
- ext-decimal: *
- ext-gmp: *
- friendsofphp/php-cs-fixer: ^3
- phpunit/phpunit: ^11
- vimeo/psalm: ^5 || ^6
Suggests
- ext-decimal: For converting overflowed integers to Decimal objects
- ext-gmp: For converting overflowed integers to GMP objects
Provides
None
Conflicts
None
Replaces
None
MIT 17fdc1e09f986181850dcfef4851a03ea6539e95
- Eugene Leonovich <gen.work.woop@gmail.com>
This package is auto-updated.
Last update: 2026-06-17 23:49:45 UTC
README
👁 Quality Assurance
👁 Code Coverage
👁 Mentioned in Awesome PHP
A pure PHP implementation of the MessagePack serialization format.
Features
- Fully compliant with the latest MessagePack specification
- Supports streaming unpacking
- Supports unsigned 64-bit integers handling
- Supports object serialization
- Fully tested
- Relatively fast
Table of contents
Installation
The recommended way to install the library is through Composer:
composer require rybakit/msgpack
Usage
Packing
To pack values, you can either use an instance of a Packer:
$packer = new Packer(); $packed = $packer->pack($value);
or call a static method on the MessagePack class:
$packed = MessagePack::pack($value);
In the examples above, the method pack automatically packs a value depending on its type. However, not all PHP types
can be uniquely translated to MessagePack types. For example, the MessagePack format defines map and array types,
which are represented by a single array type in PHP. By default, the packer will pack a PHP array as a MessagePack
array if it has sequential numeric keys starting from 0, and as a MessagePack map otherwise:
$mpArr1 = $packer->pack([1, 2]); // MP array [1, 2] $mpArr2 = $packer->pack([0 => 1, 1 => 2]); // MP array [1, 2] $mpMap1 = $packer->pack([0 => 1, 2 => 3]); // MP map {0: 1, 2: 3} $mpMap2 = $packer->pack([1 => 2, 2 => 3]); // MP map {1: 2, 2: 3} $mpMap3 = $packer->pack(['a' => 1, 'b' => 2]); // MP map {a: 1, b: 2}
However, sometimes you need to pack a sequential array as a MessagePack map.
To do this, use the packMap method:
$mpMap = $packer->packMap([1, 2]); // {0: 1, 1: 2}
Here is a list of type-specific packing methods:
$packer->packNil(); // MP nil $packer->packBool(true); // MP bool $packer->packInt(42); // MP int $packer->packFloat(M_PI); // MP float (32 or 64) $packer->packFloat32(M_PI); // MP float 32 $packer->packFloat64(M_PI); // MP float 64 $packer->packStr('foo'); // MP str $packer->packBin("\x80"); // MP bin $packer->packArray([1, 2]); // MP array $packer->packMap(['a' => 1]); // MP map $packer->packExt(1, "\xaa"); // MP ext
Check the "Custom types" section below on how to pack custom types.
Packing options
The Packer object supports a number of bitmask-based options for fine-tuning
the packing process (defaults are in bold):
| Name | Description |
|---|---|
FORCE_STR |
Forces PHP strings to be packed as MessagePack UTF-8 strings |
FORCE_BIN |
Forces PHP strings to be packed as MessagePack binary data |
DETECT_STR_BIN |
Detects MessagePack str/bin type automatically |
FORCE_ARR |
Forces PHP arrays to be packed as MessagePack arrays |
FORCE_MAP |
Forces PHP arrays to be packed as MessagePack maps |
DETECT_ARR_MAP |
Detects MessagePack array/map type automatically |
FORCE_FLOAT32 |
Forces PHP floats to be packed as 32-bits MessagePack floats |
FORCE_FLOAT64 |
Forces PHP floats to be packed as 64-bits MessagePack floats |
The type detection mode (
DETECT_STR_BIN/DETECT_ARR_MAP) adds some overhead which can be noticed when you pack large (16- and 32-bit) arrays or strings. However, if you know the value type in advance (for example, you only work with UTF-8 strings or/and associative arrays), you can eliminate this overhead by forcing the packer to use the appropriate type, which will save it from running the auto-detection routine. Another option is to explicitly specify the value type. The library provides 2 auxiliary classes for this,MapandBin. Check the "Custom types" section below for details.
Examples:
// detect str/bin type and pack PHP 64-bit floats (doubles) to MP 32-bit floats $packer = new Packer(PackOptions::DETECT_STR_BIN | PackOptions::FORCE_FLOAT32); // these will throw MessagePack\Exception\InvalidOptionException $packer = new Packer(PackOptions::FORCE_STR | PackOptions::FORCE_BIN); $packer = new Packer(PackOptions::FORCE_FLOAT32 | PackOptions::FORCE_FLOAT64);
Unpacking
To unpack data, you can either use an instance of a BufferUnpacker:
$unpacker = new BufferUnpacker(); $unpacker->reset($packed); $value = $unpacker->unpack();
or call a static method on the MessagePack class:
$value = MessagePack::unpack($packed);
If the packed data is received in chunks (e.g. when reading from a stream), use the tryUnpack method, which attempts
to unpack the data and returns an array of unpacked messages (if any) instead of throwing an InsufficientDataException:
while ($chunk = ...) { $unpacker->append($chunk); if ($messages = $unpacker->tryUnpack()) { return $messages; } }
If you want to unpack from a specific position in a buffer, use seek:
$unpacker->seek(42); // set position equal to 42 bytes $unpacker->seek(-8); // set position to 8 bytes before the end of the buffer
To skip bytes from the current position, use skip:
$unpacker->skip(10); // set position to 10 bytes ahead of the current position
To get the number of remaining (unread) bytes in the buffer:
$unreadBytesCount = $unpacker->getRemainingCount();
To check whether the buffer has unread data:
$hasUnreadBytes = $unpacker->hasRemaining();
If needed, you can remove already read data from the buffer by calling:
$releasedBytesCount = $unpacker->release();
With the read method you can read raw (packed) data:
$packedData = $unpacker->read(2); // read 2 bytes
Besides the above methods BufferUnpacker provides type-specific unpacking methods, namely:
$unpacker->unpackNil(); // PHP null $unpacker->unpackBool(); // PHP bool $unpacker->unpackInt(); // PHP int $unpacker->unpackFloat(); // PHP float $unpacker->unpackStr(); // PHP UTF-8 string $unpacker->unpackBin(); // PHP binary string $unpacker->unpackArray(); // PHP sequential array $unpacker->unpackMap(); // PHP associative array $unpacker->unpackExt(); // PHP MessagePack\Type\Ext object
Unpacking options
The BufferUnpacker object supports a number of bitmask-based options for fine-tuning
the unpacking process (defaults are in bold):
| Name | Description |
|---|---|
BIGINT_AS_STR |
Converts overflowed integers to strings [1] |
BIGINT_AS_GMP |
Converts overflowed integers to GMP objects [2] |
BIGINT_AS_DEC |
Converts overflowed integers to Decimal\Decimal objects [3] |
1. The binary MessagePack format has unsigned 64-bit as its largest integer data type, but PHP does not support such integers, which means that an overflow can occur during unpacking.
2. Make sure the GMP extension is enabled.
3. Make sure the Decimal extension is enabled.
Examples:
$packedUint64 = "\xcf"."\xff\xff\xff\xff"."\xff\xff\xff\xff"; $unpacker = new BufferUnpacker($packedUint64); var_dump($unpacker->unpack()); // string(20) "18446744073709551615" $unpacker = new BufferUnpacker($packedUint64, UnpackOptions::BIGINT_AS_GMP); var_dump($unpacker->unpack()); // object(GMP) {...} $unpacker = new BufferUnpacker($packedUint64, UnpackOptions::BIGINT_AS_DEC); var_dump($unpacker->unpack()); // object(Decimal\Decimal) {...}
Custom types
In addition to the basic types, the library provides functionality to serialize and deserialize arbitrary types. This can be done in several ways, depending on your use case. Let's take a look at them.
Type objects
If you need to serialize an instance of one of your classes into one of the basic MessagePack types, the best way
to do this is to implement the CanBePacked interface in the class. A good example of such
a class is the Map type class that comes with the library. This type is useful when you want to explicitly specify
that a given PHP array should be packed as a MessagePack map without triggering an automatic type detection routine:
$packer = new Packer(); $packedMap = $packer->pack(new Map([1, 2, 3])); $packedArray = $packer->pack([1, 2, 3]);
More type examples can be found in the src/Type directory.
Type transformers
As with type objects, type transformers are only responsible for serializing values. They should be used when you need to serialize a value that does not implement the CanBePacked interface. Examples of such values include instances of built-in or third-party classes that you do not own, or non-objects such as resources.
A transformer class must implement the CanPack interface. To use a transformer,
it must first be registered in the packer. Here is an example of how to serialize PHP streams into
the MessagePack bin format type using one of the supplied transformers, StreamTransformer:
$packer = new Packer(null, [new StreamTransformer()]); $packedBin = $packer->pack(fopen('/path/to/file', 'r+'));
More type transformer examples can be found in the src/TypeTransformer directory.
Extensions
In contrast to the cases described above, extensions are intended to handle extension types and are responsible for both serialization and deserialization of values (types).
An extension class must implement the Extension interface. To use an extension, it must first be registered in the packer and the unpacker.
The MessagePack specification divides extension types into two groups: predefined and application-specific. Currently, there is only one predefined type in the specification, Timestamp.
Timestamp
The Timestamp extension type is a predefined
type. Support for this type in the library is done through the TimestampExtension class. This class is responsible
for handling Timestamp objects, which represent the number of seconds and optional adjustment in nanoseconds:
$timestampExtension = new TimestampExtension(); $packer = new Packer(); $packer = $packer->extendWith($timestampExtension); $unpacker = new BufferUnpacker(); $unpacker = $unpacker->extendWith($timestampExtension); $packedTimestamp = $packer->pack(Timestamp::now()); $timestamp = $unpacker->reset($packedTimestamp)->unpack(); $seconds = $timestamp->getSeconds(); $nanoseconds = $timestamp->getNanoseconds();
When using the MessagePack class, the Timestamp extension is already registered:
$packedTimestamp = MessagePack::pack(Timestamp::now()); $timestamp = MessagePack::unpack($packedTimestamp);
Application-specific extensions
In addition, the format can be extended with your own types. For example, to make the built-in PHP DateTime objects
first-class citizens in your code, you can create a corresponding extension, as shown in the example.
Please note that custom extensions must be registered with a unique extension ID (an integer from 0 to 127).
More extension examples can be found in the examples/MessagePack directory.
To learn more about how extension types can be useful, check out this article.
Exceptions
If an error occurs during packing/unpacking, a PackingFailedException or an UnpackingFailedException
will be thrown, respectively. In addition, an InsufficientDataException can be thrown during unpacking.
An InvalidOptionException will be thrown in case an invalid option (or a combination of mutually
exclusive options) is used.
Tests
Run tests as follows:
vendor/bin/phpunit
Also, if you already have Docker installed, you can run the tests in a Docker container. First, create a container:
./dockerfile.sh | docker build -t msgpack -
The command above will create a container named msgpack with PHP 8.4 runtime. You may change the default runtime
by defining the PHP_IMAGE environment variable:
PHP_IMAGE='php:8.3-cli' ./dockerfile.sh | docker build -t msgpack -
See a list of various images here.
Then run the unit tests:
docker run --rm -v $PWD:/msgpack -w /msgpack msgpack
Fuzzing
To ensure that the unpacking works correctly with malformed/semi-malformed data, you can use a testing technique called fuzzing. The library ships with a helper file (target) for PHP-Fuzzer and can be used as follows:
php-fuzzer fuzz tests/fuzz_buffer_unpacker.php
Performance
To check performance, run:
php -n -dzend_extension=opcache.so \ -dpcre.jit=1 -dopcache.enable=1 -dopcache.enable_cli=1 \ tests/bench.php
With JIT:
php -n -dzend_extension=opcache.so \ -dpcre.jit=1 -dopcache.jit_buffer_size=64M -dopcache.jit=tracing -dopcache.enable=1 -dopcache.enable_cli=1 \ tests/bench.php
You may change default benchmark settings by defining the following environment variables:
| Name | Default |
|---|---|
| MP_BENCH_TARGETS | pure_p,pure_u, see the list of available targets |
| MP_BENCH_ITERATIONS | 100_000 |
| MP_BENCH_DURATION | not set |
| MP_BENCH_ROUNDS | 3 |
| MP_BENCH_TESTS | -@slow, see the list of available tests |
For example:
export MP_BENCH_TARGETS=pure_p export MP_BENCH_ITERATIONS=1000000 export MP_BENCH_ROUNDS=5 # a comma separated list of test names export MP_BENCH_TESTS='complex array, complex map' # or a group name # export MP_BENCH_TESTS='-@slow' // @pecl_comp # or a regexp # export MP_BENCH_TESTS='/complex (array|map)/'
Another example, benchmarking both the library and the PECL extension:
MP_BENCH_TARGETS=pure_p,pure_u,pecl_p,pecl_u \ php -n -dextension=msgpack.so -dzend_extension=opcache.so \ -dpcre.jit=1 -dopcache.enable=1 -dopcache.enable_cli=1 \ tests/bench.php
With JIT:
MP_BENCH_TARGETS=pure_p,pure_u,pecl_p,pecl_u \ php -n -dextension=msgpack.so -dzend_extension=opcache.so \ -dpcre.jit=1 -dopcache.jit_buffer_size=64M -dopcache.jit=tracing -dopcache.enable=1 -dopcache.enable_cli=1 \ tests/bench.php
Note that the msgpack extension (v2.1.2) doesn't support ext, bin and UTF-8 str types.
License
The library is released under the MIT License. See the bundled LICENSE file for details.
