@@ -31,13 +31,55 @@ library Base58 {
31
31
return string (_encode (data));
32
32
}
33
33
34
+ /**
35
+ * @dev Encode a `bytes32` as a Base58 `string`. This is an alternative to {encode-bytes} that is significantly
36
+ * faster when the input is known to be 32 bytes long.
37
+ *
38
+ * This is usefull to encode Solana addresses.
39
+ */
40
+ function encode (bytes32 data ) internal pure returns (string memory ) {
41
+ return string (_encode (data, 44 ));
42
+ }
43
+
34
44
/**
35
45
* @dev Decode a Base58 `string` into a `bytes` buffer.
46
+ *
47
+ * NOTE: This function reverts if the input string contains invalid characters.
36
48
*/
37
49
function decode (string memory data ) internal pure returns (bytes memory ) {
38
50
return _decode (bytes (data));
39
51
}
40
52
53
+ /**
54
+ * @dev Internal encoding function that processes `bytes32` input. This is way faster than the generic (`bytes`)
55
+ * version, but is limited to 32 bytes of input (equivalent to 44 char outputs).
56
+ */
57
+ function _encode (bytes32 input , uint256 length ) private pure returns (bytes memory encoded ) {
58
+ assembly ("memory-safe" ) {
59
+ encoded := mload (0x40 )
60
+
61
+ // Store the encoding table. This overlaps with the FMP that we are going to reset later anyway.
62
+ mstore (0x1f , "123456789ABCDEFGHJKLMNPQRSTUVWXY " )
63
+ mstore (0x3f , "Zabcdefghijkmnopqrstuvwxyz " )
64
+
65
+ for {
66
+ let i := length
67
+ } gt (i, 0 ) {
68
+ i := sub (i, 1 )
69
+ } {
70
+ mstore8 (add (add (encoded, 0x1f ), i), mload (mod (input, 58 )))
71
+ input := div (input, 58 )
72
+ }
73
+
74
+ mstore (encoded, length)
75
+ mstore (0x40 , add (add (encoded, 0x20 ), length))
76
+ }
77
+ }
78
+
79
+ /**
80
+ * @dev Internal encoding function that processes `bytes` input of arbitrary length and returns another (newly
81
+ * allocated) bytes object that contains the encoded base58 string.
82
+ */
41
83
function _encode (bytes memory data ) private pure returns (bytes memory encoded ) {
42
84
// For reference, solidity implementation
43
85
// unchecked {
@@ -138,6 +180,12 @@ library Base58 {
138
180
}
139
181
}
140
182
183
+ /**
184
+ * @dev Internal decoding function that processes `bytes` input containing a base58 encoded string of arbitrary
185
+ * length and returns another (newly allocated) bytes object that contains the decoded buffer.
186
+ *
187
+ * NOTE: This function reverts if the input string contains invalid characters.
188
+ */
141
189
function _decode (bytes memory data ) private pure returns (bytes memory ) {
142
190
unchecked {
143
191
uint256 b58Length = data.length ;
0 commit comments