Skip to content

Commit

Permalink
Improve base32 package implementation by removing regexp usage
Browse files Browse the repository at this point in the history
  • Loading branch information
nyamsprod committed Mar 22, 2024
1 parent 5c0bde3 commit 2fa5870
Showing 1 changed file with 19 additions and 19 deletions.
38 changes: 19 additions & 19 deletions src/Base32/Base32.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public function decode(string $encoded, bool $strict = false): string

$alphabet = $this->alphabet;
$padding = $this->padding;
$encoded = str_replace(["\r", "\n"], [''], $encoded);
$encoded = str_replace(["\r", "\n", ' '], [''], $encoded);
if (!$strict) {
$alphabet = strtoupper($alphabet);
$padding = strtoupper($padding);
Expand All @@ -61,45 +61,45 @@ public function decode(string $encoded, bool $strict = false): string

$remainder = strlen($encoded) % 8;
if (0 !== $remainder) {
if ($strict) {
$encoded .= !$strict ?
str_repeat($padding, $remainder) :
throw new RuntimeException('The encoded data length is invalid.');
}

$encoded .= str_repeat($padding, $remainder);
}

$inside = rtrim($encoded, $padding);
$end = substr($encoded, strlen($inside));
if ($strict && !in_array(strlen($end), [3, 4, 6, 0], true)) {
throw new RuntimeException('The encoded data contains an invalid padding character length.');
if ($strict && !in_array(strlen($end), [0, 1, 3, 4, 6], true)) {
throw new RuntimeException('The encoded data contains an invalid padding sequence length.');
}

if (str_contains($inside, $padding)) {
if ($strict) {
$encoded = !$strict ?
str_replace($padding, '', $inside).$end :
throw new RuntimeException('The encoded data contains the padding character.');
}
$encoded = str_replace($padding, '', $inside).$end;
}

$characters = $alphabet.$padding;
if (strspn($encoded, $characters) !== strlen($encoded)) {
if ($strict) {
throw new RuntimeException('The encoded data contains characters unknown to the alphabet.');
}
$encoded = preg_replace('/[^'.preg_quote($characters, '/').']/', '', $encoded);
if ('' === $encoded || null === $encoded) {
return '';
}
if ($strict && (strspn($encoded, $characters) !== strlen($encoded))) {
throw new RuntimeException('The encoded data contains characters unknown to the alphabet.');
}

$decoded = '';
$offset = 0;
$bitLen = 5;
$length = strlen($encoded);
$chars = array_combine(str_split($characters), [...range(0, 31), 0]);
$val = $chars[$encoded[0]];
$val = $chars[$encoded[$offset]] ?? -1;

while ($offset < $length) {
if (!$strict && $val === -1) {
$offset++;
if ($offset === $length) {
break;
}
$val = $chars[$encoded[$offset]] ?? -1;
continue;
}

if ($bitLen < 8) {
$bitLen += 5;
$offset++;
Expand Down

0 comments on commit 2fa5870

Please sign in to comment.