Updated Base62 implementation.

This commit is contained in:
flash 2024-07-31 18:36:16 +00:00
parent d556081541
commit b3078c28e3
2 changed files with 22 additions and 19 deletions

View file

@ -1 +1 @@
0.2407.311824
0.2407.311834

View file

@ -1,49 +1,52 @@
<?php
// Base62.php
// Created: 2022-01-28
// Updated: 2023-07-21
// Updated: 2024-07-31
namespace Index\Serialisation;
use Index\IO\Stream;
/**
* Provides a Base62 serialiser.
*/
final class Base62 {
private const CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
private const BASE = 62;
/**
* Encodes an integer as a Base62 string.
* Converts a base10 integer to a base62 integer.
*
* @param int $input Integer.
* @return string Base64 string representing the integer.
* @param int $integer The integer to encode.
* @return string The encoded data, as a string.
*/
public static function encode(int $input): string {
public static function encode(int $integer): string {
$output = '';
for($i = floor(log10($input) / log10(62)); $i >= 0; --$i) {
$index = (int)floor($input / (62 ** $i));
for($i = floor(log10($integer) / log10(self::BASE)); $i >= 0; --$i) {
$index = (int)floor($integer / (self::BASE ** $i));
$output .= substr(self::CHARS, $index, 1);
$input -= $index * (62 ** $i);
$integer -= $index * (self::BASE ** $i);
}
return $output;
}
/**
* Decodes a Base62 string back to an integer.
* Converts a base62 integer to a base10 integer.
*
* @param Stream|string $input Input Base62 string.
* @return int Integer.
* @param string $string The encoded integer.
* @return int|false Returns the decoded integer or false on failure.
*/
public static function decode(Stream|string $input): int {
$input = (string)$input;
public static function decode(string $string): int|false {
$output = 0;
$length = strlen($input) - 1;
$length = strlen($string) - 1;
for($i = 0; $i <= $length; ++$i)
$output += strpos(self::CHARS, $input[$i]) * (62 ** ($length - $i));
for($i = 0; $i <= $length; ++$i) {
$pos = strpos(self::CHARS, $string[$i]);
if($pos === false)
return false;
$output += $pos * (self::BASE ** ($length - $i));
}
return $output;
}