arnapou / encoder
库 - 带有通用接口的基本编码器。
v2.2
2024-04-05 00:03 UTC
Requires
- php: ~8.3.0
Requires (Dev)
- ext-zlib: *
- friendsofphp/php-cs-fixer: ^3.52
- phpstan/extension-installer: ^1.3
- phpstan/phpstan: ^1.10
- phpstan/phpstan-deprecation-rules: ^1.1
- phpstan/phpstan-phpunit: ^1.3
- phpstan/phpstan-strict-rules: ^1.5
- phpunit/php-code-coverage: ^11.0
- phpunit/phpunit: ^11.0
README
该库暴露具有通用接口的基本编码器。
安装
composer require arnapou/encoder
packagist 👉️ arnapou/encoder
书本编码器
这些编码器是预测编码器,在特定的已知单词书中提供强大的压缩能力。
对于不在书中的字符串,这些编码器很不好:它们需要2个字节而不是1个字节。
单字节编码器(8位)
单词数最大值:255
use Arnapou\Encoder\Book\ArrayBook;
use Arnapou\Encoder\Book\OneByteBookEncoder;
$book = new ArrayBook(['Hello', 'World']);
$encoder = new OneByteBookEncoder($book);
// 11 to 4 bytes (-63%)
var_dump(bin2hex($encoder->encode('Hello World')));
// string(8) "00ff2001"
var_dump($encoder->decode(hex2bin('00ff2001')));
// string(11) "Hello World"
双字节编码器(16位)
单词数最大值:65535
当您有很多单词需要存储(> 256)且每个单词至少为2个字节长时,这非常有用。
use Arnapou\Encoder\Book\ArrayBook;
use Arnapou\Encoder\Book\TwoBytesBookEncoder;
$book = new ArrayBook(['https://', 'arnapou.net']);
$encoder = new TwoBytesBookEncoder($book);
// 19 to 4 bytes (-79%)
var_dump(bin2hex($encoder->encode('https://arnapou.net')));
// string(6) "00010000"
var_dump($encoder->decode(hex2bin('00010000')));
// string(19) "https://arnapou.net"
示例
您可以使用此编码器来缩短预定义的文本模式。
我用来缩短具有相同模式的URL。
请参阅src/Book 中的可用书籍
- ArrayBook:泛型可迭代书籍的简单实现
- EnglishBook:内置的英文文本书籍
- WebBook:内置的URI书籍
请随意提交专用书籍。
use Arnapou\Encoder\Book\EnglishBook;
use Arnapou\Encoder\Book\OneByteBookEncoder;
$book = new EnglishBook();
$encoder = new OneByteBookEncoder($book);
// 22 to 11 bytes (-50%)
var_dump(bin2hex($encoder->encode('This is a small string')));
// string(11) "ff54446e5675aeac75d446"
var_dump($encoder->decode(hex2bin('ff54446e5675aeac75d446')));
// string(22) "This is a small string"
其他编码器
您会发现其他有用的编码器,例如
编码器 | 描述 |
---|---|
身份 | 无编码 |
十六进制 | 十六进制编码 |
Base64 | 基于64的编码,可选修剪 |
Base64UrlSafe | 用于URL的基于64的编码(+/ => -_ ) |
Zlib | gzdeflate /gzencode /gzcompress 系列 |
还有一个非常有用的PipelineEncoder
,可以用来连接编码器
use Arnapou\Encoder\Base64\Base64Encoder;
use Arnapou\Encoder\PipelineEncoder;
use Arnapou\Encoder\Zlib\ZlibEncoder;
use Arnapou\Encoder\Zlib\ZlibEncoding;
$encoder = new PipelineEncoder(
new ZlibEncoder(encoding: ZlibEncoding::raw),
new Base64Encoder(),
);
var_dump($encoder->encode('Lorem ipsum dolor sit amet'));
// string(38) "88kvSs1VyCwoLs1VSMnPyS9SKM4sUUjMTS0BAA"
var_dump($encoder->decode('88kvSs1VyCwoLs1VSMnPyS9SKM4sUUjMTS0BAA'));
// string(26) "Lorem ipsum dolor sit amet"
PHP版本
日期 | 参考 | 8.3 | 8.2 |
---|---|---|---|
25/11/2023 | 2.x,主要 | × | |
04/09/2024 | 1.3.x | × | × |
13/12/2022 | 1.x | × |