merge similar procs regarding digits (#18318)

This commit is contained in:
flywind 2021-06-22 23:02:32 +08:00 • committed by GitHub
commit 9a81e91fa5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 105 additions and 133 deletions

View file

@ -1,3 +1,6 @@
import std/private/digitsutils
proc `$`*(x: int): string {.magic: "IntToStr", noSideEffect.}
## The stringify operator for an integer argument. Returns `x`
## converted to a decimal string. `$` is Nim's general way of
@ -6,22 +9,14 @@ proc `$`*(x: int): string {.magic: "IntToStr", noSideEffect.}
template dollarImpl(x: uint | uint64, result: var string) =
type destTyp = typeof(x)
if x == 0:
result = "0"
else:
result = newString(60)
var i = 0
var n = x
while n != 0:
let nn = n div destTyp(10)
result[i] = char(n - destTyp(10) * nn + ord('0'))
inc i
n = nn
result.setLen i
return "0"
elif x == 1:
return "1"
let half = i div 2
# Reverse
for t in 0 .. half-1: swap(result[t], result[i-t-1])
let length = digits10(x)
setLen(result, length)
numToString(result, x, length)
when defined(js):
import std/private/since