Avoid UTF-8 conversion in wide versions of StringTo{Float,Double}()
StringToFloat() and StringToDouble() call into the fast_float library
internally, and fast_float can handle non-ASCII input. So pass
WideStringView inputs directly in, instead of first converting to
ByteString.
Change-Id: If601eb1218f16cf9c338f892a3f27234cb02a17b
Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/128470
Commit-Queue: Lei Zhang <thestig@chromium.org>
Reviewed-by: Thomas Sepez <tsepez@google.com>
Reviewed-by: Tom Sepez <tsepez@chromium.org>
diff --git a/core/fxcrt/fx_string.cpp b/core/fxcrt/fx_string.cpp
index 212620d..fa4f5f7 100644
--- a/core/fxcrt/fx_string.cpp
+++ b/core/fxcrt/fx_string.cpp
@@ -99,9 +99,10 @@
return neg ? ~num + 1 : num;
}
-// Intended to work for the cases where `T` is float or double.
-template <class T>
-T StringToFloatImpl(ByteStringView strc) {
+// Intended to work for the cases where `ReturnType` is float or double, and
+// `InputType` is ByteStringView or WideStringView.
+template <class ReturnType, class InputType>
+ReturnType StringToFloatImpl(InputType strc) {
// Skip leading whitespaces.
size_t start = 0;
size_t len = strc.GetLength();
@@ -114,13 +115,13 @@
++start;
}
- ByteStringView sub_strc = strc.Substr(start, len - start);
+ InputType sub_strc = strc.Substr(start, len - start);
- T value;
+ ReturnType value;
auto result = fast_float::from_chars(sub_strc.begin(), sub_strc.end(), value);
// Return 0 for parsing errors. Some examples of errors are an empty string
- // and a string that cannot be converted to T.
+ // and a string that cannot be converted to `ReturnType`.
return result.ec == std::errc() || result.ec == std::errc::result_out_of_range
? value
: 0;
@@ -172,7 +173,7 @@
}
float StringToFloat(WideStringView wsStr) {
- return StringToFloat(FX_UTF8Encode(wsStr).AsStringView());
+ return StringToFloatImpl<float>(wsStr);
}
double StringToDouble(ByteStringView strc) {
@@ -180,7 +181,7 @@
}
double StringToDouble(WideStringView wsStr) {
- return StringToDouble(FX_UTF8Encode(wsStr).AsStringView());
+ return StringToFloatImpl<double>(wsStr);
}
namespace fxcrt {