0

I'm using official MsgPack version (http://msgpack.org/), installed for PHP 7 on server side and included as a library (msgpack.js) on client (any browser). Lets pack simple ArrayBuffer with msgpack in the browser:

function s2b ( s ) {
  var b = new Uint8Array(s.length);
  for ( var i = 0; i < s.length; i++ ) {
    var c = s.charCodeAt(i);
    if ( c > 255 ) throw new Error("Wide characters are not allowed");
    b[i] = c;
  }
  return b;
}

var test = { 'name': s2b('value').buffer };
console.log('packed', new Uint8Array(msgpack.pack(test)));

and here is the console output: packed [129, 164, 110, 97, 109, 101, 196, 5, 118, 97, 108, 117, 101]

We see here that before the 'value' ascii codes we have 2 additional mspack flags - 196 (the type of data is ArrayBuffer) and 5 (the lenght of ArrayBuffer data). All is clear here.

The question is - how to construct the same object in PHP? Lets look at my code:

$data = [
  "name" => 'value',
];
$packed = msgpack_pack($data);
for($i = 0; $i < strlen($packed); $i++) echo ord($packed[$i]) . ",";

The output is: "129,164,110,97,109,101,165,118,97,108,117,101,"

Obviously [196, 5] are changed to [165]. I understood that in PHP code the type of variable is string, but HOW TO EMULATE ArrayBuffer (raw binary) data in PHP?

I have tried PHP pack() but this didn't help.

anpako
  • 1
  • 2

1 Answers1

0

It's not really possible with the current msgpack-php extension (v2.0.2). See the following tickets for details:

Although, it's quite easy to achieve with the rybakit/msgpack library (see the examples/binary.php):

use MessagePack\Packer;
use MessagePack\PackOptions;
use MessagePack\Type\Binary;
use MessagePack\TypeTransformer\BinaryTransformer;

$packer = new Packer(PackOptions::FORCE_STR);
$packer->registerTransformer(new BinaryTransformer());

$packed = $packer->pack(['name' => new Binary('value')]);

echo '[', implode(', ', unpack('C*', $packed)), "]\n";

Output: [129, 164, 110, 97, 109, 101, 196, 5, 118, 97, 108, 117, 101]

Eugene Leonovich
  • 884
  • 1
  • 9
  • 15