summaryrefslogtreecommitdiffstats
path: root/zstd.php
blob: 35c8876616e5a13d7b5dbd7f959e68c563c32f6f (plain)
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
60
61
62
63
64
65
66
<?php
/** 
 * ZSTD compressor using FFI and libzstd
 * PoC, only for documentation purpose
 *
 * Copyright (c) 2019 Remi Collet
 * License: CC-BY-SA
 * http://creativecommons.org/licenses/by-sa/4.0/
 */

if (PHP_VERSION_ID < 70400 || !extension_loaded("ffi")) {
	die("PHP 7.4 with FFI required\n");
}
printf("PHP version %s\n", PHP_VERSION);

if (PHP_SAPI == "cli" && !class_exists("\\Remi\\Zstd")) {
	printf("Fallback on manual load\n\n");
	require_once __DIR__ . '/preload-zstd.inc';
} else {
	printf("Use preloaded class\n\n");
}
if (class_exists("\\Remi\\Zstd")) {
	$t = microtime(true);

	$ret = \Remi\Zstd::compress(PHP_BINARY, "testffi.zstd");
	printf("Src length           = %d\n", $ret['in_len']);
	printf("ZSTD_compressBound   = %d\n", $ret['max_len']);
	printf("ZSTD_compress        = %d\n", $ret['out_len']);

	$ret = \Remi\Zstd::decompress("testffi.zstd", "testffi.orig");
	printf("Src length           = %d\n", $ret['in_len']);
	printf("ZSTD_decompressBound = %d\n", $ret['max_len']);
	printf("ZSTD_decompress      = %d\n", $ret['out_len']);

	$t = microtime(true) - $t;
	printf("Using FFI  extension = %.3f\"\n\n", $t);
} else {
	printf("FFI missing\n\n");
}

if (extension_loaded("zstd")) {
	$t = microtime(true);
	$src = file_get_contents(PHP_BINARY);
	$len = strlen($src);
	printf("Src length           = %d\n", $len);

	$comp = zstd_compress($src, 6);
	$clen = strlen($comp);
	printf("ZSTD_compress        = %d\n", $clen);
	$comp = substr($comp, 0, $clen);
	file_put_contents("testzstd.zstd", $comp);

	$comp = file_get_contents("testzstd.zstd");
	$unco = zstd_uncompress($comp);
	$ulen = strlen($unco);
	printf("ZSTD_decompress      = %d\n", $ulen);
	file_put_contents("testzstd.orig", $unco);

	var_dump($src === $unco);
	$t = microtime(true) - $t;
	printf("Using ZSTD extension = %.3f\"\n\n", $t);
} else {
	printf("ZSTD missing\n\n");
}