Skip to content

Commit

Permalink
fixes #23742; setLen(0) no longer allocates memory for uninitialized …
Browse files Browse the repository at this point in the history
…strs/seqs for refc (#23745)

fixes #23742

Before my PR, `setLen(0)` doesn't free buffer if `s != nil`, but it
allocated unnecessary memory for `strs`. This PR rectifies this
behavior. `setLen(0)` no longer allocates memory for uninitialized
strs/seqs

(cherry picked from commit 2bef087)
  • Loading branch information
ringabout authored and narimiran committed Jun 24, 2024
1 parent d0b3b7e commit e77e129
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions lib/system/sysstr.nim
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,10 @@ proc appendChar(dest: NimString, c: char) {.compilerproc, inline.} =
proc setLengthStr(s: NimString, newLen: int): NimString {.compilerRtl.} =
let n = max(newLen, 0)
if s == nil:
result = mnewString(n)
if n == 0:
return s
else:
result = mnewString(n)
elif n <= s.space:
result = s
else:
Expand Down Expand Up @@ -301,7 +304,10 @@ proc setLengthSeqV2(s: PGenericSeq, typ: PNimType, newLen: int): PGenericSeq {.
compilerRtl.} =
sysAssert typ.kind == tySequence, "setLengthSeqV2: type is not a seq"
if s == nil:
result = cast[PGenericSeq](newSeq(typ, newLen))
if newLen == 0:
result = s
else:
result = cast[PGenericSeq](newSeq(typ, newLen))
else:
let elemSize = typ.base.size
let elemAlign = typ.base.align
Expand Down

0 comments on commit e77e129

Please sign in to comment.