rapidyaml  0.13.0
parse and emit YAML, and do it fast
atod: chars to float64

Functions

bool c4::atod (csubstr str, double *v) noexcept
 Convert a string to a double precision real number. More...
 
size_t c4::atod_first (csubstr str, double *v) noexcept
 Convert a string to a double precision real number. More...
 

Detailed Description

Function Documentation

◆ atod()

bool c4::atod ( csubstr  str,
double *  v 
)
inlinenoexcept

Convert a string to a double precision real number.

The input string must be trimmed to the value, ie no leading or trailing whitespace can be present.

Returns
true iff the conversion succeeded
See also
atod_first() if the string is not trimmed

Definition at line 2167 of file charconv.hpp.

2168 {
2169  C4_ASSERT(str.len > 0);
2170  C4_ASSERT(str.triml(" \r\t\n").len == str.len);
2171 #if C4CORE_HAVE_FAST_FLOAT
2172  // fastfloat cannot parse hexadecimal floats
2173  bool isneg = (str.str[0] == '-');
2174  csubstr rem = str.sub(isneg || str.str[0] == '+');
2175  if(!(rem.len >= 2 && (rem.str[0] == '0' && (rem.str[1] == 'x' || rem.str[1] == 'X'))))
2176  {
2177  fast_float::from_chars_result result;
2178  #ifndef CLANG_TIDY // suppress a false-positive error (cannot be done with NOLINT: https://stackoverflow.com/questions/62838193/ )
2179  result = fast_float::from_chars(str.str, str.str + str.len, *v);
2180  #else
2181  result = {};
2182  #endif
2183  return result.ec == std::errc();
2184  }
2185  else if(detail::scan_rhex(rem.sub(2), v))
2186  {
2187  *v *= isneg ? -1. : 1.;
2188  return true;
2189  }
2190  return false;
2191 #elif C4CORE_HAVE_STD_FROMCHARS
2192  std::from_chars_result result;
2193  result = std::from_chars(str.str, str.str + str.len, *v);
2194  return result.ec == std::errc();
2195 #else
2196  csubstr rem = str.sub(str.str[0] == '-' || str.str[0] == '+');
2197  if(!(rem.len >= 2 && (rem.str[0] == '0' && (rem.str[1] == 'x' || rem.str[1] == 'X'))))
2198  return detail::scan_one(str, "lf", v) != csubstr::npos;
2199  else
2200  return detail::scan_one(str, "la", v) != csubstr::npos;
2201 #endif
2202 }
bool from_chars(csubstr buf, substr *v) noexcept
Definition: charconv.hpp:2600
@ npos
a null string position
Definition: common.hpp:258

◆ atod_first()

size_t c4::atod_first ( csubstr  str,
double *  v 
)
inlinenoexcept

Convert a string to a double precision real number.

Leading whitespace is skipped until valid characters are found.

Returns
the number of characters read from the string, or npos if conversion was not successful or if the string was empty

Definition at line 2209 of file charconv.hpp.

2210 {
2211  csubstr trimmed = str.first_real_span();
2212  if(trimmed.len == 0)
2213  return csubstr::npos;
2214  if(atod(trimmed, v))
2215  return static_cast<size_t>(trimmed.end() - str.begin());
2216  return csubstr::npos;
2217 }
bool atod(csubstr str, double *v) noexcept
Convert a string to a double precision real number.
Definition: charconv.hpp:2167