sysstr.nim 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # string & sequence handling procedures needed by the code generator
  10. # strings are dynamically resized, have a length field
  11. # and are zero-terminated, so they can be casted to C
  12. # strings easily
  13. # we don't use refcounts because that's a behaviour
  14. # the programmer may not want
  15. proc dataPointer(a: PGenericSeq, elemAlign: int): pointer =
  16. cast[pointer](cast[int](a) +% align(GenericSeqSize, elemAlign))
  17. proc dataPointer(a: PGenericSeq, elemAlign, elemSize, index: int): pointer =
  18. cast[pointer](cast[int](a) +% align(GenericSeqSize, elemAlign) +% (index*%elemSize))
  19. proc resize(old: int): int {.inline.} =
  20. if old <= 0: result = 4
  21. elif old < 65536: result = old * 2
  22. else: result = old * 3 div 2 # for large arrays * 3/2 is better
  23. when declared(allocAtomic):
  24. template allocStr(size: untyped): untyped =
  25. cast[NimString](allocAtomic(size))
  26. template allocStrNoInit(size: untyped): untyped =
  27. cast[NimString](boehmAllocAtomic(size))
  28. elif defined(gcRegions):
  29. template allocStr(size: untyped): untyped =
  30. cast[NimString](newStr(addr(strDesc), size, true))
  31. template allocStrNoInit(size: untyped): untyped =
  32. cast[NimString](newStr(addr(strDesc), size, false))
  33. else:
  34. template allocStr(size: untyped): untyped =
  35. cast[NimString](newObj(addr(strDesc), size))
  36. template allocStrNoInit(size: untyped): untyped =
  37. cast[NimString](newObjNoInit(addr(strDesc), size))
  38. proc rawNewStringNoInit(space: int): NimString =
  39. let s = max(space, 7)
  40. result = allocStrNoInit(sizeof(TGenericSeq) + s + 1)
  41. result.reserved = s
  42. when defined(gogc):
  43. result.elemSize = 1
  44. proc rawNewString(space: int): NimString {.compilerproc.} =
  45. result = rawNewStringNoInit(space)
  46. result.len = 0
  47. result.data[0] = '\0'
  48. proc mnewString(len: int): NimString {.compilerproc.} =
  49. result = rawNewStringNoInit(len)
  50. result.len = len
  51. zeroMem(addr result.data[0], len + 1)
  52. proc copyStrLast(s: NimString, start, last: int): NimString {.compilerproc.} =
  53. # This is not used by most recent versions of the compiler anymore, but
  54. # required for bootstrapping purposes.
  55. let start = max(start, 0)
  56. if s == nil: return nil
  57. let len = min(last, s.len-1) - start + 1
  58. result = rawNewStringNoInit(len)
  59. result.len = len
  60. copyMem(addr(result.data), addr(s.data[start]), len)
  61. result.data[len] = '\0'
  62. proc copyStr(s: NimString, start: int): NimString {.compilerproc.} =
  63. # This is not used by most recent versions of the compiler anymore, but
  64. # required for bootstrapping purposes.
  65. if s == nil: return nil
  66. result = copyStrLast(s, start, s.len-1)
  67. proc nimToCStringConv(s: NimString): cstring {.compilerproc, nonReloadable, inline.} =
  68. if s == nil or s.len == 0: result = cstring""
  69. else: result = cast[cstring](addr s.data)
  70. proc toNimStr(str: cstring, len: int): NimString {.compilerproc.} =
  71. result = rawNewStringNoInit(len)
  72. result.len = len
  73. copyMem(addr(result.data), str, len)
  74. result.data[len] = '\0'
  75. proc cstrToNimstr(str: cstring): NimString {.compilerRtl.} =
  76. if str == nil: NimString(nil)
  77. else: toNimStr(str, str.len)
  78. proc copyString(src: NimString): NimString {.compilerRtl.} =
  79. if src != nil:
  80. if (src.reserved and seqShallowFlag) != 0:
  81. result = src
  82. else:
  83. result = rawNewStringNoInit(src.len)
  84. result.len = src.len
  85. copyMem(addr(result.data), addr(src.data), src.len + 1)
  86. sysAssert((seqShallowFlag and result.reserved) == 0, "copyString")
  87. when defined(nimShallowStrings):
  88. if (src.reserved and strlitFlag) != 0:
  89. result.reserved = (result.reserved and not strlitFlag) or seqShallowFlag
  90. proc newOwnedString(src: NimString; n: int): NimString =
  91. result = rawNewStringNoInit(n)
  92. result.len = n
  93. copyMem(addr(result.data), addr(src.data), n)
  94. result.data[n] = '\0'
  95. proc copyStringRC1(src: NimString): NimString {.compilerRtl.} =
  96. if src != nil:
  97. if (src.reserved and seqShallowFlag) != 0:
  98. result = src
  99. when declared(incRef):
  100. incRef(usrToCell(result))
  101. else:
  102. when declared(newObjRC1) and not defined(gcRegions):
  103. var s = src.len
  104. if s < 7: s = 7
  105. result = cast[NimString](newObjRC1(addr(strDesc), sizeof(TGenericSeq) +
  106. s+1))
  107. result.reserved = s
  108. when defined(gogc):
  109. result.elemSize = 1
  110. else:
  111. result = rawNewStringNoInit(src.len)
  112. result.len = src.len
  113. copyMem(addr(result.data), addr(src.data), src.len + 1)
  114. sysAssert((seqShallowFlag and result.reserved) == 0, "copyStringRC1")
  115. when defined(nimShallowStrings):
  116. if (src.reserved and strlitFlag) != 0:
  117. result.reserved = (result.reserved and not strlitFlag) or seqShallowFlag
  118. proc copyDeepString(src: NimString): NimString {.inline.} =
  119. if src != nil:
  120. result = rawNewStringNoInit(src.len)
  121. result.len = src.len
  122. copyMem(addr(result.data), addr(src.data), src.len + 1)
  123. proc addChar(s: NimString, c: char): NimString =
  124. # is compilerproc!
  125. if s == nil:
  126. result = rawNewStringNoInit(1)
  127. result.len = 0
  128. else:
  129. result = s
  130. if result.len >= result.space:
  131. let r = resize(result.space)
  132. result = rawNewStringNoInit(r)
  133. result.len = s.len
  134. copyMem(addr result.data[0], unsafeAddr(s.data[0]), s.len+1)
  135. result.reserved = r
  136. result.data[result.len] = c
  137. result.data[result.len+1] = '\0'
  138. inc(result.len)
  139. # These routines should be used like following:
  140. # <Nim code>
  141. # s &= "Hello " & name & ", how do you feel?"
  142. #
  143. # <generated C code>
  144. # {
  145. # s = resizeString(s, 6 + name->len + 17);
  146. # appendString(s, strLit1);
  147. # appendString(s, strLit2);
  148. # appendString(s, strLit3);
  149. # }
  150. #
  151. # <Nim code>
  152. # s = "Hello " & name & ", how do you feel?"
  153. #
  154. # <generated C code>
  155. # {
  156. # string tmp0;
  157. # tmp0 = rawNewString(6 + name->len + 17);
  158. # appendString(s, strLit1);
  159. # appendString(s, strLit2);
  160. # appendString(s, strLit3);
  161. # s = tmp0;
  162. # }
  163. #
  164. # <Nim code>
  165. # s = ""
  166. #
  167. # <generated C code>
  168. # s = rawNewString(0);
  169. proc resizeString(dest: NimString, addlen: int): NimString {.compilerRtl.} =
  170. if dest == nil:
  171. result = rawNewString(addlen)
  172. elif dest.len + addlen <= dest.space:
  173. result = dest
  174. else: # slow path:
  175. let sp = max(resize(dest.space), dest.len + addlen)
  176. result = rawNewStringNoInit(sp)
  177. result.len = dest.len
  178. copyMem(addr result.data[0], unsafeAddr(dest.data[0]), dest.len+1)
  179. result.reserved = sp
  180. #result = rawNewString(sp)
  181. #copyMem(result, dest, dest.len + sizeof(TGenericSeq))
  182. # DO NOT UPDATE LEN YET: dest.len = newLen
  183. proc appendString(dest, src: NimString) {.compilerproc, inline.} =
  184. if src != nil:
  185. copyMem(addr(dest.data[dest.len]), addr(src.data), src.len + 1)
  186. inc(dest.len, src.len)
  187. proc appendChar(dest: NimString, c: char) {.compilerproc, inline.} =
  188. dest.data[dest.len] = c
  189. dest.data[dest.len+1] = '\0'
  190. inc(dest.len)
  191. proc setLengthStr(s: NimString, newLen: int): NimString {.compilerRtl.} =
  192. let n = max(newLen, 0)
  193. if s == nil:
  194. if n == 0:
  195. return s
  196. else:
  197. result = mnewString(n)
  198. elif n <= s.space:
  199. result = s
  200. else:
  201. let sp = max(resize(s.space), n)
  202. result = rawNewStringNoInit(sp)
  203. result.len = s.len
  204. copyMem(addr result.data[0], unsafeAddr(s.data[0]), s.len)
  205. zeroMem(addr result.data[s.len], n - s.len)
  206. result.reserved = sp
  207. result.len = n
  208. result.data[n] = '\0'
  209. # ----------------- sequences ----------------------------------------------
  210. proc incrSeq(seq: PGenericSeq, elemSize, elemAlign: int): PGenericSeq {.compilerproc.} =
  211. # increments the length by one:
  212. # this is needed for supporting ``add``;
  213. #
  214. # add(seq, x) generates:
  215. # seq = incrSeq(seq, sizeof(x));
  216. # seq[seq->len-1] = x;
  217. result = seq
  218. if result.len >= result.space:
  219. let r = resize(result.space)
  220. result = cast[PGenericSeq](growObj(result, align(GenericSeqSize, elemAlign) + elemSize * r))
  221. result.reserved = r
  222. inc(result.len)
  223. proc incrSeqV2(seq: PGenericSeq, elemSize, elemAlign: int): PGenericSeq {.compilerproc.} =
  224. # incrSeq version 2
  225. result = seq
  226. if result.len >= result.space:
  227. let r = resize(result.space)
  228. result = cast[PGenericSeq](growObj(result, align(GenericSeqSize, elemAlign) + elemSize * r))
  229. result.reserved = r
  230. proc incrSeqV3(s: PGenericSeq, typ: PNimType): PGenericSeq {.compilerproc.} =
  231. if s == nil:
  232. result = cast[PGenericSeq](newSeq(typ, 1))
  233. result.len = 0
  234. else:
  235. result = s
  236. if result.len >= result.space:
  237. let r = resize(result.space)
  238. result = cast[PGenericSeq](newSeq(typ, r))
  239. result.len = s.len
  240. copyMem(dataPointer(result, typ.base.align), dataPointer(s, typ.base.align), s.len * typ.base.size)
  241. # since we steal the content from 's', it's crucial to set s's len to 0.
  242. s.len = 0
  243. proc setLengthSeq(seq: PGenericSeq, elemSize, elemAlign, newLen: int): PGenericSeq {.
  244. compilerRtl, inl.} =
  245. result = seq
  246. if result.space < newLen:
  247. let r = max(resize(result.space), newLen)
  248. result = cast[PGenericSeq](growObj(result, align(GenericSeqSize, elemAlign) + elemSize * r))
  249. result.reserved = r
  250. elif newLen < result.len:
  251. # we need to decref here, otherwise the GC leaks!
  252. when not defined(boehmGC) and not defined(nogc) and
  253. not defined(gcMarkAndSweep) and not defined(gogc) and
  254. not defined(gcRegions):
  255. if ntfNoRefs notin extGetCellType(result).base.flags:
  256. for i in newLen..result.len-1:
  257. forAllChildrenAux(dataPointer(result, elemAlign, elemSize, i),
  258. extGetCellType(result).base, waZctDecRef)
  259. # XXX: zeroing out the memory can still result in crashes if a wiped-out
  260. # cell is aliased by another pointer (ie proc parameter or a let variable).
  261. # This is a tough problem, because even if we don't zeroMem here, in the
  262. # presence of user defined destructors, the user will expect the cell to be
  263. # "destroyed" thus creating the same problem. We can destroy the cell in the
  264. # finalizer of the sequence, but this makes destruction non-deterministic.
  265. zeroMem(dataPointer(result, elemAlign, elemSize, newLen), (result.len-%newLen) *% elemSize)
  266. result.len = newLen
  267. proc setLengthSeqV2(s: PGenericSeq, typ: PNimType, newLen: int): PGenericSeq {.
  268. compilerRtl.} =
  269. sysAssert typ.kind == tySequence, "setLengthSeqV2: type is not a seq"
  270. if s == nil:
  271. if newLen == 0:
  272. result = s
  273. else:
  274. result = cast[PGenericSeq](newSeq(typ, newLen))
  275. else:
  276. let elemSize = typ.base.size
  277. let elemAlign = typ.base.align
  278. if s.space < newLen:
  279. let r = max(resize(s.space), newLen)
  280. result = cast[PGenericSeq](newSeq(typ, r))
  281. copyMem(dataPointer(result, elemAlign), dataPointer(s, elemAlign), s.len * elemSize)
  282. # since we steal the content from 's', it's crucial to set s's len to 0.
  283. s.len = 0
  284. elif newLen < s.len:
  285. result = s
  286. # we need to decref here, otherwise the GC leaks!
  287. when not defined(boehmGC) and not defined(nogc) and
  288. not defined(gcMarkAndSweep) and not defined(gogc) and
  289. not defined(gcRegions):
  290. if ntfNoRefs notin typ.base.flags:
  291. for i in newLen..result.len-1:
  292. forAllChildrenAux(dataPointer(result, elemAlign, elemSize, i),
  293. extGetCellType(result).base, waZctDecRef)
  294. # XXX: zeroing out the memory can still result in crashes if a wiped-out
  295. # cell is aliased by another pointer (ie proc parameter or a let variable).
  296. # This is a tough problem, because even if we don't zeroMem here, in the
  297. # presence of user defined destructors, the user will expect the cell to be
  298. # "destroyed" thus creating the same problem. We can destroy the cell in the
  299. # finalizer of the sequence, but this makes destruction non-deterministic.
  300. zeroMem(dataPointer(result, elemAlign, elemSize, newLen), (result.len-%newLen) *% elemSize)
  301. else:
  302. result = s
  303. zeroMem(dataPointer(result, elemAlign, elemSize, result.len), (newLen-%result.len) *% elemSize)
  304. result.len = newLen
  305. func capacity*(self: string): int {.inline.} =
  306. ## Returns the current capacity of the string.
  307. # See https://github.com/nim-lang/RFCs/issues/460
  308. runnableExamples:
  309. var str = newStringOfCap(cap = 42)
  310. str.add "Nim"
  311. assert str.capacity == 42
  312. let str = cast[NimString](self)
  313. result = if str != nil: str.space else: 0
  314. func capacity*[T](self: seq[T]): int {.inline.} =
  315. ## Returns the current capacity of the seq.
  316. # See https://github.com/nim-lang/RFCs/issues/460
  317. runnableExamples:
  318. var lst = newSeqOfCap[string](cap = 42)
  319. lst.add "Nim"
  320. assert lst.capacity == 42
  321. let sek = cast[PGenericSeq](self)
  322. result = if sek != nil: sek.space else: 0