rapidyaml  0.13.0
parse and emit YAML, and do it fast
atof: chars to float32

Functions

bool c4::atof (csubstr str, float *v) noexcept
 Convert a string to a single precision real number. More...
 
size_t c4::atof_first (csubstr str, float *v) noexcept
 Convert a string to a single precision real number. More...
 

Detailed Description

Function Documentation

◆ atof()

bool c4::atof ( csubstr  str,
float *  v 
)
inlinenoexcept

Convert a string to a single 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
atof_first() if the string is not trimmed

Definition at line 2106 of file charconv.hpp.

2107 {
2108  C4_ASSERT(str.len > 0);
2109  C4_ASSERT(str.triml(" \r\t\n").len == str.len);
2110 #if C4CORE_HAVE_FAST_FLOAT
2111  // fastfloat cannot parse hexadecimal floats
2112  bool isneg = (str.str[0] == '-');
2113  csubstr rem = str.sub(isneg || str.str[0] == '+');
2114  if(!(rem.len >= 2 && (rem.str[0] == '0' && (rem.str[1] == 'x' || rem.str[1] == 'X'))))
2115  {
2116  fast_float::from_chars_result result;
2117  result = fast_float::from_chars(str.str, str.str + str.len, *v);
2118  return result.ec == std::errc();
2119  }
2120  else if(detail::scan_rhex(rem.sub(2), v))
2121  {
2122  *v *= isneg ? -1.f : 1.f;
2123  return true;
2124  }
2125  return false;
2126 #elif C4CORE_HAVE_STD_FROMCHARS
2127  std::from_chars_result result;
2128  result = std::from_chars(str.str, str.str + str.len, *v);
2129  return result.ec == std::errc();
2130 #else
2131  csubstr rem = str.sub(str.str[0] == '-' || str.str[0] == '+');
2132  if(!(rem.len >= 2 && (rem.str[0] == '0' && (rem.str[1] == 'x' || rem.str[1] == 'X'))))
2133  return detail::scan_one(str, "f", v) != csubstr::npos;
2134  else
2135  return detail::scan_one(str, "a", v) != csubstr::npos;
2136 #endif
2137 }
bool from_chars(csubstr buf, substr *v) noexcept
Definition: charconv.hpp:2600
@ npos
a null string position
Definition: common.hpp:258

◆ atof_first()

size_t c4::atof_first ( csubstr  str,
float *  v 
)
inlinenoexcept

Convert a string to a single 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 2144 of file charconv.hpp.

2145 {
2146  csubstr trimmed = str.first_real_span();
2147  if(trimmed.len == 0)
2148  return csubstr::npos;
2149  if(atof(trimmed, v))
2150  return static_cast<size_t>(trimmed.end() - str.begin());
2151  return csubstr::npos;
2152 }
bool atof(csubstr str, float *v) noexcept
Convert a string to a single precision real number.
Definition: charconv.hpp:2106