cellseqs_v2.nim 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2019 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # Cell seqs for cyclebreaker and cyclicrefs_v2.
  10. type
  11. CellTuple[T] = (T, PNimTypeV2)
  12. CellArray[T] = ptr UncheckedArray[CellTuple[T]]
  13. CellSeq[T] = object
  14. len, cap: int
  15. d: CellArray[T]
  16. proc resize[T](s: var CellSeq[T]) =
  17. s.cap = s.cap div 2 + s.cap
  18. var newSize = s.cap * sizeof(CellTuple[T])
  19. when compileOption("threads"):
  20. s.d = cast[CellArray[T]](reallocShared(s.d, newSize))
  21. else:
  22. s.d = cast[CellArray[T]](realloc(s.d, newSize))
  23. proc add[T](s: var CellSeq[T], c: T, t: PNimTypeV2) {.inline.} =
  24. if s.len >= s.cap:
  25. s.resize()
  26. s.d[s.len] = (c, t)
  27. inc(s.len)
  28. proc init[T](s: var CellSeq[T], cap: int = 1024) =
  29. s.len = 0
  30. s.cap = cap
  31. when compileOption("threads"):
  32. s.d = cast[CellArray[T]](allocShared(uint(s.cap * sizeof(CellTuple[T]))))
  33. else:
  34. s.d = cast[CellArray[T]](alloc(s.cap * sizeof(CellTuple[T])))
  35. proc deinit[T](s: var CellSeq[T]) =
  36. if s.d != nil:
  37. when compileOption("threads"):
  38. deallocShared(s.d)
  39. else:
  40. dealloc(s.d)
  41. s.d = nil
  42. s.len = 0
  43. s.cap = 0
  44. proc pop[T](s: var CellSeq[T]): (T, PNimTypeV2) =
  45. result = s.d[s.len-1]
  46. dec s.len