Skip to content

Test Stream::parseFloat() with many input digits #133

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jan 25, 2021
19 changes: 10 additions & 9 deletions api/Stream.cpp
Original file line number Diff line number Diff line change
@@ -162,9 +162,9 @@ float Stream::parseFloat(LookaheadMode lookahead, char ignore)
{
bool isNegative = false;
bool isFraction = false;
long value = 0;
double value = 0.0;
int c;
float fraction = 1.0;
double fraction = 1.0;

c = peekNextDigit(lookahead, true);
// ignore non numeric leading characters
@@ -179,9 +179,12 @@ float Stream::parseFloat(LookaheadMode lookahead, char ignore)
else if (c == '.')
isFraction = true;
else if(c >= '0' && c <= '9') { // is c a digit?
value = value * 10 + c - '0';
if(isFraction)
fraction *= 0.1;
if(isFraction) {
fraction *= 0.1;
value = value + fraction * (c - '0');
} else {
value = value * 10 + c - '0';
}
}
read(); // consume the character we got with peek
c = timedPeek();
@@ -190,10 +193,8 @@ float Stream::parseFloat(LookaheadMode lookahead, char ignore)

if(isNegative)
value = -value;
if(isFraction)
return value * fraction;
else
return value;

return value;
}

// read characters from stream into buffer
12 changes: 12 additions & 0 deletions test/src/Stream/test_parseFloat.cpp
Original file line number Diff line number Diff line change
@@ -10,6 +10,8 @@

#include <StreamMock.h>

#include <float.h>

/**************************************************************************************
* TEST CODE
**************************************************************************************/
@@ -43,6 +45,16 @@ TEST_CASE ("Testing parseFloat(LookaheadMode lookahead = SKIP_ALL, char ignore =
mock << "\r\n\t 12.34";
REQUIRE(mock.parseFloat() == 12.34f);
}
WHEN ("A float is provided with too many digits after the decimal point")
{
mock << "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870064";
REQUIRE(mock.parseFloat() == Approx(3.141592654f));
}
WHEN ("A float is larger than LONG_MAX")
{
mock << "602200000000000000000000.00";
REQUIRE(mock.parseFloat() == Approx(6.022e23f));
}
}

TEST_CASE ("Testing parseFloat(LookaheadMode lookahead = SKIP_NONE, char ignore = NO_IGNORE_CHAR)", "[Stream-parseFloat-02]")