summaryrefslogtreecommitdiffstats
path: root/preload-zstd.inc
blob: f56c833d6062e37d13e400fdec8190f07dc4a9be (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?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;

	public 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
			if (PHP_SAPI === 'cli' || (int)ini_get("ffi.enable")) {
				self::$ffi = \FFI::load(__DIR__ . '/preload-zstd.h');
				echo "Using FFI::load OK\n";
			} else {
				throw $e;
			}
		}
		if (!self::$ffi) {
			throw new \RuntimeException("FFI parse fails");
		}
	}

	public static function compress($in, $out) {
		self::init();

		$ret = [];
		$src = file_get_contents($in);
		if ($src === false) {
			throw new \RuntimeException("Read fails");
		}
		$len = strlen($src);
		$ret['in_len'] = $len;

		$max = self::$ffi->ZSTD_compressBound($len);
		$ret['max_len'] = $max;

		$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");
		}
		$ret['out_len'] = $clen;
		if (file_put_contents($out, substr($comp, 0, $clen)) !== $clen) {
			throw new \RuntimeException("Save fails");
		}

		return $ret;
	}

	public static function decompress($in, $out) {
		self::init();

		$ret = [];
		$comp = file_get_contents($in);
		if ($comp === false) {
			throw new \RuntimeException("Read fails");
		}
		$clen = strlen($comp);
		$ret['in_len'] = $clen;

		$max = self::$ffi->ZSTD_decompressBound($comp, $clen);
		$ret['max_len'] = $max;

		$unco = str_repeat(' ', $max);
		$ulen = self::$ffi->ZSTD_decompress($unco, $max, $comp, $clen);
		if (self::$ffi->ZSTD_isError($clen)) {
			throw new \RuntimeException("Compression fails");
		}
		$ret['out_len'] = $ulen;
		if (file_put_contents($out, substr($unco, 0, $ulen)) !== $ulen) {
			throw new \RuntimeException("Save fails");
		}

		return $ret;
	}
}