arnapou/encoder

库 - 带有通用接口的基本编码器。

v2.2 2024-04-05 00:03 UTC

This package is auto-updated.

Last update: 2024-09-08 14:33:58 UTC


README

pipeline coverage

该库暴露具有通用接口的基本编码器。

安装

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 中的可用书籍

请随意提交专用书籍。

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的编码(+/ => -_
Zlibgzdeflate/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.38.2
25/11/20232.x,主要×
04/09/20241.3.x××
13/12/20221.x×