Skip to content

Commit

Permalink
Replace a float cast-attempt with an empty catch block by the excepti…
Browse files Browse the repository at this point in the history
…on-less C-style std::strtof call. It's used a lot during map load.
  • Loading branch information
codereader committed Aug 8, 2021
1 parent 1f5b338 commit a117d94
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
15 changes: 15 additions & 0 deletions libs/string/convert.h
Expand Up @@ -3,6 +3,7 @@
#include "math/Vector3.h"
#include "math/Vector4.h"
#include <sstream>
#include <cstdlib>

namespace string
{
Expand Down Expand Up @@ -242,6 +243,20 @@ template<typename Src> float to_float(const Src& src)
}
#endif

// Attempts to convert the given source string to a float value,
// returning true on success. The value reference will then be holding
// the resulting float value (or 0 in case of failure).
// Note: this is using the exception-less std::strtof, making it preferable
// over the string::convert<float> method (in certain hot code paths).
inline bool tryConvertToFloat(const std::string& src, float& value)
{
char* lastChar;
auto* firstChar = src.c_str();
value = std::strtof(firstChar, &lastChar);

return lastChar != firstChar;
}

// Convert the given type to a std::string
template<typename Src>
inline std::string to_string(const Src& value)
Expand Down
15 changes: 6 additions & 9 deletions radiantcore/shaders/ShaderExpression.cpp
Expand Up @@ -338,16 +338,13 @@ class ShaderExpressionParser
else
{
// Attempt to convert the token into a floating point value
try
{
float value = std::stof(token);

_tokeniser.nextToken(); // valid token, exhaust
float value;
if (string::tryConvertToFloat(token, value))
{
_tokeniser.nextToken(); // valid token, exhaust

return std::make_shared<ConstantExpression>(value);
}
catch (std::invalid_argument&)
{}
return std::make_shared<ConstantExpression>(value);
}
}
}

Expand Down

0 comments on commit a117d94

Please sign in to comment.