Created
March 11, 2021 22:44
-
-
Save divinity76/92f46857459e11d3bbc1012baf7af5e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function shittyRecurringCompression(string $data):string{ | |
$countRecurring=function(string $str):int{ | |
$imax = min(0xFF,strlen($str)); | |
if($imax===0){ | |
return 0; | |
} | |
$startChar = $str[0]; | |
for($i=1;$i<$imax;++$i){ | |
if($str[$i]!==$startChar){ | |
return $i; | |
} | |
} | |
return $i; | |
}; | |
$countNonRecurring = function(string $str)use(&$countRecurring):int{ | |
$ret = 0; | |
$iMax = min(0xFF,strlen($str)); | |
for($i=0;$i<$iMax;++$i){ | |
if($countRecurring($str) >3){ | |
return $i; | |
} | |
$str = substr($str, 1); | |
} | |
return $i; | |
}; | |
$mode_recurring = "\x01"; | |
$mode_non_recurring = "\x00"; | |
$ret = ""; | |
while(strlen($data)){ | |
$nonRecurring = $countNonRecurring($data); | |
if($nonRecurring > 0){ | |
$ret.= $mode_non_recurring; | |
$ret.=chr($nonRecurring); | |
$ret.=substr($data,0,$nonRecurring); | |
$data = substr($data,$nonRecurring); | |
}else{ | |
$ret.=$mode_recurring; | |
$recurring = $countRecurring($data); | |
$ret.=chr($recurring); | |
$ret.=$data[0]; | |
$data = substr($data,$recurring); | |
} | |
} | |
return $ret; | |
} | |
function shittyRecurringUncompress(string $data):string{ | |
$ret = ""; | |
$mode_recurring = "\x01"; | |
$mode_non_recurring = "\x00"; | |
while(strlen($data)){ | |
$mode = $data[0]; | |
if($mode === $mode_recurring){ | |
$recur_counter = ord($data[1]); | |
$recur_char = $data[2]; | |
$data = substr($data, 3); | |
$ret.=str_repeat($recur_char, $recur_counter); | |
}elseif($mode === $mode_non_recurring){ | |
$non_recur_counter = ord($data[1]); | |
$ret.=substr($data,2, $non_recur_counter); | |
$data = substr($data, 2+$non_recur_counter); | |
}else{ | |
throw new \InvalidArgumentException("invalid mode header: ".bin2hex($mode)); | |
} | |
} | |
return $ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment