Base83.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. <?php
  2. namespace App\Util\Blurhash;
  3. use InvalidArgumentException;
  4. class Base83 {
  5. private const ALPHABET = [
  6. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
  7. 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
  8. 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
  9. 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
  10. 'u', 'v', 'w', 'x', 'y', 'z', '#', '$', '%', '*', '+', ',', '-', '.',
  11. ':', ';', '=', '?', '@', '[', ']', '^', '_', '{', '|', '}', '~'
  12. ];
  13. private const BASE = 83;
  14. public static function encode(int $value, int $length): string {
  15. if (floor($value / (self::BASE ** $length)) != 0) {
  16. throw new InvalidArgumentException('Specified length is too short to encode given value.');
  17. }
  18. $result = '';
  19. for ($i = 1; $i <= $length; $i++) {
  20. $digit = floor($value / (self::BASE ** ($length - $i))) % self::BASE;
  21. $result .= self::ALPHABET[$digit];
  22. }
  23. return $result;
  24. }
  25. public static function decode(string $hash): int {
  26. $result = 0;
  27. foreach (str_split($hash) as $char) {
  28. $result = $result * self::BASE + (int) array_search($char, self::ALPHABET, true);
  29. }
  30. return (int) $result;
  31. }
  32. }