1 // Copyright 2018 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "absl/strings/charconv.h"
16
17 #include <cfloat>
18 #include <cmath>
19 #include <cstdlib>
20 #include <functional>
21 #include <limits>
22 #include <string>
23 #include <system_error> // NOLINT(build/c++11)
24
25 #include "gtest/gtest.h"
26 #include "absl/strings/internal/pow10_helper.h"
27 #include "absl/strings/str_cat.h"
28 #include "absl/strings/str_format.h"
29 #include "absl/strings/string_view.h"
30
31 #ifdef _MSC_FULL_VER
32 #define ABSL_COMPILER_DOES_EXACT_ROUNDING 0
33 #define ABSL_STRTOD_HANDLES_NAN_CORRECTLY 0
34 #else
35 #define ABSL_COMPILER_DOES_EXACT_ROUNDING 1
36 #define ABSL_STRTOD_HANDLES_NAN_CORRECTLY 1
37 #endif
38
39 namespace {
40
41 using absl::strings_internal::Pow10;
42
43 #if ABSL_COMPILER_DOES_EXACT_ROUNDING
44
45 // Tests that the given string is accepted by absl::from_chars, and that it
46 // converts exactly equal to the given number.
TestDoubleParse(absl::string_view str,double expected_number)47 void TestDoubleParse(absl::string_view str, double expected_number) {
48 SCOPED_TRACE(str);
49 double actual_number = 0.0;
50 absl::from_chars_result result =
51 absl::from_chars(str.data(), str.data() + str.length(), actual_number);
52 EXPECT_EQ(result.ec, std::errc());
53 EXPECT_EQ(result.ptr, str.data() + str.length());
54 EXPECT_EQ(actual_number, expected_number);
55 }
56
TestFloatParse(absl::string_view str,float expected_number)57 void TestFloatParse(absl::string_view str, float expected_number) {
58 SCOPED_TRACE(str);
59 float actual_number = 0.0;
60 absl::from_chars_result result =
61 absl::from_chars(str.data(), str.data() + str.length(), actual_number);
62 EXPECT_EQ(result.ec, std::errc());
63 EXPECT_EQ(result.ptr, str.data() + str.length());
64 EXPECT_EQ(actual_number, expected_number);
65 }
66
67 // Tests that the given double or single precision floating point literal is
68 // parsed correctly by absl::from_chars.
69 //
70 // These convenience macros assume that the C++ compiler being used also does
71 // fully correct decimal-to-binary conversions.
72 #define FROM_CHARS_TEST_DOUBLE(number) \
73 { \
74 TestDoubleParse(#number, number); \
75 TestDoubleParse("-" #number, -number); \
76 }
77
78 #define FROM_CHARS_TEST_FLOAT(number) \
79 { \
80 TestFloatParse(#number, number##f); \
81 TestFloatParse("-" #number, -number##f); \
82 }
83
TEST(FromChars,NearRoundingCases)84 TEST(FromChars, NearRoundingCases) {
85 // Cases from "A Program for Testing IEEE Decimal-Binary Conversion"
86 // by Vern Paxson.
87
88 // Forms that should round towards zero. (These are the hardest cases for
89 // each decimal mantissa size.)
90 FROM_CHARS_TEST_DOUBLE(5.e125);
91 FROM_CHARS_TEST_DOUBLE(69.e267);
92 FROM_CHARS_TEST_DOUBLE(999.e-026);
93 FROM_CHARS_TEST_DOUBLE(7861.e-034);
94 FROM_CHARS_TEST_DOUBLE(75569.e-254);
95 FROM_CHARS_TEST_DOUBLE(928609.e-261);
96 FROM_CHARS_TEST_DOUBLE(9210917.e080);
97 FROM_CHARS_TEST_DOUBLE(84863171.e114);
98 FROM_CHARS_TEST_DOUBLE(653777767.e273);
99 FROM_CHARS_TEST_DOUBLE(5232604057.e-298);
100 FROM_CHARS_TEST_DOUBLE(27235667517.e-109);
101 FROM_CHARS_TEST_DOUBLE(653532977297.e-123);
102 FROM_CHARS_TEST_DOUBLE(3142213164987.e-294);
103 FROM_CHARS_TEST_DOUBLE(46202199371337.e-072);
104 FROM_CHARS_TEST_DOUBLE(231010996856685.e-073);
105 FROM_CHARS_TEST_DOUBLE(9324754620109615.e212);
106 FROM_CHARS_TEST_DOUBLE(78459735791271921.e049);
107 FROM_CHARS_TEST_DOUBLE(272104041512242479.e200);
108 FROM_CHARS_TEST_DOUBLE(6802601037806061975.e198);
109 FROM_CHARS_TEST_DOUBLE(20505426358836677347.e-221);
110 FROM_CHARS_TEST_DOUBLE(836168422905420598437.e-234);
111 FROM_CHARS_TEST_DOUBLE(4891559871276714924261.e222);
112 FROM_CHARS_TEST_FLOAT(5.e-20);
113 FROM_CHARS_TEST_FLOAT(67.e14);
114 FROM_CHARS_TEST_FLOAT(985.e15);
115 FROM_CHARS_TEST_FLOAT(7693.e-42);
116 FROM_CHARS_TEST_FLOAT(55895.e-16);
117 FROM_CHARS_TEST_FLOAT(996622.e-44);
118 FROM_CHARS_TEST_FLOAT(7038531.e-32);
119 FROM_CHARS_TEST_FLOAT(60419369.e-46);
120 FROM_CHARS_TEST_FLOAT(702990899.e-20);
121 FROM_CHARS_TEST_FLOAT(6930161142.e-48);
122 FROM_CHARS_TEST_FLOAT(25933168707.e-13);
123 FROM_CHARS_TEST_FLOAT(596428896559.e20);
124
125 // Similarly, forms that should round away from zero.
126 FROM_CHARS_TEST_DOUBLE(9.e-265);
127 FROM_CHARS_TEST_DOUBLE(85.e-037);
128 FROM_CHARS_TEST_DOUBLE(623.e100);
129 FROM_CHARS_TEST_DOUBLE(3571.e263);
130 FROM_CHARS_TEST_DOUBLE(81661.e153);
131 FROM_CHARS_TEST_DOUBLE(920657.e-023);
132 FROM_CHARS_TEST_DOUBLE(4603285.e-024);
133 FROM_CHARS_TEST_DOUBLE(87575437.e-309);
134 FROM_CHARS_TEST_DOUBLE(245540327.e122);
135 FROM_CHARS_TEST_DOUBLE(6138508175.e120);
136 FROM_CHARS_TEST_DOUBLE(83356057653.e193);
137 FROM_CHARS_TEST_DOUBLE(619534293513.e124);
138 FROM_CHARS_TEST_DOUBLE(2335141086879.e218);
139 FROM_CHARS_TEST_DOUBLE(36167929443327.e-159);
140 FROM_CHARS_TEST_DOUBLE(609610927149051.e-255);
141 FROM_CHARS_TEST_DOUBLE(3743626360493413.e-165);
142 FROM_CHARS_TEST_DOUBLE(94080055902682397.e-242);
143 FROM_CHARS_TEST_DOUBLE(899810892172646163.e283);
144 FROM_CHARS_TEST_DOUBLE(7120190517612959703.e120);
145 FROM_CHARS_TEST_DOUBLE(25188282901709339043.e-252);
146 FROM_CHARS_TEST_DOUBLE(308984926168550152811.e-052);
147 FROM_CHARS_TEST_DOUBLE(6372891218502368041059.e064);
148 FROM_CHARS_TEST_FLOAT(3.e-23);
149 FROM_CHARS_TEST_FLOAT(57.e18);
150 FROM_CHARS_TEST_FLOAT(789.e-35);
151 FROM_CHARS_TEST_FLOAT(2539.e-18);
152 FROM_CHARS_TEST_FLOAT(76173.e28);
153 FROM_CHARS_TEST_FLOAT(887745.e-11);
154 FROM_CHARS_TEST_FLOAT(5382571.e-37);
155 FROM_CHARS_TEST_FLOAT(82381273.e-35);
156 FROM_CHARS_TEST_FLOAT(750486563.e-38);
157 FROM_CHARS_TEST_FLOAT(3752432815.e-39);
158 FROM_CHARS_TEST_FLOAT(75224575729.e-45);
159 FROM_CHARS_TEST_FLOAT(459926601011.e15);
160 }
161
162 #undef FROM_CHARS_TEST_DOUBLE
163 #undef FROM_CHARS_TEST_FLOAT
164 #endif
165
ToFloat(absl::string_view s)166 float ToFloat(absl::string_view s) {
167 float f;
168 absl::from_chars(s.data(), s.data() + s.size(), f);
169 return f;
170 }
171
ToDouble(absl::string_view s)172 double ToDouble(absl::string_view s) {
173 double d;
174 absl::from_chars(s.data(), s.data() + s.size(), d);
175 return d;
176 }
177
178 // A duplication of the test cases in "NearRoundingCases" above, but with
179 // expected values expressed with integers, using ldexp/ldexpf. These test
180 // cases will work even on compilers that do not accurately round floating point
181 // literals.
TEST(FromChars,NearRoundingCasesExplicit)182 TEST(FromChars, NearRoundingCasesExplicit) {
183 EXPECT_EQ(ToDouble("5.e125"), ldexp(6653062250012735, 365));
184 EXPECT_EQ(ToDouble("69.e267"), ldexp(4705683757438170, 841));
185 EXPECT_EQ(ToDouble("999.e-026"), ldexp(6798841691080350, -129));
186 EXPECT_EQ(ToDouble("7861.e-034"), ldexp(8975675289889240, -153));
187 EXPECT_EQ(ToDouble("75569.e-254"), ldexp(6091718967192243, -880));
188 EXPECT_EQ(ToDouble("928609.e-261"), ldexp(7849264900213743, -900));
189 EXPECT_EQ(ToDouble("9210917.e080"), ldexp(8341110837370930, 236));
190 EXPECT_EQ(ToDouble("84863171.e114"), ldexp(4625202867375927, 353));
191 EXPECT_EQ(ToDouble("653777767.e273"), ldexp(5068902999763073, 884));
192 EXPECT_EQ(ToDouble("5232604057.e-298"), ldexp(5741343011915040, -1010));
193 EXPECT_EQ(ToDouble("27235667517.e-109"), ldexp(6707124626673586, -380));
194 EXPECT_EQ(ToDouble("653532977297.e-123"), ldexp(7078246407265384, -422));
195 EXPECT_EQ(ToDouble("3142213164987.e-294"), ldexp(8219991337640559, -988));
196 EXPECT_EQ(ToDouble("46202199371337.e-072"), ldexp(5224462102115359, -246));
197 EXPECT_EQ(ToDouble("231010996856685.e-073"), ldexp(5224462102115359, -247));
198 EXPECT_EQ(ToDouble("9324754620109615.e212"), ldexp(5539753864394442, 705));
199 EXPECT_EQ(ToDouble("78459735791271921.e049"), ldexp(8388176519442766, 166));
200 EXPECT_EQ(ToDouble("272104041512242479.e200"), ldexp(5554409530847367, 670));
201 EXPECT_EQ(ToDouble("6802601037806061975.e198"), ldexp(5554409530847367, 668));
202 EXPECT_EQ(ToDouble("20505426358836677347.e-221"),
203 ldexp(4524032052079546, -722));
204 EXPECT_EQ(ToDouble("836168422905420598437.e-234"),
205 ldexp(5070963299887562, -760));
206 EXPECT_EQ(ToDouble("4891559871276714924261.e222"),
207 ldexp(6452687840519111, 757));
208 EXPECT_EQ(ToFloat("5.e-20"), ldexpf(15474250, -88));
209 EXPECT_EQ(ToFloat("67.e14"), ldexpf(12479722, 29));
210 EXPECT_EQ(ToFloat("985.e15"), ldexpf(14333636, 36));
211 EXPECT_EQ(ToFloat("7693.e-42"), ldexpf(10979816, -150));
212 EXPECT_EQ(ToFloat("55895.e-16"), ldexpf(12888509, -61));
213 EXPECT_EQ(ToFloat("996622.e-44"), ldexpf(14224264, -150));
214 EXPECT_EQ(ToFloat("7038531.e-32"), ldexpf(11420669, -107));
215 EXPECT_EQ(ToFloat("60419369.e-46"), ldexpf(8623340, -150));
216 EXPECT_EQ(ToFloat("702990899.e-20"), ldexpf(16209866, -61));
217 EXPECT_EQ(ToFloat("6930161142.e-48"), ldexpf(9891056, -150));
218 EXPECT_EQ(ToFloat("25933168707.e-13"), ldexpf(11138211, -32));
219 EXPECT_EQ(ToFloat("596428896559.e20"), ldexpf(12333860, 82));
220
221
222 EXPECT_EQ(ToDouble("9.e-265"), ldexp(8168427841980010, -930));
223 EXPECT_EQ(ToDouble("85.e-037"), ldexp(6360455125664090, -169));
224 EXPECT_EQ(ToDouble("623.e100"), ldexp(6263531988747231, 289));
225 EXPECT_EQ(ToDouble("3571.e263"), ldexp(6234526311072170, 833));
226 EXPECT_EQ(ToDouble("81661.e153"), ldexp(6696636728760206, 472));
227 EXPECT_EQ(ToDouble("920657.e-023"), ldexp(5975405561110124, -109));
228 EXPECT_EQ(ToDouble("4603285.e-024"), ldexp(5975405561110124, -110));
229 EXPECT_EQ(ToDouble("87575437.e-309"), ldexp(8452160731874668, -1053));
230 EXPECT_EQ(ToDouble("245540327.e122"), ldexp(4985336549131723, 381));
231 EXPECT_EQ(ToDouble("6138508175.e120"), ldexp(4985336549131723, 379));
232 EXPECT_EQ(ToDouble("83356057653.e193"), ldexp(5986732817132056, 625));
233 EXPECT_EQ(ToDouble("619534293513.e124"), ldexp(4798406992060657, 399));
234 EXPECT_EQ(ToDouble("2335141086879.e218"), ldexp(5419088166961646, 713));
235 EXPECT_EQ(ToDouble("36167929443327.e-159"), ldexp(8135819834632444, -536));
236 EXPECT_EQ(ToDouble("609610927149051.e-255"), ldexp(4576664294594737, -850));
237 EXPECT_EQ(ToDouble("3743626360493413.e-165"), ldexp(6898586531774201, -549));
238 EXPECT_EQ(ToDouble("94080055902682397.e-242"), ldexp(6273271706052298, -800));
239 EXPECT_EQ(ToDouble("899810892172646163.e283"), ldexp(7563892574477827, 947));
240 EXPECT_EQ(ToDouble("7120190517612959703.e120"), ldexp(5385467232557565, 409));
241 EXPECT_EQ(ToDouble("25188282901709339043.e-252"),
242 ldexp(5635662608542340, -825));
243 EXPECT_EQ(ToDouble("308984926168550152811.e-052"),
244 ldexp(5644774693823803, -157));
245 EXPECT_EQ(ToDouble("6372891218502368041059.e064"),
246 ldexp(4616868614322430, 233));
247
248 EXPECT_EQ(ToFloat("3.e-23"), ldexpf(9507380, -98));
249 EXPECT_EQ(ToFloat("57.e18"), ldexpf(12960300, 42));
250 EXPECT_EQ(ToFloat("789.e-35"), ldexpf(10739312, -130));
251 EXPECT_EQ(ToFloat("2539.e-18"), ldexpf(11990089, -72));
252 EXPECT_EQ(ToFloat("76173.e28"), ldexpf(9845130, 86));
253 EXPECT_EQ(ToFloat("887745.e-11"), ldexpf(9760860, -40));
254 EXPECT_EQ(ToFloat("5382571.e-37"), ldexpf(11447463, -124));
255 EXPECT_EQ(ToFloat("82381273.e-35"), ldexpf(8554961, -113));
256 EXPECT_EQ(ToFloat("750486563.e-38"), ldexpf(9975678, -120));
257 EXPECT_EQ(ToFloat("3752432815.e-39"), ldexpf(9975678, -121));
258 EXPECT_EQ(ToFloat("75224575729.e-45"), ldexpf(13105970, -137));
259 EXPECT_EQ(ToFloat("459926601011.e15"), ldexpf(12466336, 65));
260 }
261
262 // Common test logic for converting a string which lies exactly halfway between
263 // two target floats.
264 //
265 // mantissa and exponent represent the precise value between two floating point
266 // numbers, `expected_low` and `expected_high`. The floating point
267 // representation to parse in `StrCat(mantissa, "e", exponent)`.
268 //
269 // This function checks that an input just slightly less than the exact value
270 // is rounded down to `expected_low`, and an input just slightly greater than
271 // the exact value is rounded up to `expected_high`.
272 //
273 // The exact value should round to `expected_half`, which must be either
274 // `expected_low` or `expected_high`.
275 template <typename FloatType>
TestHalfwayValue(const std::string & mantissa,int exponent,FloatType expected_low,FloatType expected_high,FloatType expected_half)276 void TestHalfwayValue(const std::string& mantissa, int exponent,
277 FloatType expected_low, FloatType expected_high,
278 FloatType expected_half) {
279 std::string low_rep = mantissa;
280 low_rep[low_rep.size() - 1] -= 1;
281 absl::StrAppend(&low_rep, std::string(1000, '9'), "e", exponent);
282
283 FloatType actual_low = 0;
284 absl::from_chars(low_rep.data(), low_rep.data() + low_rep.size(), actual_low);
285 EXPECT_EQ(expected_low, actual_low);
286
287 std::string high_rep =
288 absl::StrCat(mantissa, std::string(1000, '0'), "1e", exponent);
289 FloatType actual_high = 0;
290 absl::from_chars(high_rep.data(), high_rep.data() + high_rep.size(),
291 actual_high);
292 EXPECT_EQ(expected_high, actual_high);
293
294 std::string halfway_rep = absl::StrCat(mantissa, "e", exponent);
295 FloatType actual_half = 0;
296 absl::from_chars(halfway_rep.data(), halfway_rep.data() + halfway_rep.size(),
297 actual_half);
298 EXPECT_EQ(expected_half, actual_half);
299 }
300
TEST(FromChars,DoubleRounding)301 TEST(FromChars, DoubleRounding) {
302 const double zero = 0.0;
303 const double first_subnormal = nextafter(zero, 1.0);
304 const double second_subnormal = nextafter(first_subnormal, 1.0);
305
306 const double first_normal = DBL_MIN;
307 const double last_subnormal = nextafter(first_normal, 0.0);
308 const double second_normal = nextafter(first_normal, 1.0);
309
310 const double last_normal = DBL_MAX;
311 const double penultimate_normal = nextafter(last_normal, 0.0);
312
313 // Various test cases for numbers between two representable floats. Each
314 // call to TestHalfwayValue tests a number just below and just above the
315 // halfway point, as well as the number exactly between them.
316
317 // Test between zero and first_subnormal. Round-to-even tie rounds down.
318 TestHalfwayValue(
319 "2."
320 "470328229206232720882843964341106861825299013071623822127928412503377536"
321 "351043759326499181808179961898982823477228588654633283551779698981993873"
322 "980053909390631503565951557022639229085839244910518443593180284993653615"
323 "250031937045767824921936562366986365848075700158576926990370631192827955"
324 "855133292783433840935197801553124659726357957462276646527282722005637400"
325 "648549997709659947045402082816622623785739345073633900796776193057750674"
326 "017632467360096895134053553745851666113422376667860416215968046191446729"
327 "184030053005753084904876539171138659164623952491262365388187963623937328"
328 "042389101867234849766823508986338858792562830275599565752445550725518931"
329 "369083625477918694866799496832404970582102851318545139621383772282614543"
330 "7693412532098591327667236328125",
331 -324, zero, first_subnormal, zero);
332
333 // first_subnormal and second_subnormal. Round-to-even tie rounds up.
334 TestHalfwayValue(
335 "7."
336 "410984687618698162648531893023320585475897039214871466383785237510132609"
337 "053131277979497545424539885696948470431685765963899850655339096945981621"
338 "940161728171894510697854671067917687257517734731555330779540854980960845"
339 "750095811137303474765809687100959097544227100475730780971111893578483867"
340 "565399878350301522805593404659373979179073872386829939581848166016912201"
341 "945649993128979841136206248449867871357218035220901702390328579173252022"
342 "052897402080290685402160661237554998340267130003581248647904138574340187"
343 "552090159017259254714629617513415977493871857473787096164563890871811984"
344 "127167305601704549300470526959016576377688490826798697257336652176556794"
345 "107250876433756084600398490497214911746308553955635418864151316847843631"
346 "3080237596295773983001708984375",
347 -324, first_subnormal, second_subnormal, second_subnormal);
348
349 // last_subnormal and first_normal. Round-to-even tie rounds up.
350 TestHalfwayValue(
351 "2."
352 "225073858507201136057409796709131975934819546351645648023426109724822222"
353 "021076945516529523908135087914149158913039621106870086438694594645527657"
354 "207407820621743379988141063267329253552286881372149012981122451451889849"
355 "057222307285255133155755015914397476397983411801999323962548289017107081"
356 "850690630666655994938275772572015763062690663332647565300009245888316433"
357 "037779791869612049497390377829704905051080609940730262937128958950003583"
358 "799967207254304360284078895771796150945516748243471030702609144621572289"
359 "880258182545180325707018860872113128079512233426288368622321503775666622"
360 "503982534335974568884423900265498198385487948292206894721689831099698365"
361 "846814022854243330660339850886445804001034933970427567186443383770486037"
362 "86162277173854562306587467901408672332763671875",
363 -308, last_subnormal, first_normal, first_normal);
364
365 // first_normal and second_normal. Round-to-even tie rounds down.
366 TestHalfwayValue(
367 "2."
368 "225073858507201630123055637955676152503612414573018013083228724049586647"
369 "606759446192036794116886953213985520549032000903434781884412325572184367"
370 "563347617020518175998922941393629966742598285899994830148971433555578567"
371 "693279306015978183162142425067962460785295885199272493577688320732492479"
372 "924816869232247165964934329258783950102250973957579510571600738343645738"
373 "494324192997092179207389919761694314131497173265255020084997973676783743"
374 "155205818804439163810572367791175177756227497413804253387084478193655533"
375 "073867420834526162513029462022730109054820067654020201547112002028139700"
376 "141575259123440177362244273712468151750189745559978653234255886219611516"
377 "335924167958029604477064946470184777360934300451421683607013647479513962"
378 "13837722826145437693412532098591327667236328125",
379 -308, first_normal, second_normal, first_normal);
380
381 // penultimate_normal and last_normal. Round-to-even rounds down.
382 TestHalfwayValue(
383 "1."
384 "797693134862315608353258760581052985162070023416521662616611746258695532"
385 "672923265745300992879465492467506314903358770175220871059269879629062776"
386 "047355692132901909191523941804762171253349609463563872612866401980290377"
387 "995141836029815117562837277714038305214839639239356331336428021390916694"
388 "57927874464075218944",
389 308, penultimate_normal, last_normal, penultimate_normal);
390 }
391
392 // Same test cases as DoubleRounding, now with new and improved Much Smaller
393 // Precision!
TEST(FromChars,FloatRounding)394 TEST(FromChars, FloatRounding) {
395 const float zero = 0.0;
396 const float first_subnormal = nextafterf(zero, 1.0);
397 const float second_subnormal = nextafterf(first_subnormal, 1.0);
398
399 const float first_normal = FLT_MIN;
400 const float last_subnormal = nextafterf(first_normal, 0.0);
401 const float second_normal = nextafterf(first_normal, 1.0);
402
403 const float last_normal = FLT_MAX;
404 const float penultimate_normal = nextafterf(last_normal, 0.0);
405
406 // Test between zero and first_subnormal. Round-to-even tie rounds down.
407 TestHalfwayValue(
408 "7."
409 "006492321624085354618647916449580656401309709382578858785341419448955413"
410 "42930300743319094181060791015625",
411 -46, zero, first_subnormal, zero);
412
413 // first_subnormal and second_subnormal. Round-to-even tie rounds up.
414 TestHalfwayValue(
415 "2."
416 "101947696487225606385594374934874196920392912814773657635602425834686624"
417 "028790902229957282543182373046875",
418 -45, first_subnormal, second_subnormal, second_subnormal);
419
420 // last_subnormal and first_normal. Round-to-even tie rounds up.
421 TestHalfwayValue(
422 "1."
423 "175494280757364291727882991035766513322858992758990427682963118425003064"
424 "9651730385585324256680905818939208984375",
425 -38, last_subnormal, first_normal, first_normal);
426
427 // first_normal and second_normal. Round-to-even tie rounds down.
428 TestHalfwayValue(
429 "1."
430 "175494420887210724209590083408724842314472120785184615334540294131831453"
431 "9442813071445925743319094181060791015625",
432 -38, first_normal, second_normal, first_normal);
433
434 // penultimate_normal and last_normal. Round-to-even rounds down.
435 TestHalfwayValue("3.40282336497324057985868971510891282432", 38,
436 penultimate_normal, last_normal, penultimate_normal);
437 }
438
TEST(FromChars,Underflow)439 TEST(FromChars, Underflow) {
440 // Check that underflow is handled correctly, according to the specification
441 // in DR 3081.
442 double d;
443 float f;
444 absl::from_chars_result result;
445
446 std::string negative_underflow = "-1e-1000";
447 const char* begin = negative_underflow.data();
448 const char* end = begin + negative_underflow.size();
449 d = 100.0;
450 result = absl::from_chars(begin, end, d);
451 EXPECT_EQ(result.ptr, end);
452 EXPECT_EQ(result.ec, std::errc::result_out_of_range);
453 EXPECT_TRUE(std::signbit(d)); // negative
454 EXPECT_GE(d, -std::numeric_limits<double>::min());
455 f = 100.0;
456 result = absl::from_chars(begin, end, f);
457 EXPECT_EQ(result.ptr, end);
458 EXPECT_EQ(result.ec, std::errc::result_out_of_range);
459 EXPECT_TRUE(std::signbit(f)); // negative
460 EXPECT_GE(f, -std::numeric_limits<float>::min());
461
462 std::string positive_underflow = "1e-1000";
463 begin = positive_underflow.data();
464 end = begin + positive_underflow.size();
465 d = -100.0;
466 result = absl::from_chars(begin, end, d);
467 EXPECT_EQ(result.ptr, end);
468 EXPECT_EQ(result.ec, std::errc::result_out_of_range);
469 EXPECT_FALSE(std::signbit(d)); // positive
470 EXPECT_LE(d, std::numeric_limits<double>::min());
471 f = -100.0;
472 result = absl::from_chars(begin, end, f);
473 EXPECT_EQ(result.ptr, end);
474 EXPECT_EQ(result.ec, std::errc::result_out_of_range);
475 EXPECT_FALSE(std::signbit(f)); // positive
476 EXPECT_LE(f, std::numeric_limits<float>::min());
477 }
478
TEST(FromChars,Overflow)479 TEST(FromChars, Overflow) {
480 // Check that overflow is handled correctly, according to the specification
481 // in DR 3081.
482 double d;
483 float f;
484 absl::from_chars_result result;
485
486 std::string negative_overflow = "-1e1000";
487 const char* begin = negative_overflow.data();
488 const char* end = begin + negative_overflow.size();
489 d = 100.0;
490 result = absl::from_chars(begin, end, d);
491 EXPECT_EQ(result.ptr, end);
492 EXPECT_EQ(result.ec, std::errc::result_out_of_range);
493 EXPECT_TRUE(std::signbit(d)); // negative
494 EXPECT_EQ(d, -std::numeric_limits<double>::max());
495 f = 100.0;
496 result = absl::from_chars(begin, end, f);
497 EXPECT_EQ(result.ptr, end);
498 EXPECT_EQ(result.ec, std::errc::result_out_of_range);
499 EXPECT_TRUE(std::signbit(f)); // negative
500 EXPECT_EQ(f, -std::numeric_limits<float>::max());
501
502 std::string positive_overflow = "1e1000";
503 begin = positive_overflow.data();
504 end = begin + positive_overflow.size();
505 d = -100.0;
506 result = absl::from_chars(begin, end, d);
507 EXPECT_EQ(result.ptr, end);
508 EXPECT_EQ(result.ec, std::errc::result_out_of_range);
509 EXPECT_FALSE(std::signbit(d)); // positive
510 EXPECT_EQ(d, std::numeric_limits<double>::max());
511 f = -100.0;
512 result = absl::from_chars(begin, end, f);
513 EXPECT_EQ(result.ptr, end);
514 EXPECT_EQ(result.ec, std::errc::result_out_of_range);
515 EXPECT_FALSE(std::signbit(f)); // positive
516 EXPECT_EQ(f, std::numeric_limits<float>::max());
517 }
518
TEST(FromChars,RegressionTestsFromFuzzer)519 TEST(FromChars, RegressionTestsFromFuzzer) {
520 absl::string_view src = "0x21900000p00000000099";
521 float f;
522 auto result = absl::from_chars(src.data(), src.data() + src.size(), f);
523 EXPECT_EQ(result.ec, std::errc::result_out_of_range);
524 }
525
TEST(FromChars,ReturnValuePtr)526 TEST(FromChars, ReturnValuePtr) {
527 // Check that `ptr` points one past the number scanned, even if that number
528 // is not representable.
529 double d;
530 absl::from_chars_result result;
531
532 std::string normal = "3.14@#$%@#$%";
533 result = absl::from_chars(normal.data(), normal.data() + normal.size(), d);
534 EXPECT_EQ(result.ec, std::errc());
535 EXPECT_EQ(result.ptr - normal.data(), 4);
536
537 std::string overflow = "1e1000@#$%@#$%";
538 result = absl::from_chars(overflow.data(),
539 overflow.data() + overflow.size(), d);
540 EXPECT_EQ(result.ec, std::errc::result_out_of_range);
541 EXPECT_EQ(result.ptr - overflow.data(), 6);
542
543 std::string garbage = "#$%@#$%";
544 result = absl::from_chars(garbage.data(),
545 garbage.data() + garbage.size(), d);
546 EXPECT_EQ(result.ec, std::errc::invalid_argument);
547 EXPECT_EQ(result.ptr - garbage.data(), 0);
548 }
549
550 // Check for a wide range of inputs that strtod() and absl::from_chars() exactly
551 // agree on the conversion amount.
552 //
553 // This test assumes the platform's strtod() uses perfect round_to_nearest
554 // rounding.
TEST(FromChars,TestVersusStrtod)555 TEST(FromChars, TestVersusStrtod) {
556 for (int mantissa = 1000000; mantissa <= 9999999; mantissa += 501) {
557 for (int exponent = -300; exponent < 300; ++exponent) {
558 std::string candidate = absl::StrCat(mantissa, "e", exponent);
559 double strtod_value = strtod(candidate.c_str(), nullptr);
560 double absl_value = 0;
561 absl::from_chars(candidate.data(), candidate.data() + candidate.size(),
562 absl_value);
563 ASSERT_EQ(strtod_value, absl_value) << candidate;
564 }
565 }
566 }
567
568 // Check for a wide range of inputs that strtof() and absl::from_chars() exactly
569 // agree on the conversion amount.
570 //
571 // This test assumes the platform's strtof() uses perfect round_to_nearest
572 // rounding.
TEST(FromChars,TestVersusStrtof)573 TEST(FromChars, TestVersusStrtof) {
574 for (int mantissa = 1000000; mantissa <= 9999999; mantissa += 501) {
575 for (int exponent = -43; exponent < 32; ++exponent) {
576 std::string candidate = absl::StrCat(mantissa, "e", exponent);
577 float strtod_value = strtof(candidate.c_str(), nullptr);
578 float absl_value = 0;
579 absl::from_chars(candidate.data(), candidate.data() + candidate.size(),
580 absl_value);
581 ASSERT_EQ(strtod_value, absl_value) << candidate;
582 }
583 }
584 }
585
586 // Tests if two floating point values have identical bit layouts. (EXPECT_EQ
587 // is not suitable for NaN testing, since NaNs are never equal.)
588 template <typename Float>
Identical(Float a,Float b)589 bool Identical(Float a, Float b) {
590 return 0 == memcmp(&a, &b, sizeof(Float));
591 }
592
593 // Check that NaNs are parsed correctly. The spec requires that
594 // std::from_chars on "NaN(123abc)" return the same value as std::nan("123abc").
595 // How such an n-char-sequence affects the generated NaN is unspecified, so we
596 // just test for symmetry with std::nan and strtod here.
597 //
598 // (In Linux, this parses the value as a number and stuffs that number into the
599 // free bits of a quiet NaN.)
TEST(FromChars,NaNDoubles)600 TEST(FromChars, NaNDoubles) {
601 for (std::string n_char_sequence :
602 {"", "1", "2", "3", "fff", "FFF", "200000", "400000", "4000000000000",
603 "8000000000000", "abc123", "legal_but_unexpected",
604 "99999999999999999999999", "_"}) {
605 std::string input = absl::StrCat("nan(", n_char_sequence, ")");
606 SCOPED_TRACE(input);
607 double from_chars_double;
608 absl::from_chars(input.data(), input.data() + input.size(),
609 from_chars_double);
610 double std_nan_double = std::nan(n_char_sequence.c_str());
611 EXPECT_TRUE(Identical(from_chars_double, std_nan_double));
612
613 // Also check that we match strtod()'s behavior. This test assumes that the
614 // platform has a compliant strtod().
615 #if ABSL_STRTOD_HANDLES_NAN_CORRECTLY
616 double strtod_double = strtod(input.c_str(), nullptr);
617 EXPECT_TRUE(Identical(from_chars_double, strtod_double));
618 #endif // ABSL_STRTOD_HANDLES_NAN_CORRECTLY
619
620 // Check that we can parse a negative NaN
621 std::string negative_input = "-" + input;
622 double negative_from_chars_double;
623 absl::from_chars(negative_input.data(),
624 negative_input.data() + negative_input.size(),
625 negative_from_chars_double);
626 EXPECT_TRUE(std::signbit(negative_from_chars_double));
627 EXPECT_FALSE(Identical(negative_from_chars_double, from_chars_double));
628 from_chars_double = std::copysign(from_chars_double, -1.0);
629 EXPECT_TRUE(Identical(negative_from_chars_double, from_chars_double));
630 }
631 }
632
TEST(FromChars,NaNFloats)633 TEST(FromChars, NaNFloats) {
634 for (std::string n_char_sequence :
635 {"", "1", "2", "3", "fff", "FFF", "200000", "400000", "4000000000000",
636 "8000000000000", "abc123", "legal_but_unexpected",
637 "99999999999999999999999", "_"}) {
638 std::string input = absl::StrCat("nan(", n_char_sequence, ")");
639 SCOPED_TRACE(input);
640 float from_chars_float;
641 absl::from_chars(input.data(), input.data() + input.size(),
642 from_chars_float);
643 float std_nan_float = std::nanf(n_char_sequence.c_str());
644 EXPECT_TRUE(Identical(from_chars_float, std_nan_float));
645
646 // Also check that we match strtof()'s behavior. This test assumes that the
647 // platform has a compliant strtof().
648 #if ABSL_STRTOD_HANDLES_NAN_CORRECTLY
649 float strtof_float = strtof(input.c_str(), nullptr);
650 EXPECT_TRUE(Identical(from_chars_float, strtof_float));
651 #endif // ABSL_STRTOD_HANDLES_NAN_CORRECTLY
652
653 // Check that we can parse a negative NaN
654 std::string negative_input = "-" + input;
655 float negative_from_chars_float;
656 absl::from_chars(negative_input.data(),
657 negative_input.data() + negative_input.size(),
658 negative_from_chars_float);
659 EXPECT_TRUE(std::signbit(negative_from_chars_float));
660 EXPECT_FALSE(Identical(negative_from_chars_float, from_chars_float));
661 // Use the (float, float) overload of std::copysign to prevent narrowing;
662 // see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=98251.
663 from_chars_float = std::copysign(from_chars_float, -1.0f);
664 EXPECT_TRUE(Identical(negative_from_chars_float, from_chars_float));
665 }
666 }
667
668 // Returns an integer larger than step. The values grow exponentially.
NextStep(int step)669 int NextStep(int step) {
670 return step + (step >> 2) + 1;
671 }
672
673 // Test a conversion on a family of input strings, checking that the calculation
674 // is correct for in-bounds values, and that overflow and underflow are done
675 // correctly for out-of-bounds values.
676 //
677 // input_generator maps from an integer index to a string to test.
678 // expected_generator maps from an integer index to an expected Float value.
679 // from_chars conversion of input_generator(i) should result in
680 // expected_generator(i).
681 //
682 // lower_bound and upper_bound denote the smallest and largest values for which
683 // the conversion is expected to succeed.
684 template <typename Float>
TestOverflowAndUnderflow(const std::function<std::string (int)> & input_generator,const std::function<Float (int)> & expected_generator,int lower_bound,int upper_bound)685 void TestOverflowAndUnderflow(
686 const std::function<std::string(int)>& input_generator,
687 const std::function<Float(int)>& expected_generator, int lower_bound,
688 int upper_bound) {
689 // test legal values near lower_bound
690 int index, step;
691 for (index = lower_bound, step = 1; index < upper_bound;
692 index += step, step = NextStep(step)) {
693 std::string input = input_generator(index);
694 SCOPED_TRACE(input);
695 Float expected = expected_generator(index);
696 Float actual;
697 auto result =
698 absl::from_chars(input.data(), input.data() + input.size(), actual);
699 EXPECT_EQ(result.ec, std::errc());
700 EXPECT_EQ(expected, actual)
701 << absl::StrFormat("%a vs %a", expected, actual);
702 }
703 // test legal values near upper_bound
704 for (index = upper_bound, step = 1; index > lower_bound;
705 index -= step, step = NextStep(step)) {
706 std::string input = input_generator(index);
707 SCOPED_TRACE(input);
708 Float expected = expected_generator(index);
709 Float actual;
710 auto result =
711 absl::from_chars(input.data(), input.data() + input.size(), actual);
712 EXPECT_EQ(result.ec, std::errc());
713 EXPECT_EQ(expected, actual)
714 << absl::StrFormat("%a vs %a", expected, actual);
715 }
716 // Test underflow values below lower_bound
717 for (index = lower_bound - 1, step = 1; index > -1000000;
718 index -= step, step = NextStep(step)) {
719 std::string input = input_generator(index);
720 SCOPED_TRACE(input);
721 Float actual;
722 auto result =
723 absl::from_chars(input.data(), input.data() + input.size(), actual);
724 EXPECT_EQ(result.ec, std::errc::result_out_of_range);
725 EXPECT_LT(actual, 1.0); // check for underflow
726 }
727 // Test overflow values above upper_bound
728 for (index = upper_bound + 1, step = 1; index < 1000000;
729 index += step, step = NextStep(step)) {
730 std::string input = input_generator(index);
731 SCOPED_TRACE(input);
732 Float actual;
733 auto result =
734 absl::from_chars(input.data(), input.data() + input.size(), actual);
735 EXPECT_EQ(result.ec, std::errc::result_out_of_range);
736 EXPECT_GT(actual, 1.0); // check for overflow
737 }
738 }
739
740 // Check that overflow and underflow are caught correctly for hex doubles.
741 //
742 // The largest representable double is 0x1.fffffffffffffp+1023, and the
743 // smallest representable subnormal is 0x0.0000000000001p-1022, which equals
744 // 0x1p-1074. Therefore 1023 and -1074 are the limits of acceptable exponents
745 // in this test.
TEST(FromChars,HexdecimalDoubleLimits)746 TEST(FromChars, HexdecimalDoubleLimits) {
747 auto input_gen = [](int index) { return absl::StrCat("0x1.0p", index); };
748 auto expected_gen = [](int index) { return std::ldexp(1.0, index); };
749 TestOverflowAndUnderflow<double>(input_gen, expected_gen, -1074, 1023);
750 }
751
752 // Check that overflow and underflow are caught correctly for hex floats.
753 //
754 // The largest representable float is 0x1.fffffep+127, and the smallest
755 // representable subnormal is 0x0.000002p-126, which equals 0x1p-149.
756 // Therefore 127 and -149 are the limits of acceptable exponents in this test.
TEST(FromChars,HexdecimalFloatLimits)757 TEST(FromChars, HexdecimalFloatLimits) {
758 auto input_gen = [](int index) { return absl::StrCat("0x1.0p", index); };
759 auto expected_gen = [](int index) { return std::ldexp(1.0f, index); };
760 TestOverflowAndUnderflow<float>(input_gen, expected_gen, -149, 127);
761 }
762
763 // Check that overflow and underflow are caught correctly for decimal doubles.
764 //
765 // The largest representable double is about 1.8e308, and the smallest
766 // representable subnormal is about 5e-324. '1e-324' therefore rounds away from
767 // the smallest representable positive value. -323 and 308 are the limits of
768 // acceptable exponents in this test.
TEST(FromChars,DecimalDoubleLimits)769 TEST(FromChars, DecimalDoubleLimits) {
770 auto input_gen = [](int index) { return absl::StrCat("1.0e", index); };
771 auto expected_gen = [](int index) { return Pow10(index); };
772 TestOverflowAndUnderflow<double>(input_gen, expected_gen, -323, 308);
773 }
774
775 // Check that overflow and underflow are caught correctly for decimal floats.
776 //
777 // The largest representable float is about 3.4e38, and the smallest
778 // representable subnormal is about 1.45e-45. '1e-45' therefore rounds towards
779 // the smallest representable positive value. -45 and 38 are the limits of
780 // acceptable exponents in this test.
TEST(FromChars,DecimalFloatLimits)781 TEST(FromChars, DecimalFloatLimits) {
782 auto input_gen = [](int index) { return absl::StrCat("1.0e", index); };
783 auto expected_gen = [](int index) { return Pow10(index); };
784 TestOverflowAndUnderflow<float>(input_gen, expected_gen, -45, 38);
785 }
786
787 } // namespace
788