| 1 |
#include "fast_float/fast_float.h" |
| 2 |
|
| 3 |
#include <cctype> |
| 4 |
#include <iostream> |
| 5 |
#include <stdexcept> |
| 6 |
#include <string> |
| 7 |
#include <system_error> |
| 8 |
#include <vector> |
| 9 |
|
| 10 |
inline void Assert(bool Assertion) { |
| 11 |
if (!Assertion) { |
| 12 |
throw std::runtime_error("bug"); |
| 13 |
} |
| 14 |
} |
| 15 |
|
| 16 |
template <typename T> bool test() { |
| 17 |
std::string input = "0.156250000000000000000000000000000000000000 " |
| 18 |
"3.14159265358979323846264338327950288419716939937510 " |
| 19 |
"2.71828182845904523536028747135266249775724709369995"; |
| 20 |
std::vector<T> answers = {T(0.15625), T(3.141592653589793), |
| 21 |
T(2.718281828459045)}; |
| 22 |
char const *begin = input.data(); |
| 23 |
char const *end = input.data() + input.size(); |
| 24 |
for (size_t i = 0; i < answers.size(); i++) { |
| 25 |
T result_value; |
| 26 |
while ((begin < end) && (std::isspace(*begin))) { |
| 27 |
begin++; |
| 28 |
} |
| 29 |
auto result = fast_float::from_chars(begin, end, result_value); |
| 30 |
if (result.ec != std::errc() && |
| 31 |
result.ec != std::errc::result_out_of_range) { |
| 32 |
printf("parsing %.*s\n", int(end - begin), begin); |
| 33 |
std::cerr << " I could not parse " << std::endl; |
| 34 |
return false; |
| 35 |
} |
| 36 |
if (result_value != answers[i]) { |
| 37 |
printf("parsing %.*s\n", int(end - begin), begin); |
| 38 |
std::cerr << " Mismatch " << std::endl; |
| 39 |
std::cerr << " Expected " << answers[i] << std::endl; |
| 40 |
std::cerr << " Got " << result_value << std::endl; |
| 41 |
|
| 42 |
return false; |
| 43 |
} |
| 44 |
begin = result.ptr; |
| 45 |
} |
| 46 |
if (begin != end) { |
| 47 |
std::cerr << " bad ending " << std::endl; |
| 48 |
return false; |
| 49 |
} |
| 50 |
return true; |
| 51 |
} |
| 52 |
|
| 53 |
int main() { |
| 54 |
|
| 55 |
std::cout << "32 bits checks" << std::endl; |
| 56 |
Assert(test<float>()); |
| 57 |
|
| 58 |
std::cout << "64 bits checks" << std::endl; |
| 59 |
Assert(test<double>()); |
| 60 |
|
| 61 |
std::cout << "All ok" << std::endl; |
| 62 |
return EXIT_SUCCESS; |
| 63 |
} |