Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Reduce memory copying operations in bech32 encoding #29607

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 9 additions & 7 deletions src/bech32.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -363,13 +363,13 @@ std::string Encode(Encoding encoding, const std::string& hrp, const data& values
// to return a lowercase Bech32/Bech32m string, but if given an uppercase HRP, the
// result will always be invalid.
for (const char& c : hrp) assert(c < 'A' || c > 'Z');
data checksum = CreateChecksum(encoding, hrp, values);
data combined = Cat(values, checksum);
std::string ret = hrp + '1';
ret.reserve(ret.size() + combined.size());
for (const auto c : combined) {
ret += CHARSET[c];
}

std::string ret;
ret.reserve(hrp.size() + 1 + values.size() + CHECKSUM_SIZE);
ret += hrp;
ret += '1';
for (const uint8_t& i : values) ret += CHARSET[i];
for (const uint8_t& i : CreateChecksum(encoding, hrp, values)) ret += CHARSET[i];
return ret;
}

Expand All @@ -393,6 +393,7 @@ DecodeResult Decode(const std::string& str, CharLimit limit) {
values[i] = rev;
}
std::string hrp;
hrp.reserve(pos);
for (size_t i = 0; i < pos; ++i) {
hrp += LowerCase(str[i]);
}
Expand Down Expand Up @@ -425,6 +426,7 @@ std::pair<std::string, std::vector<int>> LocateErrors(const std::string& str, Ch
}

std::string hrp;
hrp.reserve(pos);
for (size_t i = 0; i < pos; ++i) {
hrp += LowerCase(str[i]);
}
Expand Down