rybakit / msgpack.php

A pure PHP implementation of the MessagePack serialization format / msgpack.org[PHP]
MIT License
388 stars 18 forks source link

Use generators for unpackArray/unpackMap #10

Closed rybakit closed 6 years ago

rybakit commented 8 years ago

E.g.:

private function unpackMapGenerator($size)
{
    for ($i = $size; $i; $i--) {
        yield $this->unpack() => $this->unpack();
    }
}
eFrane commented 7 years ago

Since generators are a PHP 5.5 feature I personally don't see any reason not to do this.

rybakit commented 7 years ago

@eFrane I can't come up with a good idea of how to integrate generators into the current api. For example, lets say you packed the following array:

$array = [range(1, 9), 'foobar'];

How to unpack it using generators then? You need to do something like:

function read_result($result, callable $callback)
{
    if (!$result instanceof \Traversable) {
        return $callback($result);
    }

    foreach ($result as $item) {
        read_result($item, $callback);
    }
}

$raw = $unpacker->unpack();
read_result($raw, function ($item) { var_dump($item); });

And you probably don't want to do this on every unpack call.

rybakit commented 6 years ago

New type transformers introduced in PR #21 address the issue:

https://github.com/rybakit/msgpack.php/blob/650c3c9b22ce8cbc0618d7a93fa9596a86284905/examples/MessagePack/ArrayIteratorTransformer.php#L46-L48

https://github.com/rybakit/msgpack.php/blob/650c3c9b22ce8cbc0618d7a93fa9596a86284905/examples/array_iterator.php#L18

rybakit commented 6 years ago

21 has been merged.