Skip to content

Commit

Permalink
fixes #13457 (#13458)
Browse files Browse the repository at this point in the history
  • Loading branch information
Araq authored Feb 21, 2020
1 parent e05aca8 commit 0d219d2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 11 deletions.
21 changes: 11 additions & 10 deletions lib/system/strs_v2.nim
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,13 @@ proc resize(old: int): int {.inline.} =

proc prepareAdd(s: var NimStringV2; addlen: int) {.compilerRtl.} =
if isLiteral(s):
if addlen > 0:
let oldP = s.p
# can't mutate a literal, so we need a fresh copy here:
s.p = cast[ptr NimStrPayload](allocShared0(contentSize(s.len + addlen)))
s.p.cap = s.len + addlen
if s.len > 0:
# we are about to append, so there is no need to copy the \0 terminator:
copyMem(unsafeAddr s.p.data[0], unsafeAddr oldP.data[0], s.len)
let oldP = s.p
# can't mutate a literal, so we need a fresh copy here:
s.p = cast[ptr NimStrPayload](allocShared0(contentSize(s.len + addlen)))
s.p.cap = s.len + addlen
if s.len > 0:
# we are about to append, so there is no need to copy the \0 terminator:
copyMem(unsafeAddr s.p.data[0], unsafeAddr oldP.data[0], s.len)
else:
let oldCap = s.p.cap and not strlitFlag
if s.len + addlen > oldCap:
Expand Down Expand Up @@ -110,8 +109,10 @@ proc setLengthStrV2(s: var NimStringV2, newLen: int) {.compilerRtl.} =
if newLen == 0:
frees(s)
s.p = nil
elif newLen > s.len or isLiteral(s):
prepareAdd(s, newLen - s.len)
else:
if newLen > s.len or isLiteral(s):
prepareAdd(s, newLen - s.len)
s.p.data[newLen] = '\0'
s.len = newLen

proc nimAsgnStrV2(a: var NimStringV2, b: NimStringV2) {.compilerRtl.} =
Expand Down
9 changes: 8 additions & 1 deletion tests/destructor/tnewruntime_misc.nim
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ axc
...
destroying GenericObj[T] GenericObj[system.int]
test
(allocCount: 17, deallocCount: 15)'''
(allocCount: 17, deallocCount: 15)
3'''
"""

import system / ansi_c
Expand Down Expand Up @@ -132,3 +133,9 @@ proc xx(xml: string): MyObject =

discard xx("test")
echo getAllocStats() - s1

# bug #13457
var s = "abcde"
s.setLen(3)

echo s.cstring.len

0 comments on commit 0d219d2

Please sign in to comment.