SerializeLengthPacker.php
1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
namespace AukeySwrpc\Packer;
use AukeySwrpc\Request\Request;
/**
* Class SerializeLengthPacker
*
* @package AukeySwrpc\Packer
* @author pengjch 202439 11:37:27
*/
class SerializeLengthPacker implements PackerInterface
{
/**
* @var string
*/
protected $type;
/**
* @var int
*/
protected $length;
protected $defaultOptions
= [
'package_length_type' => 'N',
'package_body_offset' => 4,
];
public function __construct(array $options = [])
{
$options = array_merge($this->defaultOptions, $options['settings'] ?? []);
$this->type = $options['package_length_type'];
$this->length = $options['package_body_offset'];
}
public function pack(Request $data): string
{
$data = serialize($data);
return pack($this->type, strlen($data)) . $data;
}
public function unpack(string $data)
{
$package = unpack('N', $data);
$len = $package[1];
//合并unserialize和substr,以减少内存拷贝 https://wenda.swoole.com/detail/107587
if (function_exists('swoole_substr_unserialize')) {
return swoole_substr_unserialize($data, $this->length, $len);
}
$data = substr($data, $this->length, $len);
return unserialize($data);
}
}