| 925 | |
| 926 | template <typename DecimalClass> |
| 927 | Status SimpleDecimalFromString(const char* type_name, std::string_view s, |
| 928 | DecimalClass* out, int32_t* precision, int32_t* scale) { |
| 929 | if (s.empty()) { |
| 930 | return Status::Invalid("Empty string cannot be converted to ", type_name); |
| 931 | } |
| 932 | |
| 933 | DecimalComponents dec; |
| 934 | if (!ParseDecimalComponents(s.data(), s.size(), &dec)) { |
| 935 | return Status::Invalid("The string '", s, "' is not a valid ", type_name, " number"); |
| 936 | } |
| 937 | |
| 938 | // count number of significant digits (without leading zeros) |
| 939 | size_t first_non_zero = dec.whole_digits.find_first_not_of('0'); |
| 940 | size_t significant_digits = dec.fractional_digits.size(); |
| 941 | if (first_non_zero != std::string::npos) { |
| 942 | significant_digits += dec.whole_digits.size() - first_non_zero; |
| 943 | } |
| 944 | int32_t parsed_precision = static_cast<int32_t>(significant_digits); |
| 945 | |
| 946 | int32_t parsed_scale = 0; |
| 947 | if (dec.has_exponent) { |
| 948 | auto adjusted_exponent = dec.exponent; |
| 949 | parsed_scale = |
| 950 | -adjusted_exponent + static_cast<int32_t>(dec.fractional_digits.size()); |
| 951 | } else { |
| 952 | parsed_scale = static_cast<int32_t>(dec.fractional_digits.size()); |
| 953 | } |
| 954 | |
| 955 | if (out != nullptr) { |
| 956 | uint64_t value{0}; |
| 957 | ShiftAndAdd(dec.whole_digits, &value, 1); |
| 958 | ShiftAndAdd(dec.fractional_digits, &value, 1); |
| 959 | if (value > static_cast<uint64_t>( |
| 960 | std::numeric_limits<typename DecimalClass::ValueType>::max())) { |
| 961 | return Status::Invalid("The string '", s, "' cannot be represented as ", type_name); |
| 962 | } |
| 963 | |
| 964 | *out = DecimalClass(value); |
| 965 | if (dec.sign == '-') { |
| 966 | out->Negate(); |
| 967 | } |
| 968 | } |
| 969 | |
| 970 | if (parsed_scale < 0) { |
| 971 | // Force the scale to zero, to avoid negative scales (due to compatibility issues |
| 972 | // with external systems such as databases) |
| 973 | if (-parsed_scale > DecimalClass::kMaxScale) { |
| 974 | return Status::Invalid("The string '", s, "' cannot be represented as ", type_name); |
| 975 | } |
| 976 | if (out != nullptr) { |
| 977 | *out *= DecimalClass::GetScaleMultiplier(-parsed_scale); |
| 978 | } |
| 979 | parsed_precision -= parsed_scale; |
| 980 | parsed_scale = 0; |
| 981 | } |
| 982 | |
| 983 | if (precision != nullptr) { |
| 984 | *precision = parsed_precision; |
no test coverage detected