queues.nim 7.4 KB

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