queues.nim 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. ## Implementation of a `queue`:idx:. The underlying implementation uses a ``seq``.
  10. ##
  11. ## None of the procs that get an individual value from the queue can be used
  12. ## on an empty queue.
  13. ## If compiled with `boundChecks` option, those procs will raise an `IndexError`
  14. ## on such access. This should not be relied upon, as `-d:release` will
  15. ## disable those checks and may return garbage or crash the program.
  16. ##
  17. ## As such, a check to see if the queue is empty is needed before any
  18. ## access, unless your program logic guarantees it indirectly.
  19. ##
  20. ## .. code-block:: Nim
  21. ## proc foo(a, b: Positive) = # assume random positive values for `a` and `b`
  22. ## var q = initQueue[int]() # initializes the object
  23. ## for i in 1 ..< a: q.add i # populates the queue
  24. ##
  25. ## if b < q.len: # checking before indexed access
  26. ## echo "The element at index position ", b, " is ", q[b]
  27. ##
  28. ## # The following two lines don't need any checking on access due to the
  29. ## # logic of the program, but that would not be the case if `a` could be 0.
  30. ## assert q.front == 1
  31. ## assert q.back == a
  32. ##
  33. ## while q.len > 0: # checking if the queue is empty
  34. ## echo q.pop()
  35. ##
  36. ## Note: For inter thread communication use
  37. ## a `Channel <channels.html>`_ instead.
  38. import math
  39. {.warning: "`queues` module is deprecated - use `deques` instead".}
  40. type
  41. Queue* {.deprecated.} [T] = object ## A queue.
  42. data: seq[T]
  43. rd, wr, count, mask: int
  44. proc initQueue*[T](initialSize: int = 4): Queue[T] =
  45. ## Create a new queue.
  46. ## Optionally, the initial capacity can be reserved via `initialSize` as a
  47. ## performance optimization. The length of a newly created queue will still
  48. ## be 0.
  49. ##
  50. ## `initialSize` needs to be a power of two. If you need to accept runtime
  51. ## values for this you could use the ``nextPowerOfTwo`` proc from the
  52. ## `math <math.html>`_ module.
  53. assert isPowerOfTwo(initialSize)
  54. result.mask = initialSize-1
  55. newSeq(result.data, initialSize)
  56. proc len*[T](q: Queue[T]): int {.inline.}=
  57. ## Return the number of elements of `q`.
  58. result = q.count
  59. template emptyCheck(q) =
  60. # Bounds check for the regular queue access.
  61. when compileOption("boundChecks"):
  62. if unlikely(q.count < 1):
  63. raise newException(IndexError, "Empty queue.")
  64. template xBoundsCheck(q, i) =
  65. # Bounds check for the array like accesses.
  66. when compileOption("boundChecks"): # d:release should disable this.
  67. if unlikely(i >= q.count): # x < q.low is taken care by the Natural parameter
  68. raise newException(IndexError,
  69. "Out of bounds: " & $i & " > " & $(q.count - 1))
  70. proc front*[T](q: Queue[T]): T {.inline.}=
  71. ## Return the oldest element of `q`. Equivalent to `q.pop()` but does not
  72. ## remove it from the queue.
  73. emptyCheck(q)
  74. result = q.data[q.rd]
  75. proc back*[T](q: Queue[T]): T {.inline.} =
  76. ## Return the newest element of `q` but does not remove it from the queue.
  77. emptyCheck(q)
  78. result = q.data[q.wr - 1 and q.mask]
  79. proc `[]`*[T](q: Queue[T], i: Natural) : T {.inline.} =
  80. ## Access the i-th element of `q` by order of insertion.
  81. ## q[0] is the oldest (the next one q.pop() will extract),
  82. ## q[^1] is the newest (last one added to the queue).
  83. xBoundsCheck(q, i)
  84. return q.data[q.rd + i and q.mask]
  85. proc `[]`*[T](q: var Queue[T], i: Natural): var T {.inline.} =
  86. ## Access the i-th element of `q` and returns a mutable
  87. ## reference to it.
  88. xBoundsCheck(q, i)
  89. return q.data[q.rd + i and q.mask]
  90. proc `[]=`* [T] (q: var Queue[T], i: Natural, val : T) {.inline.} =
  91. ## Change the i-th element of `q`.
  92. xBoundsCheck(q, i)
  93. q.data[q.rd + i and q.mask] = val
  94. iterator items*[T](q: Queue[T]): T =
  95. ## Yield every element of `q`.
  96. var i = q.rd
  97. for c in 0 ..< q.count:
  98. yield q.data[i]
  99. i = (i + 1) and q.mask
  100. iterator mitems*[T](q: var Queue[T]): var T =
  101. ## Yield every element of `q`.
  102. var i = q.rd
  103. for c in 0 ..< q.count:
  104. yield q.data[i]
  105. i = (i + 1) and q.mask
  106. iterator pairs*[T](q: Queue[T]): tuple[key: int, val: T] =
  107. ## Yield every (position, value) of `q`.
  108. var i = q.rd
  109. for c in 0 ..< q.count:
  110. yield (c, q.data[i])
  111. i = (i + 1) and q.mask
  112. proc contains*[T](q: Queue[T], item: T): bool {.inline.} =
  113. ## Return true if `item` is in `q` or false if not found. Usually used
  114. ## via the ``in`` operator. It is the equivalent of ``q.find(item) >= 0``.
  115. ##
  116. ## .. code-block:: Nim
  117. ## if x in q:
  118. ## assert q.contains x
  119. for e in q:
  120. if e == item: return true
  121. return false
  122. proc add*[T](q: var Queue[T], item: T) =
  123. ## Add an `item` to the end of the queue `q`.
  124. var cap = q.mask+1
  125. if unlikely(q.count >= cap):
  126. var n = newSeq[T](cap*2)
  127. for i, x in pairs(q): # don't use copyMem because the GC and because it's slower.
  128. shallowCopy(n[i], x)
  129. shallowCopy(q.data, n)
  130. q.mask = cap*2 - 1
  131. q.wr = q.count
  132. q.rd = 0
  133. inc q.count
  134. q.data[q.wr] = item
  135. q.wr = (q.wr + 1) and q.mask
  136. template default[T](t: typedesc[T]): T =
  137. var v: T
  138. v
  139. proc pop*[T](q: var Queue[T]): T {.inline, discardable.} =
  140. ## Remove and returns the first (oldest) element of the queue `q`.
  141. emptyCheck(q)
  142. dec q.count
  143. result = q.data[q.rd]
  144. q.data[q.rd] = default(type(result))
  145. q.rd = (q.rd + 1) and q.mask
  146. proc enqueue*[T](q: var Queue[T], item: T) =
  147. ## Alias for the ``add`` operation.
  148. q.add(item)
  149. proc dequeue*[T](q: var Queue[T]): T =
  150. ## Alias for the ``pop`` operation.
  151. q.pop()
  152. proc `$`*[T](q: Queue[T]): string =
  153. ## Turn a queue into its string representation.
  154. result = "["
  155. for x in items(q): # Don't remove the items here for reasons that don't fit in this margin.
  156. if result.len > 1: result.add(", ")
  157. result.add($x)
  158. result.add("]")
  159. when isMainModule:
  160. var q = initQueue[int](1)
  161. q.add(123)
  162. q.add(9)
  163. q.enqueue(4)
  164. var first = q.dequeue()
  165. q.add(56)
  166. q.add(6)
  167. var second = q.pop()
  168. q.add(789)
  169. assert first == 123
  170. assert second == 9
  171. assert($q == "[4, 56, 6, 789]")
  172. assert q[0] == q.front and q.front == 4
  173. q[0] = 42
  174. q[q.len - 1] = 7
  175. assert 6 in q and 789 notin q
  176. assert q.find(6) >= 0
  177. assert q.find(789) < 0
  178. for i in -2 .. 10:
  179. if i in q:
  180. assert q.contains(i) and q.find(i) >= 0
  181. else:
  182. assert(not q.contains(i) and q.find(i) < 0)
  183. when compileOption("boundChecks"):
  184. try:
  185. echo q[99]
  186. assert false
  187. except IndexError:
  188. discard
  189. try:
  190. assert q.len == 4
  191. for i in 0 ..< 5: q.pop()
  192. assert false
  193. except IndexError:
  194. discard
  195. # grabs some types of resize error.
  196. q = initQueue[int]()
  197. for i in 1 .. 4: q.add i
  198. q.pop()
  199. q.pop()
  200. for i in 5 .. 8: q.add i
  201. assert $q == "[3, 4, 5, 6, 7, 8]"
  202. # Similar to proc from the documentation example
  203. proc foo(a, b: Positive) = # assume random positive values for `a` and `b`.
  204. var q = initQueue[int]()
  205. assert q.len == 0
  206. for i in 1 .. a: q.add i
  207. if b < q.len: # checking before indexed access.
  208. assert q[b] == b + 1
  209. # The following two lines don't need any checking on access due to the logic
  210. # of the program, but that would not be the case if `a` could be 0.
  211. assert q.front == 1
  212. assert q.back == a
  213. while q.len > 0: # checking if the queue is empty
  214. assert q.pop() > 0
  215. #foo(0,0)
  216. foo(8,5)
  217. foo(10,9)
  218. foo(1,1)
  219. foo(2,1)
  220. foo(1,5)
  221. foo(3,2)