@@ -48,18 +48,30 @@ else:
4848 cast [NimString ](newObjNoInit (addr (strDesc), size))
4949
5050proc rawNewStringNoInit (space: int ): NimString =
51+ # # Returns a newly-allocated NimString with `reserved` set.
52+ # # .. warning:: `len` and the terminating null-byte are not set!
5153 let s = max (space, 7 )
5254 result = allocStrNoInit (sizeof (TGenericSeq ) + s + 1 )
5355 result .reserved = s
5456 when defined (gogc):
5557 result .elemSize = 1
5658
5759proc 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
5865 result = rawNewStringNoInit (space)
5966 result .len = 0
6067 result .data[0 ] = '\0 '
6168
6269proc 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
6375 result = rawNewStringNoInit (len)
6476 result .len = len
6577 zeroMem (addr result .data[0 ], len + 1 )
@@ -217,13 +229,16 @@ proc appendChar(dest: NimString, c: char) {.compilerproc, inline.} =
217229
218230proc setLengthStr (s: NimString , newLen: int ): NimString {.compilerRtl .} =
219231 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
224239 else :
225240 let sp = max (resize (s.space), n)
226- result = rawNewStringNoInit (sp)
241+ result = rawNewStringNoInit (sp) # len and null-byte not set
227242 copyMem (addr result .data[0 ], unsafeAddr (s.data[0 ]), s.len)
228243 zeroMem (addr result .data[s.len], n - s.len)
229244 result .len = n
0 commit comments