52 lines
1.3 KiB
PHP
52 lines
1.3 KiB
PHP
|
<?php
|
||
|
// Base62Serialiser.php
|
||
|
// Created: 2022-01-28
|
||
|
// Updated: 2022-02-27
|
||
|
|
||
|
namespace Index\Serialisation;
|
||
|
|
||
|
use Index\IO\Stream;
|
||
|
|
||
|
/**
|
||
|
* Provides a Base62 serialiser.
|
||
|
*/
|
||
|
class Base62Serialiser extends Serialiser {
|
||
|
private const CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||
|
|
||
|
/**
|
||
|
* Encodes an integer as a Base62 string.
|
||
|
*
|
||
|
* @param int $input Integer.
|
||
|
* @return string Base64 string representing the integer.
|
||
|
*/
|
||
|
public function serialise(mixed $input): string {
|
||
|
$input = intval($input);
|
||
|
$output = '';
|
||
|
|
||
|
for($i = floor(log10($input) / log10(62)); $i >= 0; --$i) {
|
||
|
$index = (int)floor($input / (62 ** $i));
|
||
|
$output .= substr(self::CHARS, $index, 1);
|
||
|
$input -= $index * (62 ** $i);
|
||
|
}
|
||
|
|
||
|
return $output;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Decodes a Base62 string back to an integer.
|
||
|
*
|
||
|
* @param Stream|string $input Input Base62 string.
|
||
|
* @return int Integer.
|
||
|
*/
|
||
|
public function deserialise(Stream|string $input): mixed {
|
||
|
$input = (string)$input;
|
||
|
$output = 0;
|
||
|
$length = strlen($input) - 1;
|
||
|
|
||
|
for($i = 0; $i <= $length; ++$i)
|
||
|
$output += strpos(self::CHARS, $input[$i]) * (62 ** ($length - $i));
|
||
|
|
||
|
return $output;
|
||
|
}
|
||
|
}
|