Skip to content

Commit 1a72d62

Browse files
sipaMacroFake
authored andcommitted
Generalize ConvertBits to permit transforming the input
1 parent 78f3ac5 commit 1a72d62

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

src/util/strencodings.h

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -249,15 +249,26 @@ bool TimingResistantEqual(const T& a, const T& b)
249249
*/
250250
[[nodiscard]] bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out);
251251

252+
namespace {
253+
/** Helper class for the default infn argument to ConvertBits (just returns the input). */
254+
struct IntIdentity
255+
{
256+
[[maybe_unused]] int operator()(int x) const { return x; }
257+
};
258+
259+
} // namespace
260+
252261
/** Convert from one power-of-2 number base to another. */
253-
template<int frombits, int tobits, bool pad, typename O, typename I>
254-
bool ConvertBits(const O& outfn, I it, I end) {
262+
template<int frombits, int tobits, bool pad, typename O, typename It, typename I = IntIdentity>
263+
bool ConvertBits(O outfn, It it, It end, I infn = {}) {
255264
size_t acc = 0;
256265
size_t bits = 0;
257266
constexpr size_t maxv = (1 << tobits) - 1;
258267
constexpr size_t max_acc = (1 << (frombits + tobits - 1)) - 1;
259268
while (it != end) {
260-
acc = ((acc << frombits) | *it) & max_acc;
269+
int v = infn(*it);
270+
if (v < 0) return false;
271+
acc = ((acc << frombits) | v) & max_acc;
261272
bits += frombits;
262273
while (bits >= tobits) {
263274
bits -= tobits;

0 commit comments

Comments
 (0)