From ed45fcae676d4039798e7eb6bfcbebdbcc642833 Mon Sep 17 00:00:00 2001 From: Pentarctagon Date: Tue, 23 May 2023 17:39:51 -0500 Subject: [PATCH] Implement one part of the -Wshorten-64-to-32 changes from #7451 Mainly since it's particularly non-obvious why it currently works for `generic_decode_be()` in the case when `in.find_last_not_of("=")` doesn't find anything: * It returns npos, which is the max value of an std::size_t * this turns into -1 when assigned to an int * -1 + 1 equals 0 * 0 * 8 / 6 is still 0 * `reserve(0)` is pointless, but at least valid This is not a behavior change because it already returns nothing after it does all its work if `out.size()` doesn't equal 0 in this case. And for `generic_decode_le()` in the case when `in.find_last_not_of("=")` doesn't find anything: * It returns npos, which is the max value of an std::size_t * this turns into -1 when assigned to an int * -1 * 8 / 6 is -0.75, which truncates to 0 because this is integer division * `reserve(0)` is pointless, but at least valid This is not a behavior change since the for-loop starts i at 0 and then checks that `i <= last_char`, however last_char is -1 so the loop is just skipped. --- src/serialization/base64.cpp | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/serialization/base64.cpp b/src/serialization/base64.cpp index 390bd1e0130..f8794493ecb 100644 --- a/src/serialization/base64.cpp +++ b/src/serialization/base64.cpp @@ -52,9 +52,12 @@ char itoa(unsigned value, const std::string& map) std::vector generic_decode_be(std::string_view in, const std::vector& atoi_map) { - const int last_char = in.find_last_not_of("="); - const int num_chars = last_char + 1; - const int length = num_chars * 6 / 8; + const std::size_t last_char = in.find_last_not_of("="); + if(last_char == std::string::npos) { + return {}; + } + const std::size_t num_chars = last_char + 1; + const std::size_t length = num_chars * 6 / 8; std::vector out; out.reserve(length); @@ -77,7 +80,7 @@ std::vector generic_decode_be(std::string_view in, const std::vector(out.size()) != length) { + if(out.size() != length) { return {}; } @@ -86,13 +89,16 @@ std::vector generic_decode_be(std::string_view in, const std::vector generic_decode_le(std::string_view in, const std::vector& atoi_map) { - const int last_char = in.find_last_not_of("="); - const int length = last_char * 6 / 8; + const std::size_t last_char = in.find_last_not_of("="); + if(last_char == std::string::npos) { + return {}; + } + const std::size_t length = last_char * 6 / 8; std::vector out; out.reserve(length); - for(int i = 0; i <= last_char; i += 4) { + for(std::size_t i = 0; i <= last_char; i += 4) { //add first char (always) unsigned value = atoi_map[in[i]];