deques.nim 14 KB

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