sysstr.nim 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. result = mnewString(n)
  195. elif n <= s.space:
  196. result = s
  197. else:
  198. let sp = max(resize(s.space), n)
  199. result = rawNewStringNoInit(sp)
  200. result.len = s.len
  201. copyMem(addr result.data[0], unsafeAddr(s.data[0]), s.len)
  202. zeroMem(addr result.data[s.len], n - s.len)
  203. result.reserved = sp
  204. result.len = n
  205. result.data[n] = '\0'
  206. # ----------------- sequences ----------------------------------------------
  207. proc incrSeq(seq: PGenericSeq, elemSize, elemAlign: int): PGenericSeq {.compilerproc.} =
  208. # increments the length by one:
  209. # this is needed for supporting ``add``;
  210. #
  211. # add(seq, x) generates:
  212. # seq = incrSeq(seq, sizeof(x));
  213. # seq[seq->len-1] = x;
  214. result = seq
  215. if result.len >= result.space:
  216. let r = resize(result.space)
  217. result = cast[PGenericSeq](growObj(result, align(GenericSeqSize, elemAlign) + elemSize * r))
  218. result.reserved = r
  219. inc(result.len)
  220. proc incrSeqV2(seq: PGenericSeq, elemSize, elemAlign: int): PGenericSeq {.compilerproc.} =
  221. # incrSeq version 2
  222. result = seq
  223. if result.len >= result.space:
  224. let r = resize(result.space)
  225. result = cast[PGenericSeq](growObj(result, align(GenericSeqSize, elemAlign) + elemSize * r))
  226. result.reserved = r
  227. proc incrSeqV3(s: PGenericSeq, typ: PNimType): PGenericSeq {.compilerproc.} =
  228. if s == nil:
  229. result = cast[PGenericSeq](newSeq(typ, 1))
  230. result.len = 0
  231. else:
  232. result = s
  233. if result.len >= result.space:
  234. let r = resize(result.space)
  235. result = cast[PGenericSeq](newSeq(typ, r))
  236. result.len = s.len
  237. copyMem(dataPointer(result, typ.base.align), dataPointer(s, typ.base.align), s.len * typ.base.size)
  238. # since we steal the content from 's', it's crucial to set s's len to 0.
  239. s.len = 0
  240. proc setLengthSeq(seq: PGenericSeq, elemSize, elemAlign, newLen: int): PGenericSeq {.
  241. compilerRtl, inl.} =
  242. result = seq
  243. if result.space < newLen:
  244. let r = max(resize(result.space), newLen)
  245. result = cast[PGenericSeq](growObj(result, align(GenericSeqSize, elemAlign) + elemSize * r))
  246. result.reserved = r
  247. elif newLen < result.len:
  248. # we need to decref here, otherwise the GC leaks!
  249. when not defined(boehmGC) and not defined(nogc) and
  250. not defined(gcMarkAndSweep) and not defined(gogc) and
  251. not defined(gcRegions):
  252. if ntfNoRefs notin extGetCellType(result).base.flags:
  253. for i in newLen..result.len-1:
  254. forAllChildrenAux(dataPointer(result, elemAlign, elemSize, i),
  255. extGetCellType(result).base, waZctDecRef)
  256. # XXX: zeroing out the memory can still result in crashes if a wiped-out
  257. # cell is aliased by another pointer (ie proc parameter or a let variable).
  258. # This is a tough problem, because even if we don't zeroMem here, in the
  259. # presence of user defined destructors, the user will expect the cell to be
  260. # "destroyed" thus creating the same problem. We can destroy the cell in the
  261. # finalizer of the sequence, but this makes destruction non-deterministic.
  262. zeroMem(dataPointer(result, elemAlign, elemSize, newLen), (result.len-%newLen) *% elemSize)
  263. result.len = newLen
  264. proc setLengthSeqV2(s: PGenericSeq, typ: PNimType, newLen: int): PGenericSeq {.
  265. compilerRtl.} =
  266. sysAssert typ.kind == tySequence, "setLengthSeqV2: type is not a seq"
  267. if s == nil:
  268. result = cast[PGenericSeq](newSeq(typ, newLen))
  269. else:
  270. let elemSize = typ.base.size
  271. let elemAlign = typ.base.align
  272. if s.space < newLen:
  273. let r = max(resize(s.space), newLen)
  274. result = cast[PGenericSeq](newSeq(typ, r))
  275. copyMem(dataPointer(result, elemAlign), dataPointer(s, elemAlign), s.len * elemSize)
  276. # since we steal the content from 's', it's crucial to set s's len to 0.
  277. s.len = 0
  278. elif newLen < s.len:
  279. result = s
  280. # we need to decref here, otherwise the GC leaks!
  281. when not defined(boehmGC) and not defined(nogc) and
  282. not defined(gcMarkAndSweep) and not defined(gogc) and
  283. not defined(gcRegions):
  284. if ntfNoRefs notin typ.base.flags:
  285. for i in newLen..result.len-1:
  286. forAllChildrenAux(dataPointer(result, elemAlign, elemSize, i),
  287. extGetCellType(result).base, waZctDecRef)
  288. # XXX: zeroing out the memory can still result in crashes if a wiped-out
  289. # cell is aliased by another pointer (ie proc parameter or a let variable).
  290. # This is a tough problem, because even if we don't zeroMem here, in the
  291. # presence of user defined destructors, the user will expect the cell to be
  292. # "destroyed" thus creating the same problem. We can destroy the cell in the
  293. # finalizer of the sequence, but this makes destruction non-deterministic.
  294. zeroMem(dataPointer(result, elemAlign, elemSize, newLen), (result.len-%newLen) *% elemSize)
  295. else:
  296. result = s
  297. zeroMem(dataPointer(result, elemAlign, elemSize, result.len), (newLen-%result.len) *% elemSize)
  298. result.len = newLen
  299. func capacity*(self: string): int {.inline.} =
  300. ## Returns the current capacity of the string.
  301. # See https://github.com/nim-lang/RFCs/issues/460
  302. runnableExamples:
  303. var str = newStringOfCap(cap = 42)
  304. str.add "Nim"
  305. assert str.capacity == 42
  306. let str = cast[NimString](self)
  307. result = if str != nil: str.space else: 0
  308. func capacity*[T](self: seq[T]): int {.inline.} =
  309. ## Returns the current capacity of the seq.
  310. # See https://github.com/nim-lang/RFCs/issues/460
  311. runnableExamples:
  312. var lst = newSeqOfCap[string](cap = 42)
  313. lst.add "Nim"
  314. assert lst.capacity == 42
  315. let sek = cast[PGenericSeq](self)
  316. result = if sek != nil: sek.space else: 0