From 22e71cbc0f8e055ae497286e1550a76f7e9dabac Mon Sep 17 00:00:00 2001 From: flywind Date: Mon, 16 Aug 2021 21:14:35 +0800 Subject: [PATCH] fix #18702(fix `parseutils.parseFloat`) (#18703) [backport:1.0] * fix #18702 * Apply suggestions from code review (cherry picked from commit 901c5ded527bb06c52bfc1fd38c9a5fadee0f49a) --- lib/system/strmantle.nim | 9 ++++---- tests/stdlib/tparseutils.nim | 43 ++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 4 deletions(-) create mode 100644 tests/stdlib/tparseutils.nim diff --git a/lib/system/strmantle.nim b/lib/system/strmantle.nim index 69e0d80529fc..23446c0ee2c1 100644 --- a/lib/system/strmantle.nim +++ b/lib/system/strmantle.nim @@ -245,15 +245,16 @@ proc nimParseBiggestFloat(s: string, number: var BiggestFloat, var ti = 0 let maxlen = t.high - "e+000".len # reserve enough space for exponent - result = i - start + let endPos = i + result = endPos - start i = start # re-parse without error checking, any error should be handled by the code above. - if i < s.len and s[i] == '.': i.inc - while i < s.len and s[i] in {'0'..'9','+','-'}: + if i < endPos and s[i] == '.': i.inc + while i < endPos and s[i] in {'0'..'9','+','-'}: if ti < maxlen: t[ti] = s[i]; inc(ti) inc(i) - while i < s.len and s[i] in {'.', '_'}: # skip underscore and decimal point + while i < endPos and s[i] in {'.', '_'}: # skip underscore and decimal point inc(i) # insert exponent diff --git a/tests/stdlib/tparseutils.nim b/tests/stdlib/tparseutils.nim new file mode 100644 index 000000000000..baad3677e247 --- /dev/null +++ b/tests/stdlib/tparseutils.nim @@ -0,0 +1,43 @@ +import parseutils, sequtils, sugar + + +let input = "$test{} $this is ${an{ example}} " +let expected = @[(ikVar, "test"), (ikStr, "{} "), (ikVar, "this"), + (ikStr, " is "), (ikExpr, "an{ example}"), (ikStr, " ")] +doAssert toSeq(interpolatedFragments(input)) == expected + +var value = 0 +discard parseHex("0x38", value) +doAssert value == 56 + +value = -1 +doAssert(parseSaturatedNatural("848", value) == 3) +doAssert value == 848 + +value = -1 +discard parseSaturatedNatural("84899999999999999999324234243143142342135435342532453", value) +doAssert value == high(int) + +value = -1 +discard parseSaturatedNatural("9223372036854775808", value) +doAssert value == high(int) + +value = -1 +discard parseSaturatedNatural("9223372036854775807", value) +doAssert value == high(int) + +value = -1 +discard parseSaturatedNatural("18446744073709551616", value) +doAssert value == high(int) + +value = -1 +discard parseSaturatedNatural("18446744073709551615", value) +doAssert value == high(int) + +value = -1 +doAssert(parseSaturatedNatural("1_000_000", value) == 9) +doAssert value == 1_000_000 + +var i64Value: int64 +discard parseBiggestInt("9223372036854775807", i64Value) +doAssert i64Value == 9223372036854775807