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 len*[T](deq: Deque[T]): int {.inline.} =
  74. ## Returns the number of elements of `deq`.
  75. result = deq.count
  76. template emptyCheck(deq) =
  77. # Bounds check for the regular deque access.
  78. when compileOption("boundChecks"):
  79. if unlikely(deq.count < 1):
  80. raise newException(IndexDefect, "Empty deque.")
  81. template xBoundsCheck(deq, i) =
  82. # Bounds check for the array like accesses.
  83. when compileOption("boundChecks"): # `-d:danger` or `--checks:off` should disable this.
  84. if unlikely(i >= deq.count): # x < deq.low is taken care by the Natural parameter
  85. raise newException(IndexDefect,
  86. "Out of bounds: " & $i & " > " & $(deq.count - 1))
  87. if unlikely(i < 0): # when used with BackwardsIndex
  88. raise newException(IndexDefect,
  89. "Out of bounds: " & $i & " < 0")
  90. proc `[]`*[T](deq: Deque[T], i: Natural): lent T {.inline.} =
  91. ## Accesses the `i`-th element of `deq`.
  92. runnableExamples:
  93. let a = [10, 20, 30, 40, 50].toDeque
  94. assert a[0] == 10
  95. assert a[3] == 40
  96. doAssertRaises(IndexDefect, echo a[8])
  97. xBoundsCheck(deq, i)
  98. return deq.data[(deq.head + i) and deq.mask]
  99. proc `[]`*[T](deq: var Deque[T], i: Natural): var T {.inline.} =
  100. ## Accesses the `i`-th element of `deq` and returns a mutable
  101. ## reference to it.
  102. runnableExamples:
  103. var a = [10, 20, 30, 40, 50].toDeque
  104. inc(a[0])
  105. assert a[0] == 11
  106. xBoundsCheck(deq, i)
  107. return deq.data[(deq.head + i) and deq.mask]
  108. proc `[]=`*[T](deq: var Deque[T], i: Natural, val: sink T) {.inline.} =
  109. ## Sets the `i`-th element of `deq` to `val`.
  110. runnableExamples:
  111. var a = [10, 20, 30, 40, 50].toDeque
  112. a[0] = 99
  113. a[3] = 66
  114. assert $a == "[99, 20, 30, 66, 50]"
  115. checkIfInitialized(deq)
  116. xBoundsCheck(deq, i)
  117. deq.data[(deq.head + i) and deq.mask] = val
  118. proc `[]`*[T](deq: Deque[T], i: BackwardsIndex): lent T {.inline.} =
  119. ## Accesses the backwards indexed `i`-th element.
  120. ##
  121. ## `deq[^1]` is the last element.
  122. runnableExamples:
  123. let a = [10, 20, 30, 40, 50].toDeque
  124. assert a[^1] == 50
  125. assert a[^4] == 20
  126. doAssertRaises(IndexDefect, echo a[^9])
  127. xBoundsCheck(deq, deq.len - int(i))
  128. return deq[deq.len - int(i)]
  129. proc `[]`*[T](deq: var Deque[T], i: BackwardsIndex): var T {.inline.} =
  130. ## Accesses the backwards indexed `i`-th element and returns a mutable
  131. ## reference to it.
  132. ##
  133. ## `deq[^1]` is the last element.
  134. runnableExamples:
  135. var a = [10, 20, 30, 40, 50].toDeque
  136. inc(a[^1])
  137. assert a[^1] == 51
  138. xBoundsCheck(deq, deq.len - int(i))
  139. return deq[deq.len - int(i)]
  140. proc `[]=`*[T](deq: var Deque[T], i: BackwardsIndex, x: sink T) {.inline.} =
  141. ## Sets the backwards indexed `i`-th element of `deq` to `x`.
  142. ##
  143. ## `deq[^1]` is the last element.
  144. runnableExamples:
  145. var a = [10, 20, 30, 40, 50].toDeque
  146. a[^1] = 99
  147. a[^3] = 77
  148. assert $a == "[10, 20, 77, 40, 99]"
  149. checkIfInitialized(deq)
  150. xBoundsCheck(deq, deq.len - int(i))
  151. deq[deq.len - int(i)] = x
  152. iterator items*[T](deq: Deque[T]): lent T =
  153. ## Yields every element of `deq`.
  154. ##
  155. ## **See also:**
  156. ## * `mitems iterator <#mitems.i,Deque[T]>`_
  157. runnableExamples:
  158. from std/sequtils import toSeq
  159. let a = [10, 20, 30, 40, 50].toDeque
  160. assert toSeq(a.items) == @[10, 20, 30, 40, 50]
  161. var i = deq.head
  162. for c in 0 ..< deq.count:
  163. yield deq.data[i]
  164. i = (i + 1) and deq.mask
  165. iterator mitems*[T](deq: var Deque[T]): var T =
  166. ## Yields every element of `deq`, which can be modified.
  167. ##
  168. ## **See also:**
  169. ## * `items iterator <#items.i,Deque[T]>`_
  170. runnableExamples:
  171. var a = [10, 20, 30, 40, 50].toDeque
  172. assert $a == "[10, 20, 30, 40, 50]"
  173. for x in mitems(a):
  174. x = 5 * x - 1
  175. assert $a == "[49, 99, 149, 199, 249]"
  176. var i = deq.head
  177. for c in 0 ..< deq.count:
  178. yield deq.data[i]
  179. i = (i + 1) and deq.mask
  180. iterator pairs*[T](deq: Deque[T]): tuple[key: int, val: T] =
  181. ## Yields every `(position, value)`-pair of `deq`.
  182. runnableExamples:
  183. from std/sequtils import toSeq
  184. let a = [10, 20, 30].toDeque
  185. assert toSeq(a.pairs) == @[(0, 10), (1, 20), (2, 30)]
  186. var i = deq.head
  187. for c in 0 ..< deq.count:
  188. yield (c, deq.data[i])
  189. i = (i + 1) and deq.mask
  190. proc contains*[T](deq: Deque[T], item: T): bool {.inline.} =
  191. ## Returns true if `item` is in `deq` or false if not found.
  192. ##
  193. ## Usually used via the `in` operator.
  194. ## It is the equivalent of `deq.find(item) >= 0`.
  195. runnableExamples:
  196. let q = [7, 9].toDeque
  197. assert 7 in q
  198. assert q.contains(7)
  199. assert 8 notin q
  200. for e in deq:
  201. if e == item: return true
  202. return false
  203. proc expandIfNeeded[T](deq: var Deque[T]) =
  204. checkIfInitialized(deq)
  205. var cap = deq.mask + 1
  206. if unlikely(deq.count >= cap):
  207. var n = newSeq[T](cap * 2)
  208. var i = 0
  209. for x in mitems(deq):
  210. when nimvm: n[i] = x # workaround for VM bug
  211. else: n[i] = move(x)
  212. inc i
  213. deq.data = move(n)
  214. deq.mask = cap * 2 - 1
  215. deq.tail = deq.count
  216. deq.head = 0
  217. proc addFirst*[T](deq: var Deque[T], item: sink T) =
  218. ## Adds an `item` to the beginning of `deq`.
  219. ##
  220. ## **See also:**
  221. ## * `addLast proc <#addLast,Deque[T],sinkT>`_
  222. runnableExamples:
  223. var a = initDeque[int]()
  224. for i in 1 .. 5:
  225. a.addFirst(10 * i)
  226. assert $a == "[50, 40, 30, 20, 10]"
  227. expandIfNeeded(deq)
  228. inc deq.count
  229. deq.head = (deq.head - 1) and deq.mask
  230. deq.data[deq.head] = item
  231. proc addLast*[T](deq: var Deque[T], item: sink T) =
  232. ## Adds an `item` to the end of `deq`.
  233. ##
  234. ## **See also:**
  235. ## * `addFirst proc <#addFirst,Deque[T],sinkT>`_
  236. runnableExamples:
  237. var a = initDeque[int]()
  238. for i in 1 .. 5:
  239. a.addLast(10 * i)
  240. assert $a == "[10, 20, 30, 40, 50]"
  241. expandIfNeeded(deq)
  242. inc deq.count
  243. deq.data[deq.tail] = item
  244. deq.tail = (deq.tail + 1) and deq.mask
  245. proc toDeque*[T](x: openArray[T]): Deque[T] {.since: (1, 3).} =
  246. ## Creates a new deque that contains the elements of `x` (in the same order).
  247. ##
  248. ## **See also:**
  249. ## * `initDeque proc <#initDeque,int>`_
  250. runnableExamples:
  251. let a = toDeque([7, 8, 9])
  252. assert len(a) == 3
  253. assert $a == "[7, 8, 9]"
  254. result.initImpl(x.len)
  255. for item in items(x):
  256. result.addLast(item)
  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("]")