From 1a72d62152bfdd7c5c2b2704b679f894e7d35e37 Mon Sep 17 00:00:00 2001 From: Pieter Wuille Date: Mon, 4 Apr 2022 11:58:54 -0400 Subject: [PATCH] Generalize ConvertBits to permit transforming the input --- src/util/strencodings.h | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/util/strencodings.h b/src/util/strencodings.h index 27f6ec6e00b..8a277bac4a7 100644 --- a/src/util/strencodings.h +++ b/src/util/strencodings.h @@ -249,15 +249,26 @@ bool TimingResistantEqual(const T& a, const T& b) */ [[nodiscard]] bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out); +namespace { +/** Helper class for the default infn argument to ConvertBits (just returns the input). */ +struct IntIdentity +{ + [[maybe_unused]] int operator()(int x) const { return x; } +}; + +} // namespace + /** Convert from one power-of-2 number base to another. */ -template -bool ConvertBits(const O& outfn, I it, I end) { +template +bool ConvertBits(O outfn, It it, It end, I infn = {}) { size_t acc = 0; size_t bits = 0; constexpr size_t maxv = (1 << tobits) - 1; constexpr size_t max_acc = (1 << (frombits + tobits - 1)) - 1; while (it != end) { - acc = ((acc << frombits) | *it) & max_acc; + int v = infn(*it); + if (v < 0) return false; + acc = ((acc << frombits) | v) & max_acc; bits += frombits; while (bits >= tobits) { bits -= tobits;