@@ -48,18 +48,30 @@ else:
48
48
cast [NimString ](newObjNoInit (addr (strDesc), size))
49
49
50
50
proc rawNewStringNoInit (space: int ): NimString =
51
+ # # Returns a newly-allocated NimString with `reserved` set.
52
+ # # .. warning:: `len` and the terminating null-byte are not set!
51
53
let s = max (space, 7 )
52
54
result = allocStrNoInit (sizeof (TGenericSeq ) + s + 1 )
53
55
result .reserved = s
54
56
when defined (gogc):
55
57
result .elemSize = 1
56
58
57
59
proc rawNewString (space: int ): NimString {.compilerproc .} =
60
+ # # Returns a newly-allocated and *not* zeroed NimString
61
+ # # with everything required set:
62
+ # # - `reserved`
63
+ # # - `len`
64
+ # # - terminating null-byte
58
65
result = rawNewStringNoInit (space)
59
66
result .len = 0
60
67
result .data[0 ] = '\0 '
61
68
62
69
proc mnewString (len: int ): NimString {.compilerproc .} =
70
+ # # Returns a newly-allocated and zeroed NimString
71
+ # # with everything required set:
72
+ # # - `reserved`
73
+ # # - `len`
74
+ # # - terminating null-byte
63
75
result = rawNewStringNoInit (len)
64
76
result .len = len
65
77
zeroMem (addr result .data[0 ], len + 1 )
@@ -217,13 +229,16 @@ proc appendChar(dest: NimString, c: char) {.compilerproc, inline.} =
217
229
218
230
proc setLengthStr (s: NimString , newLen: int ): NimString {.compilerRtl .} =
219
231
let n = max (newLen, 0 )
220
- if s == nil :
221
- return if n == 0 : s else : mnewString (n)
222
- elif n <= s.space:
223
- result = s
232
+ if s == nil : # early return check
233
+ if n == 0 :
234
+ return s
235
+ else :
236
+ return mnewString (n) # sets everything required
237
+ if n <= s.space:
238
+ result = s # len and null-byte need updating
224
239
else :
225
240
let sp = max (resize (s.space), n)
226
- result = rawNewStringNoInit (sp)
241
+ result = rawNewStringNoInit (sp) # len and null-byte not set
227
242
copyMem (addr result .data[0 ], unsafeAddr (s.data[0 ]), s.len)
228
243
zeroMem (addr result .data[s.len], n - s.len)
229
244
result .len = n
0 commit comments