summaryrefslogtreecommitdiffstats
path: root/preload-zstd.inc
blob: a42e5bea94fa1d27bd7b3fb4359b40ff697d57b0 (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
<?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/
 */
namespace Remi;

class Zstd {
	static private $ffi = null;

	private static function init() {
		if (self::$ffi) {
			return;
		}
		// Try if preloaded
		try {
			self::$ffi = \FFI::scope("_REMI_ZSTD_");
			echo "Using FFI::scope OK\n";
		} catch (\FFI\Exception $e) {
			// Try direct load
			self::$ffi = \FFI::load(__DIR__ . '/preload-zstd.h');
			echo "Using FFI::load OK\n";
		}
		if (!self::$ffi) {
			throw new \RuntimeException("FFI parse fails");
		}
	}

	public static function compress(string $src): string {
		self::init();

		$len = strlen($src);
		$max = self::$ffi->ZSTD_compressBound($len);

		$comp = str_repeat(' ', $max);
		$clen = self::$ffi->ZSTD_compress($comp, $max, $src, $len, 6);
		if (self::$ffi->ZSTD_isError($clen)) {
			throw new \RuntimeException("Compression fails");
		}

		return substr($comp, 0, $clen);
	}

	public static function decompress(string $comp): string {
		self::init();

		$clen = strlen($comp);
		$max = self::$ffi->ZSTD_decompressBound($comp, $clen);

		$unco = str_repeat(' ', $max);
		$ulen = self::$ffi->ZSTD_decompress($unco, $max, $comp, $clen);
		if (self::$ffi->ZSTD_isError($clen)) {
			throw new \RuntimeException("Decompression fails");
		}

		return substr($unco, 0, $ulen);
	}
}