@@ -10,41 +10,44 @@ final class Base62
1010
1111 public static function encode (string $ value ): string
1212 {
13- if (empty ($ value )) {
14- return $ value ;
13+ $ bytes = 0 ;
14+ $ hexadecimal = bin2hex ($ value );
15+
16+ while (str_starts_with ($ hexadecimal , '00 ' )) {
17+ $ bytes ++;
18+ $ hexadecimal = substr ($ hexadecimal , 2 );
1519 }
1620
17- $ hexadecimal = bin2hex ($ value );
18- $ decimal = gmp_init ($ hexadecimal , self ::HEXADECIMAL_RADIX );
19- $ encoded = '' ;
21+ $ base62 = str_repeat (self ::BASE62_ALPHABET [0 ], $ bytes );
2022
21- while (gmp_cmp ($ decimal , '0 ' ) > 0 ) {
22- $ remainder = gmp_intval (gmp_mod ($ decimal , self ::BASE62_RADIX ));
23- $ decimal = gmp_div_q ($ decimal , self ::BASE62_RADIX );
24- $ encoded = self ::BASE62_ALPHABET [$ remainder ] . $ encoded ;
23+ if (empty ($ hexadecimal )) {
24+ return strtr ($ base62 , self ::BASE62_ALPHABET , self ::BASE62_ALPHABET );
2525 }
2626
27- return $ encoded ;
27+ $ base62Conversion = gmp_strval (gmp_init ($ hexadecimal , self ::HEXADECIMAL_RADIX ), self ::BASE62_RADIX );
28+
29+ return strtr ($ base62 . $ base62Conversion , self ::BASE62_ALPHABET , self ::BASE62_ALPHABET );
2830 }
2931
3032 public static function decode (string $ value ): string
3133 {
34+ $ bytes = 0 ;
35+
36+ while (!empty ($ value ) && str_starts_with ($ value , self ::BASE62_ALPHABET [0 ])) {
37+ $ bytes ++;
38+ $ value = substr ($ value , 1 );
39+ }
40+
3241 if (empty ($ value )) {
33- return $ value ;
42+ return str_repeat ( "\x00" , $ bytes ) ;
3443 }
3544
36- $ decimal = gmp_init (' 0 ' );
45+ $ hexadecimal = gmp_strval ( gmp_init ($ value , self :: BASE62_RADIX ), self :: HEXADECIMAL_RADIX );
3746
38- for ($ i = 0 , $ length = strlen ($ value ); $ i < $ length ; $ i ++) {
39- $ character = $ value [$ i ];
40- $ position = strpos (self ::BASE62_ALPHABET , $ character );
41- $ decimal = gmp_mul ($ decimal , self ::BASE62_RADIX );
42- $ decimal = gmp_add ($ decimal , $ position );
47+ if (strlen ($ hexadecimal ) % 2 !== 0 ) {
48+ $ hexadecimal = '0 ' . $ hexadecimal ;
4349 }
4450
45- $ hexadecimal = gmp_strval ($ decimal , self ::HEXADECIMAL_RADIX );
46- $ decoded = hex2bin ($ hexadecimal );
47-
48- return $ decoded !== false ? $ decoded : '' ;
51+ return hex2bin (str_repeat ('00 ' , $ bytes ) . $ hexadecimal );
4952 }
5053}
0 commit comments