rapidyaml  0.10.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 2111 of file charconv.hpp.

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

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

Referenced by c4::atof_first(), c4::atox(), and c4::from_chars().

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

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

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

Referenced by c4::from_chars_first().