mirror of
https://github.com/nim-lang/Nim.git
synced 2025-12-29 17:34:43 +00:00
* Refactor and optimize cellseqs_v2 in Nim standard library * Extract resizing logic into a separate 'resize' procedure for better readability and separation of concerns * Implement realloc for non-threaded cases to improve memory operations efficiency * Use ',' instead of ';' between parameters in 'add' procedure for consistency with other Nim code * Respond to Araq's feedback: Refactor resize function to use reallocShared This commit replaces the usage of allocShared and deallocShared with reallocShared to optimize memory allocation and deallocation while resizing the CellSeq.
54 lines
1.3 KiB
Nim
54 lines
1.3 KiB
Nim
#
|
|
#
|
|
# Nim's Runtime Library
|
|
# (c) Copyright 2019 Andreas Rumpf
|
|
#
|
|
# See the file "copying.txt", included in this
|
|
# distribution, for details about the copyright.
|
|
#
|
|
|
|
# Cell seqs for cyclebreaker and cyclicrefs_v2.
|
|
|
|
type
|
|
CellTuple[T] = (T, PNimTypeV2)
|
|
CellArray[T] = ptr UncheckedArray[CellTuple[T]]
|
|
CellSeq[T] = object
|
|
len, cap: int
|
|
d: CellArray[T]
|
|
|
|
proc resize[T](s: var CellSeq[T]) =
|
|
s.cap = s.cap * 3 div 2
|
|
var newSize = s.cap * sizeof(CellTuple[T])
|
|
when compileOption("threads"):
|
|
s.d = cast[CellArray[T]](reallocShared(s.d, newSize))
|
|
else:
|
|
s.d = cast[CellArray[T]](realloc(s.d, newSize))
|
|
|
|
proc add[T](s: var CellSeq[T], c: T, t: PNimTypeV2) {.inline.} =
|
|
if s.len >= s.cap:
|
|
s.resize()
|
|
s.d[s.len] = (c, t)
|
|
inc(s.len)
|
|
|
|
proc init[T](s: var CellSeq[T], cap: int = 1024) =
|
|
s.len = 0
|
|
s.cap = cap
|
|
when compileOption("threads"):
|
|
s.d = cast[CellArray[T]](allocShared(uint(s.cap * sizeof(CellTuple[T]))))
|
|
else:
|
|
s.d = cast[CellArray[T]](alloc(s.cap * sizeof(CellTuple[T])))
|
|
|
|
proc deinit[T](s: var CellSeq[T]) =
|
|
if s.d != nil:
|
|
when compileOption("threads"):
|
|
deallocShared(s.d)
|
|
else:
|
|
dealloc(s.d)
|
|
s.d = nil
|
|
s.len = 0
|
|
s.cap = 0
|
|
|
|
proc pop[T](s: var CellSeq[T]): (T, PNimTypeV2) =
|
|
result = s.d[s.len-1]
|
|
dec s.len
|