Clamp at the first non-number character in readOpcode

This commit is contained in:
Paul Ferrand 2020-05-30 00:15:53 +02:00
parent 5e74f910c6
commit 0898030e4c

View file

@ -115,20 +115,23 @@ private:
template <typename ValueType, absl::enable_if_t<std::is_integral<ValueType>::value, int> = 0> template <typename ValueType, absl::enable_if_t<std::is_integral<ValueType>::value, int> = 0>
inline absl::optional<ValueType> readOpcode(absl::string_view value, const Range<ValueType>& validRange) inline absl::optional<ValueType> readOpcode(absl::string_view value, const Range<ValueType>& validRange)
{ {
int64_t returnedValue; const auto numberEnd = value.find_first_not_of("-1234567890.");
if (!absl::SimpleAtoi(value, &returnedValue)) { value = value.substr(0, numberEnd);
float floatValue;
if (!absl::SimpleAtof(value, &floatValue))
return {};
returnedValue = static_cast<int64_t>(floatValue);
}
if (returnedValue > std::numeric_limits<ValueType>::max()) int64_t returnedValue;
returnedValue = std::numeric_limits<ValueType>::max(); if (!absl::SimpleAtoi(value, &returnedValue)) {
if (returnedValue < std::numeric_limits<ValueType>::min()) float floatValue;
returnedValue = std::numeric_limits<ValueType>::min(); if (!absl::SimpleAtof(value, &floatValue))
return {};
returnedValue = static_cast<int64_t>(floatValue);
}
return validRange.clamp(static_cast<ValueType>(returnedValue)); if (returnedValue > std::numeric_limits<ValueType>::max())
returnedValue = std::numeric_limits<ValueType>::max();
if (returnedValue < std::numeric_limits<ValueType>::min())
returnedValue = std::numeric_limits<ValueType>::min();
return validRange.clamp(static_cast<ValueType>(returnedValue));
} }
/** /**
@ -144,8 +147,11 @@ inline absl::optional<ValueType> readOpcode(absl::string_view value, const Range
template <typename ValueType, absl::enable_if_t<std::is_floating_point<ValueType>::value, int> = 0> template <typename ValueType, absl::enable_if_t<std::is_floating_point<ValueType>::value, int> = 0>
inline absl::optional<ValueType> readOpcode(absl::string_view value, const Range<ValueType>& validRange) inline absl::optional<ValueType> readOpcode(absl::string_view value, const Range<ValueType>& validRange)
{ {
const auto numberEnd = value.find_first_not_of("-1234567890.");
value = value.substr(0, numberEnd);
float returnedValue; float returnedValue;
if (!absl::SimpleAtof(value, &returnedValue)) if (!absl::SimpleAtof(value.substr(0, numberEnd), &returnedValue))
return absl::nullopt; return absl::nullopt;
return validRange.clamp(returnedValue); return validRange.clamp(returnedValue);