ropes.nim 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 = -len(data)
  77. result.data = data
  78. var
  79. cache: array[0..2048*2 - 1, Rope] # XXX Global here!
  80. proc resetRopeCache* =
  81. for i in low(cache)..high(cache):
  82. cache[i] = nil
  83. proc ropeInvariant(r: Rope): bool =
  84. if r == nil:
  85. result = true
  86. else:
  87. result = true #
  88. # if r.data <> snil then
  89. # result := true
  90. # else begin
  91. # result := (r.left <> nil) and (r.right <> nil);
  92. # if result then result := ropeInvariant(r.left);
  93. # if result then result := ropeInvariant(r.right);
  94. # end
  95. var gCacheTries* = 0
  96. var gCacheMisses* = 0
  97. var gCacheIntTries* = 0
  98. proc insertInCache(s: string): Rope =
  99. inc gCacheTries
  100. var h = hash(s) and high(cache)
  101. result = cache[h]
  102. if isNil(result) or result.data != s:
  103. inc gCacheMisses
  104. result = newRope(s)
  105. cache[h] = result
  106. proc rope*(s: string): Rope =
  107. ## Converts a string to a rope.
  108. if s.len == 0:
  109. result = nil
  110. else:
  111. result = insertInCache(s)
  112. assert(ropeInvariant(result))
  113. proc rope*(i: BiggestInt): Rope =
  114. ## Converts an int to a rope.
  115. inc gCacheIntTries
  116. result = rope($i)
  117. proc rope*(f: BiggestFloat): Rope =
  118. ## Converts a float to a rope.
  119. result = rope($f)
  120. proc `&`*(a, b: Rope): Rope =
  121. if a == nil:
  122. result = b
  123. elif b == nil:
  124. result = a
  125. else:
  126. result = newRope()
  127. result.L = abs(a.L) + abs(b.L)
  128. result.left = a
  129. result.right = b
  130. proc `&`*(a: Rope, b: string): Rope =
  131. ## the concatenation operator for ropes.
  132. result = a & rope(b)
  133. proc `&`*(a: string, b: Rope): Rope =
  134. ## the concatenation operator for ropes.
  135. result = rope(a) & b
  136. proc `&`*(a: openArray[Rope]): Rope =
  137. ## the concatenation operator for an openarray of ropes.
  138. for i in countup(0, high(a)): result = result & a[i]
  139. proc add*(a: var Rope, b: Rope) =
  140. ## adds `b` to the rope `a`.
  141. a = a & b
  142. proc add*(a: var Rope, b: string) =
  143. ## adds `b` to the rope `a`.
  144. a = a & b
  145. iterator leaves*(r: Rope): string =
  146. ## iterates over any leaf string in the rope `r`.
  147. if r != nil:
  148. var stack = @[r]
  149. while stack.len > 0:
  150. var it = stack.pop
  151. while it.left != nil:
  152. assert it.right != nil
  153. stack.add(it.right)
  154. it = it.left
  155. assert(it != nil)
  156. yield it.data
  157. iterator items*(r: Rope): char =
  158. ## iterates over any character in the rope `r`.
  159. for s in leaves(r):
  160. for c in items(s): yield c
  161. proc writeRope*(f: File, r: Rope) =
  162. ## writes a rope to a file.
  163. for s in leaves(r): write(f, s)
  164. proc writeRope*(head: Rope, filename: AbsoluteFile): bool =
  165. var f: File
  166. if open(f, filename.string, fmWrite):
  167. if head != nil: writeRope(f, head)
  168. close(f)
  169. result = true
  170. else:
  171. result = false
  172. proc `$`*(r: Rope): string =
  173. ## converts a rope back to a string.
  174. result = newString(r.len)
  175. setLen(result, 0)
  176. for s in leaves(r): add(result, s)
  177. proc ropeConcat*(a: varargs[Rope]): Rope =
  178. # not overloaded version of concat to speed-up `rfmt` a little bit
  179. for i in countup(0, high(a)): result = result & a[i]
  180. proc prepend*(a: var Rope, b: Rope) = a = b & a
  181. proc prepend*(a: var Rope, b: string) = a = b & a
  182. proc `%`*(frmt: FormatStr, args: openArray[Rope]): Rope =
  183. var i = 0
  184. var length = len(frmt)
  185. result = nil
  186. var num = 0
  187. while i < length:
  188. if frmt[i] == '$':
  189. inc(i) # skip '$'
  190. case frmt[i]
  191. of '$':
  192. add(result, "$")
  193. inc(i)
  194. of '#':
  195. inc(i)
  196. add(result, args[num])
  197. inc(num)
  198. of '0'..'9':
  199. var j = 0
  200. while true:
  201. j = j * 10 + ord(frmt[i]) - ord('0')
  202. inc(i)
  203. if i >= frmt.len or frmt[i] notin {'0'..'9'}: break
  204. num = j
  205. if j > high(args) + 1:
  206. doAssert false, "invalid format string: " & frmt
  207. else:
  208. add(result, args[j-1])
  209. of '{':
  210. inc(i)
  211. var j = 0
  212. while frmt[i] in {'0'..'9'}:
  213. j = j * 10 + ord(frmt[i]) - ord('0')
  214. inc(i)
  215. num = j
  216. if frmt[i] == '}': inc(i)
  217. else:
  218. doAssert false, "invalid format string: " & frmt
  219. if j > high(args) + 1:
  220. doAssert false, "invalid format string: " & frmt
  221. else:
  222. add(result, args[j-1])
  223. of 'n':
  224. add(result, "\n")
  225. inc(i)
  226. of 'N':
  227. add(result, "\n")
  228. inc(i)
  229. else:
  230. doAssert false, "invalid format string: " & frmt
  231. var start = i
  232. while i < length:
  233. if frmt[i] != '$': inc(i)
  234. else: break
  235. if i - 1 >= start:
  236. add(result, substr(frmt, start, i - 1))
  237. assert(ropeInvariant(result))
  238. proc addf*(c: var Rope, frmt: FormatStr, args: openArray[Rope]) =
  239. ## shortcut for ``add(c, frmt % args)``.
  240. add(c, frmt % args)
  241. when true:
  242. template `~`*(r: string): Rope = r % []
  243. else:
  244. {.push stack_trace: off, line_trace: off.}
  245. proc `~`*(r: static[string]): Rope =
  246. # this is the new optimized "to rope" operator
  247. # the mnemonic is that `~` looks a bit like a rope :)
  248. var r {.global.} = r % []
  249. return r
  250. {.pop.}
  251. const
  252. bufSize = 1024 # 1 KB is reasonable
  253. proc equalsFile*(r: Rope, f: File): bool =
  254. ## returns true if the contents of the file `f` equal `r`.
  255. var
  256. buf: array[bufSize, char]
  257. bpos = buf.len
  258. blen = buf.len
  259. btotal = 0
  260. rtotal = 0
  261. for s in leaves(r):
  262. var spos = 0
  263. let slen = s.len
  264. rtotal += slen
  265. while spos < slen:
  266. if bpos == blen:
  267. # Read more data
  268. bpos = 0
  269. blen = readBuffer(f, addr(buf[0]), buf.len)
  270. btotal += blen
  271. if blen == 0: # no more data in file
  272. result = false
  273. return
  274. let n = min(blen - bpos, slen - spos)
  275. # TODO There's gotta be a better way of comparing here...
  276. if not equalMem(addr(buf[bpos]), cast[pointer](cast[int](cstring(s))+spos), n):
  277. result = false
  278. return
  279. spos += n
  280. bpos += n
  281. result = readBuffer(f, addr(buf[0]), 1) == 0 and
  282. btotal == rtotal # check that we've read all
  283. proc equalsFile*(r: Rope, filename: AbsoluteFile): bool =
  284. ## returns true if the contents of the file `f` equal `r`. If `f` does not
  285. ## exist, false is returned.
  286. var f: File
  287. result = open(f, filename.string)
  288. if result:
  289. result = equalsFile(r, f)
  290. close(f)
  291. proc writeRopeIfNotEqual*(r: Rope, filename: AbsoluteFile): bool =
  292. # returns true if overwritten
  293. if not equalsFile(r, filename):
  294. result = writeRope(r, filename)
  295. else:
  296. result = false