fixes #21538; expand len template parameter once in newSeqWith (#21543)

`len` could contain side effects and may result in different values when
substituted twice in the template expansion. Instead, capture the result
of substituting `len` once.

closes: #21538
This commit is contained in:
Eric N. Vander Weele
2023-03-20 13:51:31 -04:00
committed by GitHub
parent 285ea3c48e
commit da7833c68b
2 changed files with 8 additions and 3 deletions

View File

@@ -1077,9 +1077,9 @@ template newSeqWith*(len: int, init: untyped): untyped =
import std/random
var seqRand = newSeqWith(20, rand(1.0))
assert seqRand[0] != seqRand[1]
var result = newSeq[typeof(init)](len)
for i in 0 ..< len:
let newLen = len
var result = newSeq[typeof(init)](newLen)
for i in 0 ..< newLen:
result[i] = init
move(result) # refs bug #7295

View File

@@ -388,6 +388,11 @@ block: # newSeqWith tests
seq2D[0][1] = true
doAssert seq2D == @[@[true, true], @[true, false], @[false, false], @[false, false]]
block: # bug #21538
var x: seq[int] = @[2, 4]
var y = newSeqWith(x.pop(), true)
doAssert y == @[true, true, true, true]
block: # mapLiterals tests
let x = mapLiterals([0.1, 1.2, 2.3, 3.4], int)
doAssert x is array[4, int]