Skip to content

Commit 285cbcb

Browse files
authored
ref #19727; implement setLenUninit for seqsv2 (#22767)
ref #19727
1 parent 4bf0f84 commit 285cbcb

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

changelog.md

+2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
[//]: # "Additions:"
1313

1414
- Added `newStringUninit` to system, which creates a new string of length `len` like `newString` but with uninitialized content.
15+
- Added `setLenUninit` to system, which doesn't initalize
16+
slots when enlarging a sequence.
1517
- Added `hasDefaultValue` to `std/typetraits` to check if a type has a valid default value.
1618
- Added Viewport API for the JavaScript targets in the `dom` module.
1719

lib/system/seqs_v2.nim

+24
Original file line numberDiff line numberDiff line change
@@ -195,5 +195,29 @@ func capacity*[T](self: seq[T]): int {.inline.} =
195195
let sek = cast[ptr NimSeqV2[T]](unsafeAddr self)
196196
result = if sek.p != nil: sek.p.cap and not strlitFlag else: 0
197197

198+
func setLenUninit*[T](s: var seq[T], newlen: Natural) {.nodestroy.} =
199+
## Sets the length of seq `s` to `newlen`. `T` may be any sequence type.
200+
## New slots will not be initialized.
201+
##
202+
## If the current length is greater than the new length,
203+
## `s` will be truncated.
204+
## ```nim
205+
## var x = @[10, 20]
206+
## x.setLenUninit(5)
207+
## x[4] = 50
208+
## assert x[4] == 50
209+
## x.setLenUninit(1)
210+
## assert x == @[10]
211+
## ```
212+
{.noSideEffect.}:
213+
if newlen < s.len:
214+
shrink(s, newlen)
215+
else:
216+
let oldLen = s.len
217+
if newlen <= oldLen: return
218+
var xu = cast[ptr NimSeqV2[T]](addr s)
219+
if xu.p == nil or (xu.p.cap and not strlitFlag) < newlen:
220+
xu.p = cast[typeof(xu.p)](prepareSeqAddUninit(oldLen, xu.p, newlen - oldLen, sizeof(T), alignof(T)))
221+
xu.len = newlen
198222

199223
{.pop.} # See https://github.com./nim-lang/Nim/issues/21401

0 commit comments

Comments
 (0)