summaryrefslogtreecommitdiffstats
path: root/zstd.php
blob: 0ec22d7afb88419fde510fe83710162e078c8b27 (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
67
68
69
70
71
72
<?php declare(strict_types=1);

/** 
 * 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");
	require_once __DIR__ . '/preload-zstd.inc';
} else {
	printf("Use preloaded class\n");
}
if (class_exists("\\Remi\\Zstd")) {
	$t = microtime(true);

	$src = file_get_contents(PHP_BINARY);
	$comp = \Remi\Zstd::compress($src);
	printf("\nSrc length           = %d\n", \strlen($src));
	printf("ZSTD_compress        = %d\n", \strlen($comp));
	file_put_contents("testffi.zstd", $comp);

	$comp = file_get_contents("testffi.zstd");
	$out = \Remi\Zstd::decompress($comp);
	printf("Src length           = %d\n", \strlen($comp));
	printf("ZSTD_decompress      = %d\n", \strlen($out));
	file_put_contents("testffi.orig", $out);

	printf("Check                = %s\n", $src === $out ? "OK" : "KO");

	$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");
	printf("Src length           = %d\n", \strlen($comp));
	$unco = zstd_uncompress($comp);
	$ulen = strlen($unco);
	printf("ZSTD_decompress      = %d\n", $ulen);
	file_put_contents("testzstd.orig", $unco);

	printf("Check                = %s\n", $src === $unco ? "OK" : "KO");
	$t = microtime(true) - $t;
	printf("Using ZSTD extension = %.3f\"\n\n", $t);
} else {
	printf("ZSTD missing\n\n");
}