diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/conversions.h b/packages/react-native/ReactCommon/react/renderer/components/view/conversions.h index ef4202ce9580b8..c782e566ca2200 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/conversions.h @@ -31,6 +31,7 @@ #include #include #include +#include #include namespace facebook::react { @@ -64,6 +65,25 @@ inline float yogaFloatFromFloat(Float value) { return (float)value; } +/* + * Converts string to float only if the entire string is valid float. + */ +inline std::optional stringToFloat(const std::string& string) { + try { + size_t pos = 0; + auto result = std::stof(string, &pos); + // Check if entire string was valid + if (pos == string.length()) { + return result; + } + } catch (...) { + // Ignore, caller falls back to default value. + return std::nullopt; + } + + return std::nullopt; +} + /* * `yoga::FloatOptional` <-> React Native's `Float` * @@ -467,15 +487,15 @@ inline void fromRawValue( return; } else { if (stringValue.back() == '%') { - auto tryValue = folly::tryTo( - std::string_view(stringValue).substr(0, stringValue.length() - 1)); - if (tryValue.hasValue()) { + auto tryValue = + stringToFloat(stringValue.substr(0, stringValue.length() - 1)); + if (tryValue.has_value()) { result = yoga::StyleSizeLength::percent(tryValue.value()); return; } } else { - auto tryValue = folly::tryTo(stringValue); - if (tryValue.hasValue()) { + auto tryValue = stringToFloat(stringValue); + if (tryValue.has_value()) { result = yoga::StyleSizeLength::points(tryValue.value()); return; } @@ -499,15 +519,15 @@ inline void fromRawValue( return; } else { if (stringValue.back() == '%') { - auto tryValue = folly::tryTo( - std::string_view(stringValue).substr(0, stringValue.length() - 1)); - if (tryValue.hasValue()) { + auto tryValue = + stringToFloat(stringValue.substr(0, stringValue.length() - 1)); + if (tryValue.has_value()) { result = yoga::StyleLength::percent(tryValue.value()); return; } } else { - auto tryValue = folly::tryTo(stringValue); - if (tryValue.hasValue()) { + auto tryValue = stringToFloat(stringValue); + if (tryValue.has_value()) { result = yoga::StyleLength::points(tryValue.value()); return; } @@ -573,9 +593,9 @@ inline void fromRawValue( const auto stringValue = (std::string)value; if (stringValue.back() == '%') { - auto tryValue = folly::tryTo( - std::string_view(stringValue).substr(0, stringValue.length() - 1)); - if (tryValue.hasValue()) { + auto tryValue = + stringToFloat(stringValue.substr(0, stringValue.length() - 1)); + if (tryValue.has_value()) { valueUnit = ValueUnit(tryValue.value(), UnitType::Percent); } }