Updated Base32 method signatures.

This commit is contained in:
flash 2024-07-31 18:25:01 +00:00
parent 4b4ff9f7c4
commit d556081541
2 changed files with 19 additions and 19 deletions

View file

@ -1 +1 @@
0.2407.311820
0.2407.311824

View file

@ -1,32 +1,29 @@
<?php
// Base32.php
// Created: 2022-01-13
// Updated: 2023-07-21
// Updated: 2024-07-31
namespace Index\Serialisation;
use Index\IO\Stream;
/**
* Provides a Base32 serialiser.
* Provides Base32 encoding.
*/
final class Base32 {
private const CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
/**
* Encodes binary data as a Base32 string.
* Encodes data with RFC4648 base32.
*
* @param Stream|string $input Input binary data.
* @return string Base32 string representing the binary data.
* @param string $string The data to encode.
* @return string The encoded data, as a string.
*/
public static function encode(Stream|string $input): string {
$input = (string)$input;
$length = strlen($input);
public static function encode(string $string): string {
$length = strlen($string);
$bin = '';
$output = '';
for($i = 0; $i < $length; $i++)
$bin .= sprintf('%08b', ord($input[$i]));
$bin .= sprintf('%08b', ord($string[$i]));
$bin = str_split($bin, 5);
$last = array_pop($bin);
@ -39,20 +36,23 @@ final class Base32 {
}
/**
* Decodes a Base32 string back to binary data.
* Decodes data encoded with RFC4648 base32.
*
* @param Stream|string $input Input Base32 string.
* @return string Binary data.
* @param string $string The encoded data.
* @return string|false Returns the decoded data or false on failure. The returned data may be binary.
*/
public static function decode(Stream|string $input): string {
$input = (string)$input;
$length = strlen($input);
public static function decode(string $string): string|false {
$length = strlen($string);
$char = $shift = 0;
$output = '';
for($i = 0; $i < $length; $i++) {
$pos = stripos(self::CHARS, $string[$i]);
if($pos === false)
return false;
$char <<= 5;
$char += stripos(self::CHARS, $input[$i]);
$char += $pos;
$shift = ($shift + 5) % 8;
$output .= $shift < 5 ? chr(($char & (0xFF << $shift)) >> $shift) : '';
}