ropes.nim 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. #
  2. #
  3. # The Nim Compiler
  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. # Ropes for the C code generator
  10. #
  11. # Ropes are a data structure that represents a very long string
  12. # efficiently; especially concatenation is done in O(1) instead of O(N).
  13. # Ropes make use a lazy evaluation: They are essentially concatenation
  14. # trees that are only flattened when converting to a native Nim
  15. # string or when written to disk. The empty string is represented by a
  16. # nil pointer.
  17. # A little picture makes everything clear:
  18. #
  19. # "this string" & " is internally " & "represented as"
  20. #
  21. # con -- inner nodes do not contain raw data
  22. # / \
  23. # / \
  24. # / \
  25. # con "represented as"
  26. # / \
  27. # / \
  28. # / \
  29. # / \
  30. # / \
  31. #"this string" " is internally "
  32. #
  33. # Note that this is the same as:
  34. # "this string" & (" is internally " & "represented as")
  35. #
  36. # con
  37. # / \
  38. # / \
  39. # / \
  40. # "this string" con
  41. # / \
  42. # / \
  43. # / \
  44. # / \
  45. # / \
  46. #" is internally " "represented as"
  47. #
  48. # The 'con' operator is associative! This does not matter however for
  49. # the algorithms we use for ropes.
  50. #
  51. # Note that the left and right pointers are not needed for leaves.
  52. # Leaves have relatively high memory overhead (~30 bytes on a 32
  53. # bit machines) and we produce many of them. This is why we cache and
  54. # share leaves across different rope trees.
  55. # To cache them they are inserted in a `cache` array.
  56. import
  57. hashes
  58. from pathutils import AbsoluteFile
  59. type
  60. FormatStr* = string # later we may change it to CString for better
  61. # performance of the code generator (assignments
  62. # copy the format strings
  63. # though it is not necessary)
  64. Rope* = ref RopeObj
  65. RopeObj*{.acyclic.} = object of RootObj # the empty rope is represented
  66. # by nil to safe space
  67. left, right: Rope
  68. L: int # <= 0 if a leaf
  69. data*: string
  70. proc len*(a: Rope): int =
  71. ## the rope's length
  72. if a == nil: result = 0
  73. else: result = abs a.L
  74. proc newRope(data: string = ""): Rope =
  75. new(result)
  76. result.L = -data.len
  77. result.data = data
  78. when not compileOption("threads"):
  79. var
  80. cache: array[0..2048*2 - 1, Rope]
  81. proc resetRopeCache* =
  82. for i in low(cache)..high(cache):
  83. cache[i] = nil
  84. proc ropeInvariant(r: Rope): bool =
  85. if r == nil:
  86. result = true
  87. else:
  88. result = true #
  89. # if r.data <> snil then
  90. # result := true
  91. # else begin
  92. # result := (r.left <> nil) and (r.right <> nil);
  93. # if result then result := ropeInvariant(r.left);
  94. # if result then result := ropeInvariant(r.right);
  95. # end
  96. var gCacheTries* = 0
  97. var gCacheMisses* = 0
  98. var gCacheIntTries* = 0
  99. proc insertInCache(s: string): Rope =
  100. when declared(cache):
  101. inc gCacheTries
  102. var h = hash(s) and high(cache)
  103. result = cache[h]
  104. if isNil(result) or result.data != s:
  105. inc gCacheMisses
  106. result = newRope(s)
  107. cache[h] = result
  108. else:
  109. result = newRope(s)
  110. proc rope*(s: string): Rope =
  111. ## Converts a string to a rope.
  112. if s.len == 0:
  113. result = nil
  114. else:
  115. result = insertInCache(s)
  116. assert(ropeInvariant(result))
  117. proc rope*(i: BiggestInt): Rope =
  118. ## Converts an int to a rope.
  119. inc gCacheIntTries
  120. result = rope($i)
  121. proc rope*(f: BiggestFloat): Rope =
  122. ## Converts a float to a rope.
  123. result = rope($f)
  124. proc `&`*(a, b: Rope): Rope =
  125. if a == nil:
  126. result = b
  127. elif b == nil:
  128. result = a
  129. else:
  130. result = newRope()
  131. result.L = abs(a.L) + abs(b.L)
  132. result.left = a
  133. result.right = b
  134. proc `&`*(a: Rope, b: string): Rope =
  135. ## the concatenation operator for ropes.
  136. result = a & rope(b)
  137. proc `&`*(a: string, b: Rope): Rope =
  138. ## the concatenation operator for ropes.
  139. result = rope(a) & b
  140. proc `&`*(a: openArray[Rope]): Rope =
  141. ## the concatenation operator for an openarray of ropes.
  142. for i in 0..high(a): result = result & a[i]
  143. proc add*(a: var Rope, b: Rope) =
  144. ## adds `b` to the rope `a`.
  145. a = a & b
  146. proc add*(a: var Rope, b: string) =
  147. ## adds `b` to the rope `a`.
  148. a = a & b
  149. iterator leaves*(r: Rope): string =
  150. ## iterates over any leaf string in the rope `r`.
  151. if r != nil:
  152. var stack = @[r]
  153. while stack.len > 0:
  154. var it = stack.pop
  155. while it.left != nil:
  156. assert it.right != nil
  157. stack.add(it.right)
  158. it = it.left
  159. assert(it != nil)
  160. yield it.data
  161. iterator items*(r: Rope): char =
  162. ## iterates over any character in the rope `r`.
  163. for s in leaves(r):
  164. for c in items(s): yield c
  165. proc writeRope*(f: File, r: Rope) =
  166. ## writes a rope to a file.
  167. for s in leaves(r): write(f, s)
  168. proc writeRope*(head: Rope, filename: AbsoluteFile): bool =
  169. var f: File
  170. if open(f, filename.string, fmWrite):
  171. if head != nil: writeRope(f, head)
  172. close(f)
  173. result = true
  174. else:
  175. result = false
  176. proc `$`*(r: Rope): string =
  177. ## converts a rope back to a string.
  178. result = newString(r.len)
  179. setLen(result, 0)
  180. for s in leaves(r): result.add(s)
  181. proc ropeConcat*(a: varargs[Rope]): Rope =
  182. # not overloaded version of concat to speed-up `rfmt` a little bit
  183. for i in 0..high(a): result = result & a[i]
  184. proc prepend*(a: var Rope, b: Rope) = a = b & a
  185. proc prepend*(a: var Rope, b: string) = a = b & a
  186. proc runtimeFormat*(frmt: FormatStr, args: openArray[Rope]): Rope =
  187. var i = 0
  188. result = nil
  189. var num = 0
  190. while i < frmt.len:
  191. if frmt[i] == '$':
  192. inc(i) # skip '$'
  193. case frmt[i]
  194. of '$':
  195. result.add("$")
  196. inc(i)
  197. of '#':
  198. inc(i)
  199. result.add(args[num])
  200. inc(num)
  201. of '0'..'9':
  202. var j = 0
  203. while true:
  204. j = j * 10 + ord(frmt[i]) - ord('0')
  205. inc(i)
  206. if i >= frmt.len or frmt[i] notin {'0'..'9'}: break
  207. num = j
  208. if j > high(args) + 1:
  209. doAssert false, "invalid format string: " & frmt
  210. else:
  211. result.add(args[j-1])
  212. of '{':
  213. inc(i)
  214. var j = 0
  215. while frmt[i] in {'0'..'9'}:
  216. j = j * 10 + ord(frmt[i]) - ord('0')
  217. inc(i)
  218. num = j
  219. if frmt[i] == '}': inc(i)
  220. else:
  221. doAssert false, "invalid format string: " & frmt
  222. if j > high(args) + 1:
  223. doAssert false, "invalid format string: " & frmt
  224. else:
  225. result.add(args[j-1])
  226. of 'n':
  227. result.add("\n")
  228. inc(i)
  229. of 'N':
  230. result.add("\n")
  231. inc(i)
  232. else:
  233. doAssert false, "invalid format string: " & frmt
  234. var start = i
  235. while i < frmt.len:
  236. if frmt[i] != '$': inc(i)
  237. else: break
  238. if i - 1 >= start:
  239. result.add(substr(frmt, start, i - 1))
  240. assert(ropeInvariant(result))
  241. proc `%`*(frmt: static[FormatStr], args: openArray[Rope]): Rope =
  242. runtimeFormat(frmt, args)
  243. template addf*(c: var Rope, frmt: FormatStr, args: openArray[Rope]) =
  244. ## shortcut for ``add(c, frmt % args)``.
  245. c.add(frmt % args)
  246. when true:
  247. template `~`*(r: string): Rope = r % []
  248. else:
  249. {.push stack_trace: off, line_trace: off.}
  250. proc `~`*(r: static[string]): Rope =
  251. # this is the new optimized "to rope" operator
  252. # the mnemonic is that `~` looks a bit like a rope :)
  253. var r {.global.} = r % []
  254. return r
  255. {.pop.}
  256. const
  257. bufSize = 1024 # 1 KB is reasonable
  258. proc equalsFile*(r: Rope, f: File): bool =
  259. ## returns true if the contents of the file `f` equal `r`.
  260. var
  261. buf: array[bufSize, char]
  262. bpos = buf.len
  263. blen = buf.len
  264. btotal = 0
  265. rtotal = 0
  266. for s in leaves(r):
  267. var spos = 0
  268. rtotal += s.len
  269. while spos < s.len:
  270. if bpos == blen:
  271. # Read more data
  272. bpos = 0
  273. blen = readBuffer(f, addr(buf[0]), buf.len)
  274. btotal += blen
  275. if blen == 0: # no more data in file
  276. result = false
  277. return
  278. let n = min(blen - bpos, s.len - spos)
  279. # TODO There's gotta be a better way of comparing here...
  280. if not equalMem(addr(buf[bpos]), cast[pointer](cast[int](cstring(s))+spos), n):
  281. result = false
  282. return
  283. spos += n
  284. bpos += n
  285. result = readBuffer(f, addr(buf[0]), 1) == 0 and
  286. btotal == rtotal # check that we've read all
  287. proc equalsFile*(r: Rope, filename: AbsoluteFile): bool =
  288. ## returns true if the contents of the file `f` equal `r`. If `f` does not
  289. ## exist, false is returned.
  290. var f: File
  291. result = open(f, filename.string)
  292. if result:
  293. result = equalsFile(r, f)
  294. close(f)
  295. proc writeRopeIfNotEqual*(r: Rope, filename: AbsoluteFile): bool =
  296. # returns true if overwritten
  297. if not equalsFile(r, filename):
  298. result = writeRope(r, filename)
  299. else:
  300. result = false