Debian Codegraph @

tests/exhaustive32_64.cpp

raw
1
2 #include "fast_float/fast_float.h"
3
4 #include <cassert>
5 #include <cmath>
6 #include <cstdio>
7 #include <ios>
8 #include <iostream>
9 #include <limits>
10 #include <string>
11 #include <system_error>
12
13 template <typename T> char *to_string(T d, char *buffer) {
14 auto written = std::snprintf(buffer, 64, "%.*e",
15 std::numeric_limits<T>::max_digits10 - 1, d);
16 return buffer + written;
17 }
18
19 bool basic_test_64bit(std::string vals, double val) {
20 double result_value;
21 auto result = fast_float::from_chars(vals.data(), vals.data() + vals.size(),
22 result_value);
23 if (result.ec != std::errc() && result.ec != std::errc::result_out_of_range) {
24 std::cerr << " I could not parse " << vals << std::endl;
25 return false;
26 }
27 if (std::isnan(val)) {
28 if (!std::isnan(result_value)) {
29 std::cerr << vals << std::endl;
30 std::cerr << "not nan" << result_value << std::endl;
31 return false;
32 }
33 } else if (copysign(1, result_value) != copysign(1, val)) {
34 std::cerr << "I got " << std::hexfloat << result_value
35 << " but I was expecting " << val << std::endl;
36 return false;
37 } else if (result_value != val) {
38 std::cerr << vals << std::endl;
39 std::cerr << "I got " << std::hexfloat << result_value
40 << " but I was expecting " << val << std::endl;
41 std::cerr << std::dec;
42 std::cerr << "string: " << vals << std::endl;
43 return false;
44 }
45 return true;
46 }
47
48 void all_32bit_values() {
49 char buffer[64];
50 for (uint64_t w = 0; w <= 0xFFFFFFFF; w++) {
51 float v32;
52 if ((w % 1048576) == 0) {
53 std::cout << ".";
54 std::cout.flush();
55 }
56 uint32_t word = uint32_t(w);
57 memcpy(&v32, &word, sizeof(v32));
58 double v = v32;
59
60 {
61 char const *string_end = to_string(v, buffer);
62 std::string s(buffer, size_t(string_end - buffer));
63 if (!basic_test_64bit(s, v)) {
64 return;
65 }
66 }
67 }
68 std::cout << std::endl;
69 }
70
71 int main() {
72 all_32bit_values();
73 std::cout << std::endl;
74 std::cout << "all ok" << std::endl;
75 return EXIT_SUCCESS;
76 }