deques.nim 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. ## An implementation of a `deque`:idx: (double-ended queue).
  10. ## The underlying implementation uses a `seq`.
  11. ##
  12. ## .. note:: None of the procs that get an individual value from the deque should be used
  13. ## on an empty deque.
  14. ##
  15. ## If compiled with the `boundChecks` option, those procs will raise an `IndexDefect`
  16. ## on such access. This should not be relied upon, as `-d:danger` or `--checks:off` will
  17. ## disable those checks and then the procs may return garbage or crash the program.
  18. ##
  19. ## As such, a check to see if the deque is empty is needed before any
  20. ## access, unless your program logic guarantees it indirectly.
  21. runnableExamples:
  22. var a = [10, 20, 30, 40].toDeque
  23. doAssertRaises(IndexDefect, echo a[4])
  24. a.addLast(50)
  25. assert $a == "[10, 20, 30, 40, 50]"
  26. assert a.peekFirst == 10
  27. assert a.peekLast == 50
  28. assert len(a) == 5
  29. assert a.popFirst == 10
  30. assert a.popLast == 50
  31. assert len(a) == 3
  32. a.addFirst(11)
  33. a.addFirst(22)
  34. a.addFirst(33)
  35. assert $a == "[33, 22, 11, 20, 30, 40]"
  36. a.shrink(fromFirst = 1, fromLast = 2)
  37. assert $a == "[22, 11, 20]"
  38. ## See also
  39. ## ========
  40. ## * `lists module <lists.html>`_ for singly and doubly linked lists and rings
  41. ## * `channels module <channels_builtin.html>`_ for inter-thread communication
  42. import std/private/since
  43. import math
  44. type
  45. Deque*[T] = object
  46. ## A double-ended queue backed with a ringed `seq` buffer.
  47. ##
  48. ## To initialize an empty deque,
  49. ## use the `initDeque proc <#initDeque,int>`_.
  50. data: seq[T]
  51. head, tail, count, mask: int
  52. const
  53. defaultInitialSize* = 4
  54. template initImpl(result: typed, initialSize: int) =
  55. let correctSize = nextPowerOfTwo(initialSize)
  56. result.mask = correctSize - 1
  57. newSeq(result.data, correctSize)
  58. template checkIfInitialized(deq: typed) =
  59. when compiles(defaultInitialSize):
  60. if deq.mask == 0:
  61. initImpl(deq, defaultInitialSize)
  62. proc initDeque*[T](initialSize: int = defaultInitialSize): Deque[T] =
  63. ## Creates a new empty deque.
  64. ##
  65. ## Optionally, the initial capacity can be reserved via `initialSize`
  66. ## as a performance optimization
  67. ## (default: `defaultInitialSize <#defaultInitialSize>`_).
  68. ## The length of a newly created deque will still be 0.
  69. ##
  70. ## **See also:**
  71. ## * `toDeque proc <#toDeque,openArray[T]>`_
  72. result.initImpl(initialSize)
  73. proc toDeque*[T](x: openArray[T]): Deque[T] {.since: (1, 3).} =
  74. ## Creates a new deque that contains the elements of `x` (in the same order).
  75. ##
  76. ## **See also:**
  77. ## * `initDeque proc <#initDeque,int>`_
  78. runnableExamples:
  79. let a = toDeque([7, 8, 9])
  80. assert len(a) == 3
  81. assert $a == "[7, 8, 9]"
  82. result.initImpl(x.len)
  83. for item in items(x):
  84. result.addLast(item)
  85. proc len*[T](deq: Deque[T]): int {.inline.} =
  86. ## Returns the number of elements of `deq`.
  87. result = deq.count
  88. template emptyCheck(deq) =
  89. # Bounds check for the regular deque access.
  90. when compileOption("boundChecks"):
  91. if unlikely(deq.count < 1):
  92. raise newException(IndexDefect, "Empty deque.")
  93. template xBoundsCheck(deq, i) =
  94. # Bounds check for the array like accesses.
  95. when compileOption("boundChecks"): # `-d:danger` or `--checks:off` should disable this.
  96. if unlikely(i >= deq.count): # x < deq.low is taken care by the Natural parameter
  97. raise newException(IndexDefect,
  98. "Out of bounds: " & $i & " > " & $(deq.count - 1))
  99. if unlikely(i < 0): # when used with BackwardsIndex
  100. raise newException(IndexDefect,
  101. "Out of bounds: " & $i & " < 0")
  102. proc `[]`*[T](deq: Deque[T], i: Natural): lent T {.inline.} =
  103. ## Accesses the `i`-th element of `deq`.
  104. runnableExamples:
  105. let a = [10, 20, 30, 40, 50].toDeque
  106. assert a[0] == 10
  107. assert a[3] == 40
  108. doAssertRaises(IndexDefect, echo a[8])
  109. xBoundsCheck(deq, i)
  110. return deq.data[(deq.head + i) and deq.mask]
  111. proc `[]`*[T](deq: var Deque[T], i: Natural): var T {.inline.} =
  112. ## Accesses the `i`-th element of `deq` and returns a mutable
  113. ## reference to it.
  114. runnableExamples:
  115. var a = [10, 20, 30, 40, 50].toDeque
  116. inc(a[0])
  117. assert a[0] == 11
  118. xBoundsCheck(deq, i)
  119. return deq.data[(deq.head + i) and deq.mask]
  120. proc `[]=`*[T](deq: var Deque[T], i: Natural, val: sink T) {.inline.} =
  121. ## Sets the `i`-th element of `deq` to `val`.
  122. runnableExamples:
  123. var a = [10, 20, 30, 40, 50].toDeque
  124. a[0] = 99
  125. a[3] = 66
  126. assert $a == "[99, 20, 30, 66, 50]"
  127. checkIfInitialized(deq)
  128. xBoundsCheck(deq, i)
  129. deq.data[(deq.head + i) and deq.mask] = val
  130. proc `[]`*[T](deq: Deque[T], i: BackwardsIndex): lent T {.inline.} =
  131. ## Accesses the backwards indexed `i`-th element.
  132. ##
  133. ## `deq[^1]` is the last element.
  134. runnableExamples:
  135. let a = [10, 20, 30, 40, 50].toDeque
  136. assert a[^1] == 50
  137. assert a[^4] == 20
  138. doAssertRaises(IndexDefect, echo a[^9])
  139. xBoundsCheck(deq, deq.len - int(i))
  140. return deq[deq.len - int(i)]
  141. proc `[]`*[T](deq: var Deque[T], i: BackwardsIndex): var T {.inline.} =
  142. ## Accesses the backwards indexed `i`-th element and returns a mutable
  143. ## reference to it.
  144. ##
  145. ## `deq[^1]` is the last element.
  146. runnableExamples:
  147. var a = [10, 20, 30, 40, 50].toDeque
  148. inc(a[^1])
  149. assert a[^1] == 51
  150. xBoundsCheck(deq, deq.len - int(i))
  151. return deq[deq.len - int(i)]
  152. proc `[]=`*[T](deq: var Deque[T], i: BackwardsIndex, x: sink T) {.inline.} =
  153. ## Sets the backwards indexed `i`-th element of `deq` to `x`.
  154. ##
  155. ## `deq[^1]` is the last element.
  156. runnableExamples:
  157. var a = [10, 20, 30, 40, 50].toDeque
  158. a[^1] = 99
  159. a[^3] = 77
  160. assert $a == "[10, 20, 77, 40, 99]"
  161. checkIfInitialized(deq)
  162. xBoundsCheck(deq, deq.len - int(i))
  163. deq[deq.len - int(i)] = x
  164. iterator items*[T](deq: Deque[T]): lent T =
  165. ## Yields every element of `deq`.
  166. ##
  167. ## **See also:**
  168. ## * `mitems iterator <#mitems.i,Deque[T]>`_
  169. runnableExamples:
  170. from std/sequtils import toSeq
  171. let a = [10, 20, 30, 40, 50].toDeque
  172. assert toSeq(a.items) == @[10, 20, 30, 40, 50]
  173. var i = deq.head
  174. for c in 0 ..< deq.count:
  175. yield deq.data[i]
  176. i = (i + 1) and deq.mask
  177. iterator mitems*[T](deq: var Deque[T]): var T =
  178. ## Yields every element of `deq`, which can be modified.
  179. ##
  180. ## **See also:**
  181. ## * `items iterator <#items.i,Deque[T]>`_
  182. runnableExamples:
  183. var a = [10, 20, 30, 40, 50].toDeque
  184. assert $a == "[10, 20, 30, 40, 50]"
  185. for x in mitems(a):
  186. x = 5 * x - 1
  187. assert $a == "[49, 99, 149, 199, 249]"
  188. var i = deq.head
  189. for c in 0 ..< deq.count:
  190. yield deq.data[i]
  191. i = (i + 1) and deq.mask
  192. iterator pairs*[T](deq: Deque[T]): tuple[key: int, val: T] =
  193. ## Yields every `(position, value)`-pair of `deq`.
  194. runnableExamples:
  195. from std/sequtils import toSeq
  196. let a = [10, 20, 30].toDeque
  197. assert toSeq(a.pairs) == @[(0, 10), (1, 20), (2, 30)]
  198. var i = deq.head
  199. for c in 0 ..< deq.count:
  200. yield (c, deq.data[i])
  201. i = (i + 1) and deq.mask
  202. proc contains*[T](deq: Deque[T], item: T): bool {.inline.} =
  203. ## Returns true if `item` is in `deq` or false if not found.
  204. ##
  205. ## Usually used via the `in` operator.
  206. ## It is the equivalent of `deq.find(item) >= 0`.
  207. runnableExamples:
  208. let q = [7, 9].toDeque
  209. assert 7 in q
  210. assert q.contains(7)
  211. assert 8 notin q
  212. for e in deq:
  213. if e == item: return true
  214. return false
  215. proc expandIfNeeded[T](deq: var Deque[T]) =
  216. checkIfInitialized(deq)
  217. var cap = deq.mask + 1
  218. if unlikely(deq.count >= cap):
  219. var n = newSeq[T](cap * 2)
  220. var i = 0
  221. for x in mitems(deq):
  222. when nimvm: n[i] = x # workaround for VM bug
  223. else: n[i] = move(x)
  224. inc i
  225. deq.data = move(n)
  226. deq.mask = cap * 2 - 1
  227. deq.tail = deq.count
  228. deq.head = 0
  229. proc addFirst*[T](deq: var Deque[T], item: sink T) =
  230. ## Adds an `item` to the beginning of `deq`.
  231. ##
  232. ## **See also:**
  233. ## * `addLast proc <#addLast,Deque[T],sinkT>`_
  234. runnableExamples:
  235. var a = initDeque[int]()
  236. for i in 1 .. 5:
  237. a.addFirst(10 * i)
  238. assert $a == "[50, 40, 30, 20, 10]"
  239. expandIfNeeded(deq)
  240. inc deq.count
  241. deq.head = (deq.head - 1) and deq.mask
  242. deq.data[deq.head] = item
  243. proc addLast*[T](deq: var Deque[T], item: sink T) =
  244. ## Adds an `item` to the end of `deq`.
  245. ##
  246. ## **See also:**
  247. ## * `addFirst proc <#addFirst,Deque[T],sinkT>`_
  248. runnableExamples:
  249. var a = initDeque[int]()
  250. for i in 1 .. 5:
  251. a.addLast(10 * i)
  252. assert $a == "[10, 20, 30, 40, 50]"
  253. expandIfNeeded(deq)
  254. inc deq.count
  255. deq.data[deq.tail] = item
  256. deq.tail = (deq.tail + 1) and deq.mask
  257. proc peekFirst*[T](deq: Deque[T]): lent T {.inline.} =
  258. ## Returns the first element of `deq`, but does not remove it from the deque.
  259. ##
  260. ## **See also:**
  261. ## * `peekFirst proc <#peekFirst,Deque[T]_2>`_ which returns a mutable reference
  262. ## * `peekLast proc <#peekLast,Deque[T]>`_
  263. runnableExamples:
  264. let a = [10, 20, 30, 40, 50].toDeque
  265. assert $a == "[10, 20, 30, 40, 50]"
  266. assert a.peekFirst == 10
  267. assert len(a) == 5
  268. emptyCheck(deq)
  269. result = deq.data[deq.head]
  270. proc peekLast*[T](deq: Deque[T]): lent T {.inline.} =
  271. ## Returns the last element of `deq`, but does not remove it from the deque.
  272. ##
  273. ## **See also:**
  274. ## * `peekLast proc <#peekLast,Deque[T]_2>`_ which returns a mutable reference
  275. ## * `peekFirst proc <#peekFirst,Deque[T]>`_
  276. runnableExamples:
  277. let a = [10, 20, 30, 40, 50].toDeque
  278. assert $a == "[10, 20, 30, 40, 50]"
  279. assert a.peekLast == 50
  280. assert len(a) == 5
  281. emptyCheck(deq)
  282. result = deq.data[(deq.tail - 1) and deq.mask]
  283. proc peekFirst*[T](deq: var Deque[T]): var T {.inline, since: (1, 3).} =
  284. ## Returns a mutable reference to the first element of `deq`,
  285. ## but does not remove it from the deque.
  286. ##
  287. ## **See also:**
  288. ## * `peekFirst proc <#peekFirst,Deque[T]>`_
  289. ## * `peekLast proc <#peekLast,Deque[T]_2>`_
  290. runnableExamples:
  291. var a = [10, 20, 30, 40, 50].toDeque
  292. a.peekFirst() = 99
  293. assert $a == "[99, 20, 30, 40, 50]"
  294. emptyCheck(deq)
  295. result = deq.data[deq.head]
  296. proc peekLast*[T](deq: var Deque[T]): var T {.inline, since: (1, 3).} =
  297. ## Returns a mutable reference to the last element of `deq`,
  298. ## but does not remove it from the deque.
  299. ##
  300. ## **See also:**
  301. ## * `peekFirst proc <#peekFirst,Deque[T]_2>`_
  302. ## * `peekLast proc <#peekLast,Deque[T]>`_
  303. runnableExamples:
  304. var a = [10, 20, 30, 40, 50].toDeque
  305. a.peekLast() = 99
  306. assert $a == "[10, 20, 30, 40, 99]"
  307. emptyCheck(deq)
  308. result = deq.data[(deq.tail - 1) and deq.mask]
  309. template destroy(x: untyped) =
  310. reset(x)
  311. proc popFirst*[T](deq: var Deque[T]): T {.inline, discardable.} =
  312. ## Removes and returns the first element of the `deq`.
  313. ##
  314. ## See also:
  315. ## * `popLast proc <#popLast,Deque[T]>`_
  316. ## * `shrink proc <#shrink,Deque[T],int,int>`_
  317. runnableExamples:
  318. var a = [10, 20, 30, 40, 50].toDeque
  319. assert $a == "[10, 20, 30, 40, 50]"
  320. assert a.popFirst == 10
  321. assert $a == "[20, 30, 40, 50]"
  322. emptyCheck(deq)
  323. dec deq.count
  324. result = move deq.data[deq.head]
  325. deq.head = (deq.head + 1) and deq.mask
  326. proc popLast*[T](deq: var Deque[T]): T {.inline, discardable.} =
  327. ## Removes and returns the last element of the `deq`.
  328. ##
  329. ## **See also:**
  330. ## * `popFirst proc <#popFirst,Deque[T]>`_
  331. ## * `shrink proc <#shrink,Deque[T],int,int>`_
  332. runnableExamples:
  333. var a = [10, 20, 30, 40, 50].toDeque
  334. assert $a == "[10, 20, 30, 40, 50]"
  335. assert a.popLast == 50
  336. assert $a == "[10, 20, 30, 40]"
  337. emptyCheck(deq)
  338. dec deq.count
  339. deq.tail = (deq.tail - 1) and deq.mask
  340. result = move deq.data[deq.tail]
  341. proc clear*[T](deq: var Deque[T]) {.inline.} =
  342. ## Resets the deque so that it is empty.
  343. ##
  344. ## **See also:**
  345. ## * `shrink proc <#shrink,Deque[T],int,int>`_
  346. runnableExamples:
  347. var a = [10, 20, 30, 40, 50].toDeque
  348. assert $a == "[10, 20, 30, 40, 50]"
  349. clear(a)
  350. assert len(a) == 0
  351. for el in mitems(deq): destroy(el)
  352. deq.count = 0
  353. deq.tail = deq.head
  354. proc shrink*[T](deq: var Deque[T], fromFirst = 0, fromLast = 0) =
  355. ## Removes `fromFirst` elements from the front of the deque and
  356. ## `fromLast` elements from the back.
  357. ##
  358. ## If the supplied number of elements exceeds the total number of elements
  359. ## in the deque, the deque will remain empty.
  360. ##
  361. ## **See also:**
  362. ## * `clear proc <#clear,Deque[T]>`_
  363. ## * `popFirst proc <#popFirst,Deque[T]>`_
  364. ## * `popLast proc <#popLast,Deque[T]>`_
  365. runnableExamples:
  366. var a = [10, 20, 30, 40, 50].toDeque
  367. assert $a == "[10, 20, 30, 40, 50]"
  368. a.shrink(fromFirst = 2, fromLast = 1)
  369. assert $a == "[30, 40]"
  370. if fromFirst + fromLast > deq.count:
  371. clear(deq)
  372. return
  373. for i in 0 ..< fromFirst:
  374. destroy(deq.data[deq.head])
  375. deq.head = (deq.head + 1) and deq.mask
  376. for i in 0 ..< fromLast:
  377. destroy(deq.data[deq.tail])
  378. deq.tail = (deq.tail - 1) and deq.mask
  379. dec deq.count, fromFirst + fromLast
  380. proc `$`*[T](deq: Deque[T]): string =
  381. ## Turns a deque into its string representation.
  382. runnableExamples:
  383. let a = [10, 20, 30].toDeque
  384. assert $a == "[10, 20, 30]"
  385. result = "["
  386. for x in deq:
  387. if result.len > 1: result.add(", ")
  388. result.addQuoted(x)
  389. result.add("]")