@@ -29,18 +29,34 @@ const
29
29
# doAssert res == digits100
30
30
31
31
proc utoa2Digits* (buf: var openArray [char ]; pos: int ; digits: uint32 ) {.inline.} =
32
- assert(digits <= 99 )
33
32
buf[pos] = digits100[2 * digits]
34
33
buf[pos+ 1 ] = digits100[2 * digits + 1 ]
35
34
# copyMem(buf, unsafeAddr(digits100[2 * digits]), 2 * sizeof((char)))
36
35
37
36
proc trailingZeros2Digits* (digits: uint32 ): int32 {.inline.} =
38
- assert(digits <= 99 )
39
37
return trailingZeros100[digits]
40
38
41
- func addIntImpl* (result : var string , origin: uint64 ) =
39
+ when defined(js):
40
+ proc numToString(a: SomeInteger): cstring {.importjs: " ((#) + \"\" )" .}
41
+
42
+ func addChars[T](result : var string , x: T, start: int , n: int ) {.inline.} =
43
+ let old = result .len
44
+ result .setLen old + n
45
+ template impl =
46
+ for i in 0..<n: result [old + i] = x[start + i]
47
+ when nimvm : impl
48
+ else:
49
+ when defined(js) or defined(nimscript): impl
50
+ else:
51
+ {.noSideEffect.}:
52
+ copyMem result [old].addr, x[start].unsafeAddr, n
53
+
54
+ func addChars[T](result : var string , x: T) {.inline.} =
55
+ addChars(result , x, 0, x.len)
56
+
57
+ func addIntImpl(result : var string , x: uint64 ) {.inline.} =
42
58
var tmp {.noinit.}: array [24, char ]
43
- var num = origin
59
+ var num = x
44
60
var next = tmp.len - 1
45
61
const nbatch = 100
46
62
@@ -60,17 +76,39 @@ func addIntImpl*(result: var string, origin: uint64) =
60
76
tmp[next] = digits100[index + 1 ]
61
77
tmp[next - 1 ] = digits100[index]
62
78
dec next
63
- let n = result .len
64
- let length = tmp.len - next
65
- result .setLen n + length
66
- when nimvm :
67
- for i in 0 ..< length:
68
- result [n+ i] = tmp[next+ i]
79
+ addChars(result , tmp, next, tmp.len - next)
80
+
81
+ func addInt* (result : var string , x: uint64 ) =
82
+ when nimvm : addIntImpl(result , x)
69
83
else :
70
- when defined(js) or defined(nimscript):
71
- for i in 0 ..< length:
72
- result [n+ i] = tmp[next+ i]
84
+ when not defined(js): addIntImpl(result , x)
73
85
else :
74
- {.noSideEffect.}:
75
- copyMem result [n].addr , tmp[next].addr , length
86
+ addChars(result , numToString(x))
87
+
88
+ proc addInt* (result : var string ; x: int64 ) =
89
+ # # Converts integer to its string representation and appends it to `result`.
90
+ runnableExamples:
91
+ var s = " foo"
92
+ s.addInt(45 )
93
+ assert s == " foo45"
94
+ template impl =
95
+ var num: uint64
96
+ if x < 0 :
97
+ if x == low(int64 ):
98
+ num = uint64 (x)
99
+ else :
100
+ num = uint64 (- x)
101
+ let base = result .len
102
+ setLen(result , base + 1 )
103
+ result [base] = '-'
104
+ else :
105
+ num = uint64 (x)
106
+ addInt(result , num)
107
+ when nimvm : impl()
108
+ else :
109
+ when defined(js):
110
+ addChars(result , numToString(x))
111
+ else : impl()
76
112
113
+ proc addInt* (result : var string ; x: int ) {.inline.} =
114
+ addInt(result , int64 (x))
0 commit comments