Skip to content

Commit 159ed95

Browse files
committed
base58: Improve DecodeBase58 performance.
Improve DecodeBase58 performance the same way as commit 3252208 did for EncodeBase58.
1 parent a82e5d8 commit 159ed95

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

src/base58.cpp

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,14 @@ bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
2525
psz++;
2626
// Skip and count leading '1's.
2727
int zeroes = 0;
28+
int length = 0;
2829
while (*psz == '1') {
2930
zeroes++;
3031
psz++;
3132
}
3233
// Allocate enough space in big-endian base256 representation.
33-
std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up.
34+
int size = strlen(psz) * 733 /1000 + 1; // log(58) / log(256), rounded up.
35+
std::vector<unsigned char> b256(size);
3436
// Process the characters.
3537
while (*psz && !isspace(*psz)) {
3638
// Decode base58 character
@@ -39,12 +41,14 @@ bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
3941
return false;
4042
// Apply "b256 = b256 * 58 + ch".
4143
int carry = ch - pszBase58;
42-
for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {
44+
int i = 0;
45+
for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); (carry != 0 || i < length) && (it != b256.rend()); it++, i++) {
4346
carry += 58 * (*it);
4447
*it = carry % 256;
4548
carry /= 256;
4649
}
4750
assert(carry == 0);
51+
length = i;
4852
psz++;
4953
}
5054
// Skip trailing spaces.
@@ -53,7 +57,7 @@ bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
5357
if (*psz != 0)
5458
return false;
5559
// Skip leading zeroes in b256.
56-
std::vector<unsigned char>::iterator it = b256.begin();
60+
std::vector<unsigned char>::iterator it = b256.begin() + (size - length);
5761
while (it != b256.end() && *it == 0)
5862
it++;
5963
// Copy result into output vector.

0 commit comments

Comments
 (0)