Fix #11352 strutil.insertSep() fails on negative numbers (#15087)

* fix #11352 strutil.insertSep handle negtive number

* test for #11352

* optimize

* not parts string var

* Update lib/pure/strutils.nim

Thanks!

Co-authored-by: alaviss <leorize+oss@disroot.org>

* need to be countdown

Co-authored-by: alaviss <leorize+oss@disroot.org>
This commit is contained in:
Bung 2020-07-28 17:47:22 +08:00 • committed by GitHub
commit e2b1491905
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 6 deletions

View file

@ -2264,17 +2264,28 @@ proc insertSep*(s: string, sep = '_', digits = 3): string {.noSideEffect,
## if `s` contains a number. ## if `s` contains a number.
runnableExamples: runnableExamples:
doAssert insertSep("1000000") == "1_000_000" doAssert insertSep("1000000") == "1_000_000"
result = newStringOfCap(s.len)
var L = (s.len-1) div digits + s.len let hasPrefix = isDigit(s[s.low]) == false
result = newString(L) var idx:int
if hasPrefix:
result.add s[s.low]
for i in (s.low + 1)..s.high:
idx = i
if not isDigit(s[i]):
result.add s[i]
else:
break
let partsLen = s.len - idx
var L = (partsLen-1) div digits + partsLen
result.setLen(L + idx)
var j = 0 var j = 0
dec(L) dec(L)
for i in countdown(len(s)-1, 0): for i in countdown(partsLen-1,0):
if j == digits: if j == digits:
result[L] = sep result[L + idx] = sep
dec(L) dec(L)
j = 0 j = 0
result[L] = s[i] result[L + idx] = s[i + idx]
inc(j) inc(j)
dec(L) dec(L)

View file

@ -0,0 +1,13 @@
discard """
output: '''
-100
-100,000
100,000
'''
"""
# test https://github.com/nim-lang/Nim/issues/11352
import strutils
echo insertSep($(-100), ',')
echo insertSep($(-100_000), ',')
echo insertSep($(100_000), ',')