index/src/Serialisation/Base62.php
2023-07-21 21:47:41 +00:00

51 lines
1.2 KiB
PHP

<?php
// Base62.php
// Created: 2022-01-28
// Updated: 2023-07-21
namespace Index\Serialisation;
use Index\IO\Stream;
/**
* Provides a Base62 serialiser.
*/
final class Base62 {
private const CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
/**
* Encodes an integer as a Base62 string.
*
* @param int $input Integer.
* @return string Base64 string representing the integer.
*/
public static function encode(int $input): string {
$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 static function decode(Stream|string $input): int {
$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;
}
}