index/src/Serialisation/Base62.php

51 lines
1.2 KiB
PHP
Raw Normal View History

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