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