rapidyaml  0.11.1
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 2110 of file charconv.hpp.

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

References c4::from_chars(), and c4::yml::npos.

◆ 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 2148 of file charconv.hpp.

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

References c4::atof(), and c4::yml::npos.