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.
This commit is contained in:
Pentarctagon 2023-05-23 17:39:51 -05:00
parent ec40bd211d
commit ed45fcae67

View File

@ -52,9 +52,12 @@ char itoa(unsigned value, const std::string& map)
std::vector<uint8_t> generic_decode_be(std::string_view in, const std::vector<int>& 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<uint8_t> out;
out.reserve(length);
@ -77,7 +80,7 @@ std::vector<uint8_t> generic_decode_be(std::string_view in, const std::vector<in
val &= 0xFFFF; // Prevent shifting bits off the left end, which is UB
}
}
if(static_cast<int>(out.size()) != length) {
if(out.size() != length) {
return {};
}
@ -86,13 +89,16 @@ std::vector<uint8_t> generic_decode_be(std::string_view in, const std::vector<in
std::vector<uint8_t> generic_decode_le(std::string_view in, const std::vector<int>& 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<uint8_t> 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]];