deques.nim 13 KB

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