metanohi-misc-subsites/old-projects/nalgh/nalgh.php

76 lines
1.4 KiB
PHP
Raw Normal View History

2011-08-02 19:57:57 +02:00
<?php
//WTFPL 2.0
function nalgh_compress($txt) {
$len = strlen($txt);
for ($i = 0; $i < $len; $i++) {
$c[substr($txt, $i, 1)]++;
}
while ($n = current($c)) {
$l[sizeof($l)] = array($n, key($c));
next($c);
}
sort($l);
$l = array_reverse($l);
$i = 0;
foreach ($l as $t) {
$f[$t[1]] = decbin($i);
$i++;
}
for ($i = 0; $i < $len; $i++) {
$r .= '2' . $f[substr($txt, $i, 1)];
}
$r = substr($r, 1);
$rlen = strlen($r);
$extra = 5 - ($rlen % 5);
$extra == 5 ? $extra = 0 : pass;
for ($i = 0; $i < $extra; $i++) {
$r .= '2';
}
$rlen += $extra;
for ($i = 0; $i < $rlen; $i += 5) {
$e .= chr((int)base_convert(substr($r, $i, 5), 3, 10));
}
$ee = chr('' . sizeof($f) - 1 . '');
reset($f);
$ee .= key($f);
next($f);
while ($fe = current($f)) {
$ee .= key($f);
next($f);
}
$e = $ee . $e;
return $e;
}
function nalgh_decompress($txt) {
$olen = ord(substr($txt, 0, 1)) + 1;
for ($i = 0; $i < $olen; $i++) {
$s['' . decbin($i) . ''] = substr($txt, $i + 1, 1);
}
$txt = substr($txt, $olen + 1);
$len = strlen($txt);
for ($i = 0; $i < $len; $i++) {
$t = base_convert(ord(substr($txt, $i, 1)), 10, 3);
$tlen = 5 - strlen($t);
for ($ii = 0; $ii < $tlen; $ii++) {
$t = '0' . $t;
}
$r .= $t;
}
$p = explode('2', $r);
foreach ($p as $t) {
$e .= $s[$t];
}
return $e;
}
?>